skip to content

What does a non-blocking refresh of a materialized view actually cost, and why does applying it as a diff need a unique row key?

level: seniorimportance: should knowfreq 44%

answer

  1. same recompute, different apply step
  2. a side copy nobody reads yet
  3. diff-and-apply versus build-and-swap
  4. the key pairs old row with new
  5. recompute floor means go incremental

basics

~20 s

A non-blocking refresh still recomputes the full query into a side copy, then diffs it into the live copy or swaps it in, so readers keep old rows meanwhile. Diffing needs a unique key to pair old and new rows.

solid answer

~50 s

A blocking refresh rewrites the stored rows in place: readers wait for it, or, where an engine truncates and reloads without atomicity, briefly see an empty or partial view. A **non-blocking refresh** leaves the live copy alone until the end. It recomputes the *entire* defining query into a side copy, then either **diffs and applies** the difference as ordinary inserts, updates and deletes in one transaction, or **swaps** the side copy in under a brief lock. Readers see the old rows, then the new ones, never a mix. The diff needs a **stable row identity**: a unique key pairs each new row with its old counterpart, while with duplicate rows nothing says which copy changed. The bill is the full recompute plus the diff and per-row index and dead-version work, or a full second copy for a swap. When the recompute alone misses the staleness budget, move to incremental maintenance.

code

pseudocode · 12 lines
pseudocode
-- non-blocking refresh, diff-and-apply form
side := run(view_definition)          -- full recompute, invisible to readers
begin transaction
  for each key k in keys(side) + keys(live):
    old := live.row(k)
    new := side.row(k)
    if old is missing:   insert new into live
    elif new is missing: delete old from live
    elif old <> new:     replace old with new in live
    -- old = new: no write, no dead version
commit                                -- readers switch from old rows to new here
drop side

go deeper

for a junior

Know that a refresh recomputes the stored result, that the simple form can block readers while it runs, and that a non-blocking form lets them keep reading the previous rows.

for a middle

Explain the side copy and the two ways to apply it, diff-and-apply and build-and-swap, what readers see in each, and why the diff needs a unique key.

for a senior

Weigh the costs: the full recompute either way, the diff join, per-row index and dead-version work versus a second copy, a swap lock queuing behind readers, and keys that stay stable across runs.

for a principal

Decide from the staleness budget and the recompute cost when no full-refresh method can work, and move the workload to incremental refresh or a maintained summary with its write-path cost stated.

