Prompt
How do I run reporting queries without hurting production PostgreSQL?
Latest observation
To run reporting queries on PostgreSQL without hurting production, the main goal is to keep heavy reads off the primary and make any unavoidable reads cheaper and safer.
Best option: use a replica for reporting
The safest approach is:
- Set up a read replica / standby
- Point reporting jobs, BI tools, and ad hoc analytics to the replica
- Keep the primary focused on writes and latency-sensitive queries
This avoids:
- competing for CPU
- blowing out cache on the primary
- causing slowdowns from long sequential scans or sort-heavy queries
- holding locks that interfere with application work
Important tradeoff
A replica may be:
- slightly behind the primary
- unavailable during failover/recovery
- impacted by long-running reports too, just not on the primary
If reports must be exact to the latest transaction, you may need to accept some primary load or build a reporting pipeline.
If you must query production directly
Use safeguards so reports don’t become incidents.
1) Put hard time limits on queries
Use:
statement_timeoutto prevent runaway querieslock_timeoutto avoid waiting too long on locks
Example:
SET statement_timeout = '30s';
SET lock_timeout = '5s';
2) Limit resource usage
For reporting sessions, reduce the chance of large memory spills or excessive parallelism.
Examples:
SET work_mem = '32MB';
SET max_parallel_workers_per_gather = 2;
Be careful: too much work_mem multiplied by many queries can also hurt memory.
3) Run reports in off-peak hours
If possible:
- schedule heavy reports overnight
- avoid running them during peak traffic
4) Make queries index-friendly
Avoid:
SELECT *- functions on indexed columns in
WHERE - leading wildcard searches like
LIKE '%foo' - huge cross joins
- unnecessary
ORDER BY
Prefer:
- selective filters
- covering indexes where useful
- pre-aggregated data when possible
Example:
-- Better
SELECT customer_id, sum(amount)
FROM orders
WHERE created_at >= now() - interval '7 days'
GROUP BY customer_id;
5) Use pagination carefully
Avoid offset pagination for large datasets:
LIMIT 100 OFFSET 1000000
This gets slower as offset grows.
Prefer keyset pagination:
WHERE id > $last_seen_id
ORDER BY id
LIMIT 100
6) Read-only transactions
For reporting connections:
BEGIN READ ONLY;
This prevents accidental writes and can make intent clear.
7) Cancel bad queries automatically
Set up monitoring to detect:
- long-running queries
- high temp file usage
- sequential scans on large tables
- blocking
Tools:
pg_stat_activitypg_stat_statements- logging slow queries with
log_min_duration_statement
Use a reporting architecture when reporting grows
If reports are frequent or expensive, consider:
- ETL to a warehouse: Snowflake, BigQuery, Redshift, etc.
- materialized views in PostgreSQL
- summary tables updated on a schedule
- logical replication into a reporting database
- columnar analytics store for BI workloads
Materialized views
Good for dashboards where “near real-time” is enough.
CREATE MATERIALIZED VIEW daily_sales AS
SELECT date_trunc('day', created_at) AS day, sum(amount) AS total
FROM orders
GROUP BY 1;
Refresh during low traffic:
REFRESH MATERIALIZED VIEW daily_sales;
Use CONCURRENTLY if you need reads during refresh, though it has extra requirements and cost.
Operational protections
A few practical guards help a lot:
- Use a separate DB user for reports
- Set per-role settings:
statement_timeoutidle_in_transaction_session_timeoutsearch_path
- Restrict access to only replica/reporting databases
- Monitor replica lag and report freshness
- Test report queries on production-sized data before release
Example per-role:
ALTER ROLE reporting_user SET statement_timeout = '30s';
ALTER ROLE reporting_user SET idle_in_transaction_session_timeout = '1min';
Rule of thumb
If a query:
- scans millions of rows
- sorts large result sets
- groups by high-cardinality columns
- runs for minutes
- is used by BI dashboards or analysts
then it should not run on the primary unless you have no alternative.
If you want, I can also give you:
- a PostgreSQL production reporting checklist, or
- a sample setup for read replicas + role limits + timeouts.