Sub topic 6
Balancing Data Freshness Against Refresh Cost
This chapter assumes that you know SELECT, aggregate functions, GROUP BY, tables, views, and basic indexes. You should also know how to connect to PostgreSQL with psql or another SQL client.
A materialized view stores the result of a query. Reading it is usually fast because PostgreSQL reads stored rows instead of recalculating the query. The stored result can become stale, however. A materialized view does not automatically change when its source tables change.
Freshness is a design choice
Suppose sales_daily summarizes orders by day. If a new order arrives, the materialized view still shows the old summary until you refresh it.
The required freshness depends on how people use the data:
- A monthly financial report may tolerate data that is several hours old.
- An operations dashboard may need data from the last 15 minutes.
- A fraud detection process may require current data and should not depend on a periodically refreshed materialized view.
- A historical report may never need to refresh after its reporting period closes.
The shorter the freshness interval, the more often PostgreSQL must run the defining query. Frequent refreshes consume CPU, memory, disk I/O, and possibly locks. The source tables may also be busy while the aggregate query scans them.
-- The view is refreshed after the source data changes.
REFRESH MATERIALIZED VIEW sales_daily;A refresh recomputes the materialized view's contents. In the usual form, PostgreSQL replaces the stored result and can prevent ordinary reads from proceeding during part of the operation. The exact duration depends on the query, the amount of data, indexes, and system resources.
Compare freshness policies
Choose a refresh policy by measuring how quickly the data changes and how expensive the query is.
| Policy | Typical use | Main trade-off |
|---|---|---|
| On demand | Reports or administrative queries | Freshness depends on someone running the refresh |
| Every few hours | Large analytical summaries | Lower load, but older data |
| Every 15 minutes | Business dashboards | More load and possible refresh overlap |
| After a batch load | Nightly reporting | Predictable results and predictable cost |
For a scheduled refresh, make sure one refresh can finish before the next one starts. If a refresh takes 25 minutes but the scheduler starts it every 15 minutes, jobs may overlap. Use a job lock, scheduler setting, or separate worker process to prevent concurrent jobs unless you deliberately use PostgreSQL's supported concurrent refresh behavior.
Use concurrent refresh when readers need access
REFRESH MATERIALIZED VIEW CONCURRENTLY allows readers to continue querying the existing contents while PostgreSQL builds the refreshed result. Readers see the old data until the refresh completes, and then they can see the new contents.
Concurrent refresh requires a unique index on the materialized view. The indexed columns must identify each row, and the index must cover all rows without a partial predicate.
CREATE UNIQUE INDEX sales_daily_day_idx
ON sales_daily (day);
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily;The unique index does not make the refresh free. PostgreSQL still computes the new result and compares or merges it with the existing contents. Concurrent refresh can also require more temporary disk space and take longer than a regular refresh. Use it when uninterrupted reads matter more than the additional refresh cost.
Schedule refreshes around workload
PostgreSQL does not include a general built-in scheduler for materialized views. You can use an external scheduler, such as a system timer or an application job, or use the pg_cron extension when it is installed and configured.
SELECT cron.schedule(
'refresh-sales-daily',
'*/15 * * * *',
'REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily'
);A schedule should match the business requirement, not an arbitrary interval. Monitor refresh duration, failed jobs, last refresh time, and the age of the data. If the refresh takes longer as the source tables grow, reassess the interval before jobs begin to overlap.
Know when a materialized view does not fit
A materialized view is a good choice when the query is expensive, the result is read often, and some staleness is acceptable. It is a poor choice when every read must reflect the latest transaction or when the defining query is too expensive to rerun.
Alternatives include a carefully indexed live query, an application-maintained summary table, an incremental aggregation pipeline, or a reporting database populated by batch processing. These options add their own complexity, so compare their freshness, operational cost, correctness, and recovery behavior.
Exercise
A dashboard can show data up to 10 minutes old. A refresh takes two minutes, and readers must remain online. What setup is appropriate?
Show answer
Schedule a refresh every 10 minutes or less, create the required unique index, and use REFRESH MATERIALIZED VIEW CONCURRENTLY. Monitor the refresh duration and prevent overlapping jobs.