How to Refresh Materialized Views Without Downtime
Pick CONCURRENTLY with a unique index, or dual-view atomic swap, schedule incremental windows, and monitor staleness with recorded refresh times.
On this page
Introduction
A materialized view is a query whose answer is stored as a table, giving analytic speed to aggregation, joins, and rollups that would take minutes to compute on demand. The stored answer drifts from the source data, and reconciling that drift is an operational problem with real failure modes: the naive REFRESH takes an ACCESS EXCLUSIVE lock, so every reader, including health checks, queues behind it for the entire recomputation, and a refresh that grows with the data turns a maintenance job into a rolling outage. PostgreSQL offers two ways out. REFRESH MATERIALIZED VIEW CONCURRENTLY refreshes without blocking readers, at the cost of requiring a unique index and taking longer. The dual-view pattern swaps two identically-shaped views atomically inside a transaction, at the cost of a rename dance and some naming discipline. This tutorial implements both, schedules refreshes as bounded jobs, and instruments staleness so the product, not the database, defines how old is too old.
The locking problem
Understand what the plain refresh actually does before choosing the alternative. REFRESH MATERIALIZED VIEW executes the defining query, computes the full result set, and replaces the view contents. To replace contents safely it takes an ACCESS EXCLUSIVE lock: no reader may even see the view during the swap. For a small view the lock is milliseconds and nobody notices. As the source grows, the query inside the refresh grows with it, and the exclusive lock is held for the full recomputation, because the swap only happens at the end. Readers pile up, connection pools exhaust, health checks time out, and the application reports an outage that the database considers routine maintenance. Worse, lock waits queue behind each other, so a slow analytical query that started before the refresh can push the effective blocking window far beyond the refresh itself. Any refresh strategy that preserves uptime must either avoid the exclusive lock entirely or make the lock so short that queuing cannot build up. Both production patterns in this tutorial follow that principle.
Refresh concurrently
CONCURRENTLY is the built-in answer: it computes the new result into a temporary table, diffs it against the current contents using a unique index, and applies inserts, updates, and deletes row by row. Readers see the old contents throughout and the new contents immediately after commit; there is never a moment where the view is empty or locked. The requirements are a unique index covering every row of the view, and a slower wall-clock refresh, since the diff adds work proportional to changed rows.
CREATE MATERIALIZED VIEW order_daily_summary AS
SELECT date_trunc('day', created_at) AS day,
customer_id,
count(*) AS order_count,
sum(total_cents) AS revenue_cents
FROM orders
GROUP BY 1, 2;
CREATE UNIQUE INDEX ON order_daily_summary (day, customer_id);
REFRESH MATERIALIZED VIEW CONCURRENTLY order_daily_summary;
The unique index must cover the entire view, which forces an honest design decision: the view needs a natural key. A summary keyed by day and customer has one; a summary over a ragged dimensional rollout may not, and forcing an artificial unique column undermines the diff. In that case the dual-view pattern below is the better fit. Note also that CONCURRENTLY cannot run inside a transaction block, so the job runner must issue it as a top-level statement with its own timeout.
Dual-view atomic swap
The swap pattern builds the new answer under a temporary name and renames it into place inside one transaction. Renames take only brief catalog locks, so the reader-visible interruption is milliseconds regardless of how long the rebuild took. The cost is operational discipline: two objects exist, and every consumer references the stable name through a plain view.
BEGIN;
DROP MATERIALIZED VIEW IF EXISTS summary_build;
CREATE MATERIALIZED VIEW summary_build AS
SELECT date_trunc('day', created_at) AS day,
customer_id,
count(*) AS order_count,
sum(total_cents) AS revenue_cents
FROM orders
GROUP BY 1, 2;
CREATE UNIQUE INDEX ON summary_build (day, customer_id);
DROP VIEW summary;
CREATE VIEW summary AS SELECT * FROM summary_build;
-- next cycle rebuilds into the other name and swaps again
COMMIT;
A common refinement alternates two build names so the rebuild never starts by dropping the live object’s twin, and some teams add the index before the swap so consumers inherit it with the rename. Because the rebuild runs as an ordinary query, it can use all the tuning available to any query: parallelism, work_mem, and a statement timeout that bounds the job. The pattern trades the database’s built-in diffing for full control of the swap instant, which matters when consumers must never observe a partially updated answer, since CONCURRENTLY applies row-level changes that a reader can observe mid-flight.
Schedule as a bounded job
Either refresh belongs to a job runner, not a cron habit, and the job needs four properties. Lock awareness: before starting, check pg_locks or simply attempt the refresh, and serialize refreshes of the same view with an advisory lock so two schedulers cannot pile diff work on one object. A statement timeout: set locally per job, sized from the observed refresh duration with headroom, so a refresh that degrades with data growth fails loudly at the job layer instead of holding locks or workers indefinitely. A window derived from the source: refresh more often than the data changes materially, because refreshing an unchanged view is wasted IO, and less often than the product tolerance for staleness, measured next. And telemetry: export duration, rows changed, and outcome for every run, because a refresh whose duration doubles in a month is telling you about the source query’s query plan before an incident does.
SELECT pg_try_advisory_lock(hashtext('refresh:order_daily_summary')) AS acquired;
SET LOCAL statement_timeout = '10min';
REFRESH MATERIALIZED VIEW CONCURRENTLY order_daily_summary;
SELECT pg_advisory_unlock(hashtext('refresh:order_daily_summary'));
Incremental windows instead of full rebuilds
When the source has a reliable updated_at or append-only structure, the refresh does not need to recompute history that cannot have changed. The incremental pattern maintains the view by merging only the recent window: delete the affected partitions of the summary, re-insert them from the source rows in that window, and do it inside one transaction so readers see the old answer or the new one. For a daily summary, refreshing the trailing three days covers late-arriving corrections in most domains, and the refresh cost becomes constant instead of growing with table size. This works only when the window assumption is documented and enforced: if rows older than the window can be corrected by a backfill job, that job must trigger a full refresh for the affected range. Backfills that forget this are the standard way incremental views become silently wrong, and the staleness monitor below catches it only if it tracks per-row age rather than a single refresh timestamp.
Monitor staleness explicitly
The product decides acceptable staleness, and the system must measure it, not assume it. The simplest instrument is a refresh stamp: the refresh job writes the completion timestamp to a one-row metadata table in the same transaction as the swap, and dashboards and alerting compute age against it. The subtler instrument for incremental views is per-row age, the maximum source timestamp represented in the view, because a refresh can succeed while the window assumption quietly excludes late data.
UPDATE mv_metadata
SET last_refresh_at = now(),
last_source_max = (SELECT max(updated_at) FROM orders)
WHERE view_name = 'order_daily_summary';
Alert on two conditions: age exceeding the product tolerance, which means the scheduler or the refresh itself failed, and age jumping backward after a deploy, which means someone changed the window or the view definition and the contract shifted. Both are cheap to compute and both catch failure modes that row counts and job success booleans miss.
Common pitfalls
- Plain REFRESH on a read-heavy view. The exclusive lock queues every reader for the full recomputation; this is the rolling outage in its pure form.
- Missing unique index. CONCURRENTLY refuses to run, and teams fall back to the plain refresh under pressure.
- No statement timeout on the job. A degrading refresh holds workers and locks indefinitely instead of failing loudly.
- Two schedulers refreshing one view. Concurrent diff work doubles cost and can deadlock; serialize with an advisory lock.
- Incremental windows without backfill hooks. Late corrections outside the window make the view silently wrong.
- No staleness metric. Freshness is a product contract; unmeasured, it is discovered by users.
Conclusion
Materialized views buy analytic speed with a freshness debt that must be serviced deliberately. Use REFRESH CONCURRENTLY with a honest unique key for read-heavy summaries where row-level mid-flight changes are acceptable. Use the dual-view swap when consumers must observe only whole answers or the view lacks a natural key. Run the refresh as a bounded, serialized, telemetry-emitting job with a statement timeout, and adopt incremental windows when the source has a reliable recency signal, provided backfills trigger the full path. Finally, publish staleness as a measured number with an alert, because the product’s tolerance for old data is a contract, and contracts need instruments, not assumptions.
Sources: PostgreSQL: REFRESH MATERIALIZED VIEW, PostgreSQL: materialized views, PostgreSQL: CREATE MATERIALIZED VIEW.
FAQ
- Why does REFRESH CONCURRENTLY need a unique index?
- The concurrent algorithm compares old and new results row by row to apply differences, and it identifies rows using the unique index. Without one, the database cannot apply the diff safely while readers are querying.
- Is CONCURRENTLY always slower than plain REFRESH?
- It takes longer than a plain refresh in wall-clock terms because it computes a diff, but it never blocks readers. For views with heavy read traffic, the plain refresh’s exclusive lock costs far more than the extra refresh time.
- How do I know how stale the view is?
- Store the refresh timestamp as a column in the view or in a small metadata table updated in the same transaction, then expose the age to dashboards and alerting.
Report a problem with this articleOpens a pre-filled issue on GitHub.