## Two ways to replace a materialized view's rows A **materialized view** stores the result rows of its defining query, so a refresh has two jobs: compute the new result, and replace the old rows with it. Every *full* refresh does the first job the same way: it re-executes the whole defining query, however little of the base data changed. Refresh methods differ in the second job, and that decides who is blocked and what the refresh costs. - **Blocking (in-place) refresh.** Empty or overwrite the stored rows and write the new result into the same object. Cheap in raw work, but readers must not be shown a half-written object. - **Non-blocking refresh.** Build the new result in a **side copy** that no reader sees, and touch the live copy only at the end, by one of two methods: - **diff-and-apply**: compare the side copy with the live copy and apply only the differences as ordinary row changes inside one transaction; - **build-and-swap**: point the view at the side copy under a brief exclusive lock, then discard the old copy. ## What readers see | Method | Readers during the refresh | At the end | |---|---|---| | In-place rebuild under an exclusive lock | Wait for the whole refresh | See the new rows | | Non-atomic truncate and reload (some engines or modes) | May see an empty or partly loaded view | See the new rows | | Diff-and-apply in one transaction | Keep reading the old rows | Switch to the new rows atomically at commit | | Build-and-swap | Keep reading the old copy | Switch at the swap | The swap hides a trap. Its brief exclusive lock must wait for readers already using the old copy, and in many engines new readers queue behind a waiting exclusive lock. One long report can therefore stall a "non-blocking" refresh and every query behind it, so the swap step needs a lock timeout. ## What a non-blocking refresh costs 1. **The full recompute, unchanged.** *Non-blocking* describes how the result is applied, not how it is computed. A defining query that takes 20 minutes still takes 20 minutes. 2. **Space for the side copy.** A swap needs a complete second copy plus its indexes; a diff needs at least a temporary copy of the new result. 3. **The diff itself.** Matching the side copy against the live copy is a join over every row of both. 4. **Per-row apply work.** Each changed row is written as ordinary DML: log records, maintenance of every index on the view and, in multi-version engines, a dead version per updated or deleted row that cleanup must reclaim later. 5. **Longer wall-clock time.** When most rows change, diff-and-apply does more work than rewriting the object once, so it pays off when a small share of rows changes per refresh. A swap avoids per-row apply work and dead versions, but it rebuilds every index on the new copy and pays for a full second copy on every run. ## Why diff-and-apply needs a stable row key To apply a difference, the refresh must decide for every row whether it **replaces** an existing row, is **new**, or has **vanished**. A **unique key** on the view, usually the grouping columns of an aggregate such as `(store_id, sale_date)`, turns that into a one-to-one join: the same key with different values is an update, a key only in the new result is an insert, a key only in the old rows is a delete. Without uniqueness the pairing is ambiguous: if two identical rows exist and one of them should change, nothing says which. Engines that implement diff-and-apply therefore typically demand a unique key on the view and refuse the refresh without one, and a hand-rolled diff job needs the same key for the same reason. The key must also be **stable across refreshes**. If it is a row number generated inside the query, or the result carries a value that changes on every run, every new row differs from its predecessor and the "diff" rewrites the whole view at the highest possible price. ## When incremental maintenance beats any full refresh Every method above shares one cost floor: the full recompute. Change the maintenance model, not the apply method, when: - the **recompute alone exceeds the staleness budget**: a 20-minute query cannot back a view that must be at most 5 minutes old, blocking or not; - the **base data is large and changes a little** per interval, so most of the recompute reproduces rows that did not change; - the **aggregate is additive** (`SUM`, `COUNT`), so a base-row change can be applied as a delta to one summary row. The options are engine-supported **incremental refresh**, which reads recorded base-table changes, or a **summary table** kept current by triggers or application code. Both move cost onto the write path, restrict which query shapes can be maintained, and on a narrow grouping make concurrent writers contend for the same summary row, so they are a deliberate trade rather than a free upgrade. ## How to argue it Name the side copy, the two apply methods and what readers see in each; say plainly that non-blocking does not mean incremental; explain the unique key as row pairing; and finish with the recompute floor that makes incremental maintenance the next step.

  • Why can a non-blocking refresh take longer than a blocking refresh of the same view?
    Both run the same full recompute. The non-blocking form then joins the new result against the live rows and writes every difference as ordinary DML, with log records, index maintenance and, in multi-version engines, a dead version per changed row. When most rows change, that is more work than rewriting the object once, so diff-and-apply pays off only when a small share of rows changes per refresh.
  • A diff-and-apply refresh rewrites every row of the view each time, although only a few hundred base rows change per hour. What would you look for?
    An unstable identity or a volatile column. If the key is a row number generated in the query, or the result includes something like the refresh time or a rank that shifts with every insert, every new row differs from its predecessor and the diff degenerates into a full delete-and-insert. Key the view on its natural grouping columns and move per-run values out of it.
  • When would you choose build-and-swap over diff-and-apply?
    When most rows change on every refresh, when dead versions and index churn on the view are a problem, or when the view has no natural unique key. The swap writes a fresh, compact copy and switches with one brief lock, at the price of a full second copy, rebuilt indexes, and a swap step that must wait for readers already using the old copy.

A non-blocking refresh is printing a complete new timetable in the back office while passengers keep reading the posted one, then either pasting in the changed lines or swapping the whole board. Pasting only works if every line carries a unique route number.

  • Believing a non-blocking refresh recomputes only the rows that changed
  • Assuming the non-blocking form is faster than the blocking one
  • Thinking a diff can pair old and new rows without a unique key
  • Ignoring that a swap's brief lock can queue behind a long reader
  • Putting a per-run timestamp or generated row number in a diffed view
  • Answering a recompute that overruns the staleness budget by changing apply method

context