← Back to PostgreSQL, page 5

postgresql-0096 · Hard senior

A dashboard runs heavy aggregate queries every few seconds and slows the primary. Design a better approach.

Stop recomputing totals from raw rows on every refresh. Precompute: incremental summary tables updated by batch jobs or triggers, materialized views refreshed on a schedule, or a time-bucketed roll-up of recent data. Serve dashboards from a replica or an analytics store, and cache results at the application layer for the refresh interval users actually need.

Full answer

Questions to settle first: how fresh must the numbers be (seconds, minutes, hourly), how many users view them, and which filters they apply.

Options, by freshness and cost:

  • Application cache: cache each dashboard query result for 30 to 60 seconds; many viewers then cost one query per interval.
  • Roll-up tables: a job aggregates new raw rows into per-minute or per-hour buckets (insert ... on conflict do update), so dashboards scan thousands of summary rows instead of millions of events. Keep a watermark of the last processed id or time so the job is incremental and idempotent.
  • Materialized views refreshed CONCURRENTLY on a schedule, suitable when a full recompute is acceptable every few minutes.
  • Trigger-maintained summaries for exact real-time totals, accepting write overhead and contention on hot summary rows.
  • Read replicas or a column store (for example a separate analytics database or extension) for ad-hoc exploration, keeping the primary for transactions.

Also check the queries themselves: missing indexes on time columns, aggregates over all history when the screen shows the last 24 hours, and per-widget queries that could be one. Measure the dashboard's share of primary load in pg_stat_statements before and after. This is a design item with nothing to run.

Key points

  • Agree on freshness needs first
  • Cache results per refresh interval
  • Incremental roll-up tables
  • Scheduled materialized view refreshes
  • Move analytics off the primary

Common mistakes

  • Recomputing from raw events on every refresh
  • Real-time triggers where minute-level freshness suffices

Follow-ups

  • How would you make the roll-up job idempotent?
  • When would you add a dedicated analytics database?

Tips

  • Start with freshness requirements