Sub topic 5
Refreshing without blocking readers using CONCURRENTLY
This chapter assumes you can create a materialized view and run a plain REFRESH MATERIALIZED VIEW. It also assumes you know what a unique index is and can read basic psql output. You will learn why a plain refresh blocks readers, how CONCURRENTLY avoids that, what it requires, and what it costs.
Why a plain refresh blocks readers
A plain REFRESH MATERIALIZED VIEW sales_daily takes an ACCESS EXCLUSIVE lock on the view. That is the strongest table lock in PostgreSQL. While it is held, even a SELECT on the view has to wait.
The refresh re-runs the defining query and replaces the stored contents. If the query takes 40 seconds, every reader of the view waits up to 40 seconds. This is acceptable for a nightly report. It is a problem for a dashboard that queries the view all day.
REFRESH MATERIALIZED VIEW CONCURRENTLY removes that wait. Readers keep seeing the old contents until the refresh commits, and then they see the new contents.
How CONCURRENTLY works
With CONCURRENTLY, PostgreSQL does not overwrite the stored rows in place. It follows these steps:
- It runs the defining query and writes the result into a temporary table.
- It compares the temporary table with the current contents of the view. The comparison uses the unique index to match rows.
- It works out which rows were inserted, updated, or deleted.
- It applies only those differences to the materialized view.
During the whole process the lock is EXCLUSIVE, not ACCESS EXCLUSIVE. An EXCLUSIVE lock blocks writes and other refreshes, but it allows SELECT. Because nobody can write to a materialized view directly, "blocks writes" in practice means "blocks other refreshes and DDL on the view".
The requirements
CONCURRENTLY only works if the view meets these conditions.
- The view must already be populated. A view created
WITH NO DATAneeds a plainREFRESHfirst. - The view must have at least one unique index.
- That unique index must cover plain columns only. An index on an expression, such as
lower(name), does not count. - The unique index must cover all rows. A partial index, one with a
WHEREclause, does not count.
If these are not met, PostgreSQL stops with an error and does nothing.
A worked example
This example uses the sales_daily view from earlier chapters. The query groups by order_date, so each day value appears once. That makes day a natural unique key.
CREATE UNIQUE INDEX sales_daily_day_idx ON sales_daily (day);
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily;Now try it without the index to see the error. This sketch uses a second view built on the same table.
CREATE MATERIALIZED VIEW sales_by_customer AS
SELECT customer_id, sum(total) AS revenue
FROM orders
GROUP BY customer_id;
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_by_customer;The refresh fails with an error like this:
ERROR: cannot refresh materialized view "public.sales_by_customer" concurrently
HINT: Create a unique index with no WHERE clause on one or more columns of the materialized view.Fix it by adding the index and running the refresh again:
CREATE UNIQUE INDEX sales_by_customer_idx ON sales_by_customer (customer_id);
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_by_customer;Seeing that readers are not blocked
You can check this yourself with two psql sessions.
In session A, start a refresh. To make it last long enough, use a view whose query is slow. In session B, run a SELECT while session A is working:
-- Session A
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily;
-- Session B, at the same time
SELECT * FROM sales_daily ORDER BY day DESC LIMIT 7;Session B returns at once with the old rows. If you repeat the test with a plain REFRESH, session B waits until session A finishes.
You can also look at lock modes while a refresh runs:
SELECT l.mode, l.granted, l.pid
FROM pg_locks AS l
WHERE l.relation = 'sales_daily'::regclass;Choosing the unique index
The unique index is not only a requirement. It is how PostgreSQL matches old rows to new rows, so its choice affects correctness and speed.
- Use the grouping columns of the query when the view is an aggregate. For
sales_dailythat isday. - For a view that joins tables, use the primary key columns of the rows you want to identify. If the view has no natural key, you may need to add one to the query, for example a
row_number()column or a key from one of the base tables. - Each combination of values in the index columns must be unique in the query result. If the query returns duplicates, the refresh fails.
A composite unique index works too, as shown here:
CREATE MATERIALIZED VIEW sales_by_day_customer AS
SELECT order_date AS day, customer_id, sum(total) AS revenue
FROM orders
GROUP BY order_date, customer_id;
CREATE UNIQUE INDEX sales_by_day_customer_idx
ON sales_by_day_customer (day, customer_id);Trade-offs and costs
CONCURRENTLY is not free. Compare the two modes before you pick one.
| Aspect | Plain `REFRESH` | `REFRESH ... CONCURRENTLY` |
|---|---|---|
| Lock on the view | `ACCESS EXCLUSIVE` | `EXCLUSIVE` |
| Readers during refresh | Blocked | Not blocked |
| Unique index required | No | Yes |
| Works on an unpopulated view | Yes | No |
| Work done | Rewrite whole view | Build temp table, diff, apply changes |
| Speed | Usually faster | Usually slower |
| Dead rows left behind | None, the storage is replaced | Yes, from updates and deletes |
Three points follow from this table.
First, a concurrent refresh is usually slower. It does the same query work, and then also builds a temporary table and compares it with the view. When most rows change, the comparison does not save anything, and a plain refresh can be much faster.
Second, a concurrent refresh produces dead rows. Updated and deleted rows stay in the view's storage until vacuum removes them. A frequently refreshed view can bloat if autovacuum does not keep up. Check it with pg_stat_user_tables:
SELECT relname, n_live_tup, n_dead_tup, last_autovacuum
FROM pg_stat_user_tables
WHERE relname = 'sales_daily';Third, the refresh needs room for the temporary table. A view with millions of rows needs matching temporary disk space.
Only one refresh at a time
Two concurrent refreshes of the same view cannot run together. The second one waits for the first to finish, because both need the EXCLUSIVE lock. This matters when you schedule refreshes. If a refresh takes 20 minutes and you schedule one every 15 minutes, the jobs queue up behind each other.
Two ways to avoid this:
- Schedule refreshes less often than a refresh takes to run.
- Set a
lock_timeoutin the refresh job so a job gives up instead of waiting.
SET lock_timeout = '5s';
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily;If the lock cannot be obtained in 5 seconds, the statement fails with a lock timeout error and your scheduler can log it.
Running it inside a transaction
A plain REFRESH MATERIALIZED VIEW can be run inside a transaction block. This is a difference you may hit in migration tools. Check the behavior on your PostgreSQL version with a test before you rely on it in a migration that wraps everything in BEGIN and COMMIT.
Also keep in mind that readers see a consistent snapshot. A reader that began a query before the refresh committed keeps seeing the old rows for the length of that query. Readers that start after the commit see the new rows.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `cannot refresh materialized view ... concurrently` with a hint about a unique index | No usable unique index | Create a unique index on plain columns, with no `WHERE` clause |
| `materialized view ... has not been populated` | View was created `WITH NO DATA` | Run a plain `REFRESH MATERIALIZED VIEW` once |
| `new data for materialized view ... contains duplicate rows without any null columns` | The query returns rows that are equal on every column | Change the query so that rows are distinct, for example with `GROUP BY` or `DISTINCT` |
| Refresh waits and never starts | Another refresh holds the lock | Check `pg_stat_activity`, then lengthen the interval or set `lock_timeout` |
| View grows over time | Dead rows from repeated concurrent refreshes | Tune autovacuum for the view, or run `VACUUM` on it |
Putting it together
A safe pattern for a production dashboard view has four parts. Create the view and populate it. Add a unique index. Refresh with CONCURRENTLY from a scheduler. Set lock_timeout so jobs do not pile up. The next chapters cover the scheduling part in detail.
CREATE MATERIALIZED VIEW sales_daily AS
SELECT order_date AS day,
count(*) AS orders,
sum(total) AS revenue
FROM orders
GROUP BY order_date;
CREATE UNIQUE INDEX sales_daily_day_idx ON sales_daily (day);
SET lock_timeout = '5s';
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily;Exercise
A materialized view called topproducts is built from a query that joins orderitems to products and groups by productid. You run REFRESH MATERIALIZED VIEW CONCURRENTLY topproducts and get an error about a unique index. You then create INDEX topproductsidx ON topproducts (productid) WHERE revenue > 0, a unique index, and the error stays the same. Why, and what should you do?
Show answer
A unique index with a WHERE clause is a partial index, and CONCURRENTLY requires a unique index that covers all rows. Drop the partial index and create a unique index on productid with no WHERE clause. The query groups by productid, so product_id is unique in the result and the index will be valid.
Exercise
A materialized view refreshes by a plain REFRESH in 8 seconds. About 90 percent of its rows change in every refresh, and it is read only by a nightly batch job at 02:00, with the refresh running at 01:00. Should you switch to CONCURRENTLY? Give two reasons.
Show answer
No. First, nobody reads the view during the refresh, so there are no readers to block and CONCURRENTLY gives no benefit. Second, with most rows changing, a concurrent refresh would build a temporary table, compare it with the view, and apply nearly every row as a change, which is slower and leaves dead rows that vacuum must clean up.