Sub topic 12
Deciding when a materialized view is the right tool
This chapter assumes you can create, index, and refresh a materialized view, and that you know the difference between REFRESH MATERIALIZED VIEW and REFRESH MATERIALIZED VIEW CONCURRENTLY. It also assumes you can read an EXPLAIN ANALYZE plan. The earlier chapters covered the mechanics. This one covers the decision: whether a materialized view fits a given problem, and what to use when it does not.
What you are trading
A materialized view stores the result of a query as a physical relation. Reads become cheap because the work was done earlier. You pay for this in three ways:
- Staleness. The stored rows are correct only as of the last refresh.
- Refresh cost. Every refresh re-runs the whole query. PostgreSQL has no built-in incremental refresh.
- Storage. The result is a second copy of derived data, and it can have its own indexes.
Every decision below is a judgment about whether the read savings outweigh these three costs.
Three questions to ask first
- Is the query expensive, and is it read often? A query that takes 4 seconds and runs 50,000 times a day is a strong candidate. A query that takes 20 ms and runs twice an hour is not.
- How stale can the answer be? Name a number: "up to 15 minutes old" is a requirement. "Reasonably fresh" is not.
- Can you afford to re-run the query at that frequency? Refresh cost grows with the size of the base data, not with the number of changed rows.
Measuring before you decide
Do not guess whether the query is expensive. Run the defining query on realistic data and look at the time and buffer counts.
EXPLAIN (ANALYZE, BUFFERS)
SELECT order_date AS day,
count(*) AS orders,
sum(total) AS revenue
FROM orders
GROUP BY order_date;The execution time reported here is also your refresh cost, because a refresh runs the same query and then writes the result. A concurrent refresh costs more, since it builds a temporary copy and compares it with the existing rows.
You also need the size of the stored result:
SELECT pg_size_pretty(pg_total_relation_size('sales_daily')) AS total_size;pg_total_relation_size includes indexes. If the view is nearly as large as the base table, you have probably summarized too little. A materialized view pays off most when it is much smaller than the data it summarizes.
A cost estimate you can do on paper
Suppose the defining query takes 4 seconds, and the dashboard reads it 50,000 times a day.
- Without materialization: 50,000 × 4 s = 200,000 s of query time per day.
- With a refresh every 15 minutes: 96 refreshes × 4 s = 384 s of query time per day, plus 50,000 index lookups that take milliseconds.
The materialized view cuts the work by about 99.8%. Now consider the opposite case: a 6-second query read 20 times a day. Refreshing every 15 minutes costs 576 s per day, which is more than the 120 s of work it saves. A plain view, or a refresh scheduled only before the report is needed, would be cheaper.
The rule is that refresh work should be much smaller than the read work it replaces.
Good fits
A materialized view works well when most of these hold:
- The result is an aggregate or a join over a large table, and the result is small.
- The base data is mostly appended to, or changes at a pace the refresh interval can absorb.
- Readers see a defined "as of" time and that is acceptable, such as a daily report or a dashboard.
- Many readers run the same query with the same shape. A single stored result serves all of them.
- You want to index the derived data differently from the base tables.
Poor fits
Avoid a materialized view in these situations:
- Read-your-writes is required. A user places an order and the next page must show it. The view will not have it until the next refresh.
- The query takes parameters. A materialized view has no parameters. If every user asks for a different customer or date range, you would have to store results for all of them, or filter the stored result afterward. Filtering works only if the stored result already contains the needed grain.
- The base table is small or the query is already indexed. Adding a stored copy only adds a refresh job.
- Nearly all of the base data changes between refreshes and you need frequent refreshes. The refresh then re-reads a huge table over and over.
- You need to update individual rows of the result. A materialized view is read-only. You cannot
INSERT,UPDATE, orDELETEits rows.
Knowing how stale the data is
PostgreSQL does not record when a materialized view was last refreshed. pg_matviews tells you whether it is populated, but not when it was populated. If staleness matters to readers or to monitoring, record it yourself.
A tempting approach is to add now() AS refreshed_at to the view definition. Avoid it. Every row then differs on every refresh, so REFRESH ... CONCURRENTLY sees every row as changed and rewrites all of them, which defeats the point of the diff.
A separate one-row table is cheaper:
CREATE TABLE refresh_log (
view_name text PRIMARY KEY,
refreshed_at timestamptz NOT NULL
);
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily;
INSERT INTO refresh_log (view_name, refreshed_at)
VALUES ('sales_daily', now())
ON CONFLICT (view_name) DO UPDATE SET refreshed_at = EXCLUDED.refreshed_at;Run both statements from the same scheduled job. Dashboards can then show "data as of" from refresh_log, and an alert can fire when the timestamp is older than your agreed limit. If the refresh fails, the log row is not updated, so the staleness shows up where you are looking.
Failure modes to plan for
- Blocking refreshes. A plain
REFRESH MATERIALIZED VIEWtakes anACCESS EXCLUSIVElock, so readers wait until it finishes. If the view serves live traffic, useCONCURRENTLY. That requires a unique index, as covered earlier. - Overlapping refreshes. If a refresh takes longer than the schedule interval, a second one queues behind the first. Make the interval comfortably longer than the measured refresh time.
- Silent failure. A scheduled refresh that errors leaves the view stale with no visible symptom. Monitor the
refresh_logtimestamp, not just the job's existence. - Growing refresh time. The refresh scans all the base data every time. A refresh that takes 20 seconds today may take 10 minutes after a year of data. Re-measure periodically.
- Bloat. A concurrent refresh applies deletes and inserts to the existing relation, which leaves dead rows for vacuum to reclaim. A plain refresh rebuilds the relation and does not.
- Permissions. Privileges on a materialized view are separate from privileges on its base tables. Grant
SELECTon the view to the roles that need it. The refresh runs with the view owner's privileges, so the owner needs access to the base tables.
Alternatives and when they win
| Approach | Freshness | Write overhead | Refresh cost | Best when |
|---|---|---|---|---|
| Plain view plus an index on the base table | Always current | None | None, but each read runs the query | The query is fast enough with proper indexes |
| Materialized view | As of the last refresh | None | Full query per refresh | Expensive aggregate, tolerable staleness |
| Summary table updated by a periodic incremental job | As of the last job run | None | Only the recent slice | Append-heavy data where only recent rows change |
| Summary table updated by triggers | Current | Added to every write | None | Freshness required and write rate is moderate |
| Incremental view maintenance extension such as `pg_ivm` | Current | Added to every write | None | You want view semantics with incremental updates and can install the extension |
| Application or external cache | As of the cache time | None | Depends on the cache | Results are parameterized or needed outside the database |
The summary table with an incremental job is the most common step up from a materialized view. It recomputes only the recent days instead of the whole history:
CREATE TABLE sales_daily_summary (
day date PRIMARY KEY,
orders bigint NOT NULL,
revenue numeric(12,2) NOT NULL
);
INSERT INTO sales_daily_summary (day, orders, revenue)
SELECT order_date, count(*), sum(total)
FROM orders
WHERE order_date >= CURRENT_DATE - 1
GROUP BY order_date
ON CONFLICT (day) DO UPDATE
SET orders = EXCLUDED.orders,
revenue = EXCLUDED.revenue;This runs in time proportional to two days of orders, no matter how large orders grows. The cost is correctness work you now own. Orders that arrive late and are dated before yesterday are missed. Rows deleted from orders can leave an obsolete summary row. A materialized view avoids both problems because it recomputes everything. Choose the incremental table only when the full refresh has become too slow, and accept the extra rules that come with it.
Triggers keep a summary perfectly current but add work to every insert, update, and delete on the base table. They can also make concurrent writers contend on the same summary row, for example every order for the same day updating one row.
Quick decision guide
| Situation | Recommendation |
|---|---|
| Nightly report over a year of data, read all day | Materialized view, refreshed after the nightly load |
| Executive dashboard, 15-minute lag acceptable | Materialized view with a unique index and a concurrent refresh every 15 minutes |
| Page that must show a user's own just-placed order | Query the base tables, or update a summary table in the same transaction |
| Daily totals over billions of rows, full refresh takes an hour | Incremental summary table, or `pg_ivm` |
| Query result depends on a user-supplied parameter | Plain query with indexes, or a cache keyed by the parameter |
| Small lookup query that already runs in 5 ms | Neither. Leave it alone. |
Exercise
A reporting query joins orders and order_items, takes 8 seconds, and is read about 30 times per day by analysts who only need data through the end of the previous day. Would you use a materialized view, and how often would you refresh it? Justify with a rough cost comparison.
Show answer
Yes. Staleness of up to a day is acceptable, so one refresh per day, scheduled after the nightly data load, is enough. Without materialization the work is 30 × 8 s = 240 s per day. With the view it is one 8-second refresh (plus a little more for index maintenance) plus 30 millisecond-scale reads. A unique index is only needed if the refresh will run while analysts are querying. In that case use REFRESH MATERIALIZED VIEW CONCURRENTLY, otherwise the plain refresh can run during the quiet window.
Exercise
A storefront shows each customer their "total spent this month" right after checkout. The defining aggregate query is slow. A teammate proposes a materialized view refreshed every minute. Explain why this is a poor fit and name two alternatives.
Show answer
Readers need to see their own purchase immediately, and a view refreshed once a minute can be up to a minute behind, so the customer would not see the order they just placed. Refreshing more often does not fix it, because each refresh re-runs the full aggregate over all customers. Alternatives: maintain a per-customer summary table updated in the same transaction as the order (by trigger or application code), or use an incremental view maintenance extension such as pgivm. A query restricted to one customer with an index on customerid and order_date is a third option if it is fast enough.
Exercise
Why is adding now() AS refreshed_at to a materialized view definition a bad way to track freshness when you refresh with CONCURRENTLY? What is a better approach?
Show answer
now() returns a new value on every refresh, so every row in the new result differs from the stored one. A concurrent refresh computes a row-by-row difference, so it would rewrite every row each time, losing the benefit of the diff and creating dead rows. A better approach is a separate one-row-per-view table, such as refresh_log, that the scheduled job updates after a successful refresh, and which dashboards and monitoring read.