Sub topic 6
Balancing data freshness against refresh cost
This chapter assumes you can create a materialized view, run REFRESH MATERIALIZED VIEW, and add a unique index. It uses the orders table and the sales_daily view from earlier chapters. The aim is to choose a refresh strategy deliberately, not by habit.
Why freshness and cost pull against each other
A materialized view is a snapshot. Between refreshes, the stored rows can differ from what the defining query would return today. The gap is called staleness. You can measure it as the time since the last successful refresh, or as the number of base-table changes the view has not seen.
PostgreSQL has no incremental refresh for materialized views. Every REFRESH re-runs the whole defining query. The cost of a refresh depends on the size of the base data the query reads, not on how many rows changed. A refresh after one new order costs about the same as a refresh after a million.
That gives you two quantities to trade against each other:
- Staleness is how old the data may be when a reader sees it. Readers and the business decide this.
- Refresh cost is the duration of one refresh multiplied by how often you run it. The database pays this in CPU, I/O, and locks.
Refreshing more often lowers staleness and raises cost. Refreshing less often does the opposite.
Put a number on the cost
Start by measuring how long the defining query takes. In psql, turn on timing and run the refresh once:
\timing on
REFRESH MATERIALIZED VIEW sales_daily;Then multiply. Suppose a refresh takes 40 seconds.
| Interval | Refreshes per hour | Refresh work per hour | Share of one session's time |
|---|---|---|---|
| 5 minutes | 12 | 480 s | about 13% |
| 15 minutes | 4 | 160 s | about 4.4% |
| 1 hour | 1 | 40 s | about 1.1% |
Going from 15 minutes to 5 minutes makes data three times fresher and the load three times higher. If readers are fine with 15-minute-old numbers, the extra cost buys nothing.
Use the measured duration as a floor for the interval. If a refresh takes 40 seconds under load, an interval of 30 seconds cannot work. Leave a wide margin, because duration grows as the base table grows.
Know what each refresh mode costs
The two refresh modes pay for freshness in different ways.
Plain REFRESH MATERIALIZED VIEW takes an ACCESS EXCLUSIVE lock on the view. Readers wait until it finishes. It builds the new contents into a fresh file and swaps it in. That makes it the cheaper mode, and it leaves no dead rows behind.
REFRESH MATERIALIZED VIEW CONCURRENTLY builds the new result in a temporary table, compares it with the stored rows, and applies only the differences. Readers keep querying the old contents throughout. The price:
- It needs a unique index on plain columns, covering all rows.
- It is usually slower than a plain refresh, because of the comparison step and the extra temporary storage.
- Deleted and updated rows leave dead tuples, so autovacuum has work to do on the view.
- Two concurrent refreshes of the same view cannot run at the same time. The second one waits.
- It only works on a view that is already populated.
| Mode | Readers during refresh | Relative cost | Requirement |
|---|---|---|---|
| `REFRESH` | Blocked until it ends | Lower | None |
| `REFRESH ... CONCURRENTLY` | Read old contents | Higher | Unique index, view populated |
Choose the plain mode when a short pause is acceptable, for example a nightly report refreshed at 03:00. Choose CONCURRENTLY when the view backs a dashboard that is always in use.
Lock queues make blocking worse than it looks
A plain refresh waits for any running queries on the view to finish before it gets its lock. While it waits, new readers queue behind it. One slow report can therefore stall every other reader of the view, not only the refresh. Setting a lock timeout makes the refresh give up instead of piling up a queue:
BEGIN;
SET LOCAL lock_timeout = '5s';
REFRESH MATERIALIZED VIEW sales_daily;
COMMIT;If the lock is not available within five seconds, the statement fails with an error and the old contents stay in place. Your scheduler can retry at the next interval.
A failed refresh of either kind never leaves a half-updated view. The refresh is a single transaction, so readers see either the old rows or the new ones.
Measure staleness instead of guessing
pg_matviews shows whether a view is populated, but it does not record when the view was last refreshed. If you need to know the age of the data, record it yourself. A small log table and a procedure that wraps the refresh do this:
CREATE TABLE matview_refresh_log (
view_name text PRIMARY KEY,
refreshed_at timestamptz NOT NULL,
duration interval NOT NULL
);
CREATE PROCEDURE refresh_sales_daily()
LANGUAGE plpgsql
AS $$
DECLARE
started timestamptz := clock_timestamp();
BEGIN
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily;
INSERT INTO matview_refresh_log (view_name, refreshed_at, duration)
VALUES ('sales_daily', clock_timestamp(), clock_timestamp() - started)
ON CONFLICT (view_name) DO UPDATE
SET refreshed_at = EXCLUDED.refreshed_at,
duration = EXCLUDED.duration;
END;
$$;
CALL refresh_sales_daily();
SELECT view_name,
now() - refreshed_at AS age,
duration
FROM matview_refresh_log;The procedure assumes the unique index sales_daily_day_idx from the earlier chapter exists. The log row is written in the same transaction as the refresh. If the refresh fails, the log keeps the previous timestamp, so age stays honest.
You can now alert when age exceeds your staleness budget. You can also watch duration over weeks. A steadily rising duration is the early sign that your interval will soon be too short.
Reduce staleness without refreshing more often
If the interval you can afford is longer than readers want to wait, change the design before you add load.
Shrink what each refresh recomputes
Cost follows the amount of data the query scans. Options:
- Limit the view to the window people actually query, for example the last 13 months, instead of all history.
- Pre-aggregate in layers. A view over
sales_dailyis cheap to refresh because it reads a few thousand rows, not millions of orders. - Move expensive joins out of the view if readers could do them at query time on a small result.
Combine stored history with a live tail
Old data rarely changes. Only the recent part needs to be fresh. Store the closed days in a materialized view, and compute the open days live. A plain view stitches the two together:
CREATE MATERIALIZED VIEW sales_daily_closed AS
SELECT order_date AS day,
count(*) AS orders,
sum(total) AS revenue
FROM orders
WHERE order_date < CURRENT_DATE
GROUP BY order_date;
CREATE UNIQUE INDEX sales_daily_closed_day_idx ON sales_daily_closed (day);
CREATE VIEW sales_daily_live AS
SELECT day, orders, revenue
FROM sales_daily_closed
UNION ALL
SELECT order_date, count(*), sum(total)
FROM orders
WHERE order_date > COALESCE((SELECT max(day) FROM sales_daily_closed),
'-infinity'::date)
GROUP BY order_date;CURRENT_DATE is evaluated when the refresh runs, so the stored rows end at the day before that refresh. The live branch starts after the newest stored day, not at today's date. If the refresh runs late after midnight, yesterday is still covered by the live branch, and no day falls into a gap.
This hybrid has its own trade-offs:
- The live branch scans only recent rows, which needs an index on
orders (order_date)to stay fast. - Changes to old orders, such as a late correction dated last week, do not show up until the next refresh.
- The view is more complex to maintain than a single materialized view.
Use it when "today" must be exact and history can be refreshed once a day.
Pick an interval from requirements
Work through these steps in order:
- Ask the readers what staleness they can accept, in minutes. Get a number, not "as fresh as possible".
- Measure one refresh under realistic load, using the mode you plan to run.
- Set the interval at the staleness budget or longer, and at least several times the measured duration.
- Check that the cost per hour fits your spare capacity. If it does not, shrink the query or relax the budget.
- Log refresh age and duration, and review them as the data grows.
A refresh that runs longer than its interval is a warning sign. Runs start to overlap or queue, and the view ends up no fresher than a longer interval would have made it, at a higher cost.
Common mistakes
- Refreshing on a short timer "to be safe". Cost grows linearly with frequency, and freshness may not matter to anyone.
- Using
CONCURRENTLYeverywhere. On a view nobody queries during the refresh window, plain refresh is faster and leaves no dead rows. - Ignoring growth. A refresh that takes 5 seconds today can take 5 minutes after a year of data.
- Leaving no record of the last refresh. Without one, you cannot tell a slow scheduler from a failed one.
Exercise
A materialized view takes 90 seconds to refresh. Product asks for a refresh every 2 minutes so the dashboard looks live. Give two concrete problems with this plan and one alternative design.
Show answer
First, the refresh is busy for 90 of every 120 seconds, which is 75% of one session's time, so the load is very high. Second, any growth in the base table pushes the duration past the interval, so refreshes overlap or queue and the data is no fresher. An alternative is the hybrid design: store closed history in a materialized view refreshed rarely, and compute only the recent rows live in a plain view with UNION ALL. Shrinking the view to the window readers actually need is another valid option.
Exercise
You run REFRESH MATERIALIZED VIEW sales_daily while a long report is still reading the view. A second dashboard query then starts. What happens to the second query, and what setting reduces the impact?
Show answer
The refresh waits for the ACCESS EXCLUSIVE lock until the report finishes, and the second query queues behind the waiting refresh, so it is blocked too. Running SET LOCAL lock_timeout = '5s' before the refresh makes the refresh fail if it cannot get the lock in time, which clears the queue. Using REFRESH MATERIALIZED VIEW CONCURRENTLY avoids the problem, because readers are not blocked, but it needs a unique index on the view.