Skip to content

PostgreSQL materialized views with concurrent refresh

Use materialized views in PostgreSQL — REFRESH MATERIALIZED VIEW CONCURRENTLY, the unique-index prerequisite, and the operational pattern for dashboards.

A materialized view is a snapshot of a query stored on disk — query it like a table, refresh it on a schedule. The right tool for dashboards, leaderboards, and reporting queries that don’t need second-level freshness but can’t afford to re-run a 30-second aggregation per page view. The trap is the default refresh takes an AccessExclusiveLock; CONCURRENTLY avoids it, but only if you’ve prepared. This article covers the pattern.

How to verify

Look at the view, its index, and the refresh history:

psql -d app -c "\dm+ public.*"
psql -d app -c "SELECT matviewname, ispopulated, definition
                FROM pg_matviews WHERE schemaname='public';"
psql -d app -c "SELECT indexname, indexdef FROM pg_indexes
                WHERE tablename = 'orders_daily_summary';"
psql -d app -c "EXPLAIN (ANALYZE, BUFFERS)
                SELECT * FROM orders_daily_summary
                WHERE day >= current_date - 30;"

A query against a populated matview reads from disk — pg_stat_user_tables shows reads against the matview’s underlying table.

What’s happening

CREATE MATERIALIZED VIEW foo AS SELECT ... runs the query once and stores the result as a regular table-like relation. SELECTs go against the stored data — no recomputation, no joins against the source. REFRESH MATERIALIZED VIEW foo re-runs the query and replaces the stored result; the default refresh takes ACCESS EXCLUSIVE on the matview, blocking reads.

REFRESH MATERIALIZED VIEW CONCURRENTLY foo builds the new result into a temporary table, computes the diff against the existing matview, and applies the diff under a less-blocking lock. SELECTs against the matview keep running. The cost is doubled work (it computes the full result and the diff) and a hard requirement: the matview must have at least one UNIQUE INDEX that covers every column needed to identify a row — otherwise Postgres can’t compute the diff and the command fails.

For dashboards and reports, the right pattern is a matview refreshed every 5-60 minutes by a scheduled job, with CONCURRENTLY so users don’t see blank dashboards during refresh.

The procedure

  1. Create the matview with the eventual unique key in mind:

    CREATE MATERIALIZED VIEW orders_daily_summary AS
    SELECT
      date_trunc('day', created_at)::date AS day,
      tenant_id,
      count(*)                            AS orders,
      sum(total_cents)                    AS revenue_cents,
      count(*) FILTER (WHERE status='paid') AS paid_orders
    FROM orders
    GROUP BY 1, 2
    WITH NO DATA;
    
    CREATE UNIQUE INDEX orders_daily_summary_pk
      ON orders_daily_summary (day, tenant_id);
    
    REFRESH MATERIALIZED VIEW orders_daily_summary;

    WITH NO DATA skips the initial population so you can build the index first — useful when the query is expensive. The unique index on (day, tenant_id) is what makes the concurrent refresh possible.

  2. Schedule the refresh:

    -- pg_cron syntax (run by a scheduler extension)
    SELECT cron.schedule('refresh-orders-daily', '*/15 * * * *',
      $$REFRESH MATERIALIZED VIEW CONCURRENTLY orders_daily_summary$$);

    Or via a systemd timer / cron job on the OS calling psql. We prefer pg_cron because the schedule lives with the database.

  3. For incremental-style refreshes, layer logic in:

    CREATE TABLE orders_daily_summary_t AS
      TABLE orders_daily_summary WITH NO DATA;
    
    INSERT INTO orders_daily_summary_t
    SELECT ... FROM orders WHERE created_at >= current_date - 7
      GROUP BY 1, 2
    ON CONFLICT (day, tenant_id) DO UPDATE SET ...;

    A full matview refresh recomputes everything; for huge source tables it’s better to maintain a regular table with ON CONFLICT DO UPDATE driven by triggers or scheduled jobs.

  4. Query the matview, not the source:

    SELECT day, sum(revenue_cents) / 100 AS revenue
    FROM orders_daily_summary
    WHERE tenant_id = $1 AND day >= current_date - 30
    GROUP BY 1
    ORDER BY 1;

    The dashboard query is millisecond-fast — the heavy lifting happened during refresh.

  5. Monitor refresh duration and lag. A concurrent refresh that takes longer than your refresh interval will queue and possibly stack — measure with pg_stat_user_tables.last_autoanalyze and a custom last_refreshed timestamp column you maintain yourself.

  6. VACUUM the matview. It accumulates dead tuples from each concurrent refresh. Autovacuum handles it, but for very high-frequency refreshes you may need to lower autovacuum_vacuum_scale_factor per matview.

Common pitfalls

  • Concurrent refresh without a unique index fails immediately — verify with \d+ matview_name before relying on it in production.
  • The diff phase of concurrent refresh holds a snapshot — long matview refreshes hold the publisher slot’s WAL retention budget if logical replication is active.
  • Refreshing a matview built on a partitioned table can be expensive; consider per-partition aggregates instead.
  • Matviews aren’t logically replicated to subscribers — refresh on each replica or treat one as authoritative.
  • WITH NO DATA matviews can’t be queried until populated; ensure your bootstrap migration runs REFRESH after CREATE.

In the engagements we run, the matview + concurrent refresh + pg_cron pattern is the default for dashboards and reporting tiles. We size refresh intervals to the actual freshness requirement (15 minutes for ops dashboards, hourly for finance, daily for trends) and pair with a last_refreshed_at column that the UI surfaces. For continuous aggregation on a time-series stack, see TimescaleDB hypertables. For the operating model behind a reporting-heavy Postgres footprint, see managed operations.