HAMZA KAREEM / CONCEPTS hamzawi.dev

Lesson 1352 min read

Materialized View Refresh (CONCURRENTLY)

The Hourly 90-Second Freeze

Databasesdatabases / caching & operations

The symptom

Your dashboard API is healthy: p99 = 120ms. Except at :00 every hour, when every request touching /analytics times out for ~80 seconds. CPU is flat. No slow query in the logs. Then it heals itself.

🔎 Debug step 1 — who is awake at :00?

A cron job:

psql -c "REFRESH MATERIALIZED VIEW daily_revenue;"

Debug step 2 — look at locks, not CPU

SELECT a.query, l.mode, l.granted
FROM pg_locks l JOIN pg_stat_activity a USING (pid)
WHERE l.relation = 'daily_revenue'::regclass;

Output: one AccessExclusiveLock granted to the REFRESH, and 40 plain SELECTs sitting ungranted behind it.

The concept that explains it

A materialized view is not a view. It's a real heap table with a stored query attached.

  • A VIEW = a saved query. Re-executed on every read. Always fresh, always costs you.
  • A MATERIALIZED VIEW = cached rows on disk. Cheap reads, stale data, and someone must pay to rebuild it.

Plain REFRESH rebuilds the whole thing and swaps it in under ACCESS EXCLUSIVE — the same lock level as ALTER TABLE. It conflicts with everything, including SELECT. Your readers didn't get slow; they got queued.

The fix (two lines)

CREATE UNIQUE INDEX daily_revenue_pk ON daily_revenue (day, product_id);
REFRESH MATERIALIZED VIEW CONCURRENTLY daily_revenue;

CONCURRENTLY builds the new result into a temp table, diffs it against the old rows, and applies only INSERT/UPDATE/DELETE. It takes EXCLUSIVE instead of ACCESS EXCLUSIVE, so SELECTs keep running throughout. The unique index is mandatory — that's how Postgres matches old rows to new ones.

What practitioners get wrong

1️⃣ "CONCURRENTLY makes it cheap." No. It's typically 2–3x slower in total work (full query + diff + writes). You traded wall-clock cost for availability, nothing else.

2️⃣ "It refreshes incrementally." No. Postgres re-runs your entire 40-second aggregate every time, even if one row changed. There is no incremental maintenance.

3️⃣ The diff path writes real dead tuples. Hourly CONCURRENTLY refresh on a wide matview = steady bloat; autovacuum has to keep up.

4️⃣ You cannot run CONCURRENTLY on a matview created WITH NO DATA — the first refresh must be a plain one.

5️⃣ Two CONCURRENTLY refreshes of the same matview serialize against each other. If your refresh takes 70 minutes and your cron is hourly, you are building a queue.

6️⃣ Staleness is now part of your API contract. Ship it: store a refreshed_at timestamp and return it in the payload, so the UI can say "as of 14:00" instead of lying.

When to stop using matviews

Rough rule: once refresh time exceeds ~10% of your refresh interval, switch to a rollup table maintained incrementally —

INSERT INTO daily_revenue
SELECT day, product_id, sum(amount) FROM orders
WHERE created_at >= now() - interval '2 hours'
GROUP BY 1,2
ON CONFLICT (day, product_id) DO UPDATE SET amount = EXCLUDED.amount;

Same table, bounded work, no global rebuild.

Your exercise

Take any matview you have (or make one over a table with ~1M rows). Open two psql sessions. In session A run a plain REFRESH MATERIALIZED VIEW; in session B, immediately run SELECT count(*) from it and time it. Then add a unique index, redo it with CONCURRENTLY, and time session B again.

Question to answer for yourself: how long did the plain refresh take vs the CONCURRENTLY one — and which number would you actually put in your on-call runbook?