← Back to SQL, page 22

sql-0429 · Medium mid

A heavy monthly report slows the production database for everyone while it runs. What are the options?

Move the load away from the primary: run the report on a read replica, precompute it with a materialized view or summary table refreshed off-peak, or load data into a separate warehouse built for analytics. Also tune the query itself and, if it must stay on the primary, run it at a quiet time with a statement timeout.

Full answer

Options, from least to most effort:

  1. Tune: check the plan, add an index for the report's filter, and avoid fetching unneeded columns.
  2. Schedule: run it off-peak with statement_timeout so a runaway query is cancelled instead of degrading the service.
  3. Replica: point reporting connections at a replica. Lag of a few seconds is usually fine for monthly reports.
  4. Precompute: a summary table (orders per day per product) updated nightly or incrementally turns a full scan into a small read. PostgreSQL materialized views with REFRESH MATERIALIZED VIEW CONCURRENTLY keep reads available during refresh.
  5. Warehouse: export changes to a columnar analytics store when reports multiply and need joins across many sources.

The right answer depends on freshness needs: a finance close needs exact numbers as of a cut-off time, while a trend chart tolerates a day's delay.

Key points

  • Tune the query first
  • Use replicas for reporting reads
  • Precompute summaries
  • Warehouses suit growing analytics
  • Match freshness to the need

Common mistakes

  • Adding hardware before checking the query
  • Running ad-hoc analytics on the primary at peak

Follow-ups

  • How would you keep a summary table up to date incrementally?
  • What problems can long queries cause on a replica?

Tips

  • Order the options by effort