Full answer
Options, from least to most effort:
- Tune: check the plan, add an index for the report's filter, and avoid fetching unneeded columns.
- Schedule: run it off-peak with
statement_timeoutso a runaway query is cancelled instead of degrading the service. - Replica: point reporting connections at a replica. Lag of a few seconds is usually fine for monthly reports.
- 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 CONCURRENTLYkeep reads available during refresh. - 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