Rebuilding a large table without locking readers
Issue #935. Rebuilding gold.mdm_person (13.8M rows)
used to freeze every API query on people for minutes, and on every other build it lost its trigram search index. This
page explains why and gives the pattern any large table model should use.
Why it locked
dbt's table materialization (dbt/include/global_project/macros/materializations/models/table.sql) does this:
- Build
<model>__dbt_tmpwith the model's SQL. This doesn't lock the live table. - Build the indexes declared in the model's
indexesconfig on<model>__dbt_tmp. This doesn't lock the live table either. - Rename the live table to
<model>__dbt_backupand rename<model>__dbt_tmpin. Each rename takes an ACCESS EXCLUSIVE lock. - Run the post_hooks, then commit.
- Drop
<model>__dbt_backup.
Three things went wrong:
- An index built in a post_hook builds under the lock.
mdm_personbuilt its GINgin_trgm_opsindex in a post_hook, so the index ran in step 4, after the renames. Every query onmdm_personwaited while it built over 13.8M names. - A named index in a post_hook vanishes on every other build. In step 4 the backup still owns the index name, so
CREATE INDEX IF NOT EXISTS <name>finds the name taken and skips. Step 5 then drops the index along with the backup.ensure_search_indexes(on-run-end) rebuilt it after the run, so the index alternated between "built under the lock" and "missing until the backstop". This is the "trigram index drops after a rebuild" seen before. - The renames wait with no limit, and readers queue behind them. A rename can't get its lock while any query is reading the table. While the rename waits, every new query waits behind it too. Two overlapping builds of the same model made this worse.
The pattern
For a large table model:
{{
config(
materialized='table',
indexes=[
{'columns': ['state_code'], 'type': 'btree'},
{'columns': ['full_name gin_trgm_ops'], 'type': 'gin'} -- operator classes pass through as written
],
pre_hook=["{{ swap_guard() }}"],
post_hook=[
"{{ swap_guard_check() }}"
]
)
}}
-
Indexes go in
indexes, never in a post_hook. dbt builds them on the tmp table before the swap, under a generated name, so they never collide with the backup's and never build under the lock. -
swap_guard()(dbt_project/macros/swap_guard.sql) is an in-transaction pre-hook. It does three things:- It takes
pg_try_advisory_xact_lockon the relation, so a second build of the same model fails immediately with "swap_guard: another build of … is running". - It records the transaction id.
- It records the rename timeout (10s) as a transaction-local setting.
The project's
postgres__rename_relation(same file) applies that timeout immediately before eachALTER TABLE … RENAME. A swap that can't get its lock then rolls back fast (the old table keeps serving) instead of queuing every reader. The timeout covers only the renames, not the build. A model with contract foreign keys creates its tmp table withreferences <parent>, which waits for sibling models building against the same parent. A timeout over the whole build would fail them for nothing, as review of #938 pointed out. Outside a guarded transaction the setting is empty, and the override is exactly dbt's own rename.All of this ends at the swap's COMMIT, so none of it applies to the backup drop or to other models.
- It takes
-
swap_guard_check()must be the first post-hook. It runs right after the renames, before COMMIT, and does two things:- It fails the build if the swap didn't run in the transaction
swap_guard()started. - It ends the rename timeout (
lock_timeoutback to default, the setting cleared), so nothing after the renames inherits it.
- It fails the build if the swap didn't run in the transaction
-
Statements that lock other tables go in after-commit post-hooks:
{'sql': "ALTER TABLE … ADD CONSTRAINT … FOREIGN KEY …", 'transaction': false}. A foreign key needs a lock on the parent table, which a parallel model may hold for many minutes (grant's build holdsmdm_organizationfor 20-30). Inside the swap transaction theALTERwaits while still holding the swapped table's exclusive lock, so every reader waits too. After commit it holds only a lock that doesn't block reads.In #938's builds,
mdm_bridge_org_jurisdiction's in-transactionADD CONSTRAINT … REFERENCES mdm_organizationwaited ongrantand timed out twice. The four bridge models' foreign keys are now after-commit hooks. -
pg_trgmis created once per invocation inon-run-start(dbt_project.yml). Trigram indexes now build before any hook, so a per-model hook would come too late on a fresh warehouse. -
No before-begin hooks (
{'sql': ..., 'transaction': false}inpre_hook) on these models. dbt sends a literalcommit;before those, and psycopg2 then never opens another transaction on that connection. Every later statement autocommits, including the two renames, so they stop being atomic, andSET LOCALand transaction locks end with their own statement. The first version of this fix had one (forCREATE EXTENSION), and it cost two things:- A reader caught between the renames got
relation "gold.mdm_person" does not exist. lock_timeoutnever applied, so one swap waited 365 seconds with readers queued behind it.
swap_guard_check()now catches this. An after-commit post-hook ('transaction': falseinpost_hook) is harmless. - A reader caught between the renames got
-
ensure_search_indexesfinds an index by definition when its entry has amatchkey, so it counts the config index (generated name) as present instead of building a duplicate. Only valid, non-partial indexes count. -
Incremental models (
grant_opportunity): dbt buildsindexesonly when the table is first created or full-refreshed. An index added to the config later appears only after--full-refresh.
Primary keys added in hooks (#941)
Models whose key isn't a dbt contract constraint add it with gold_pk_post_hook('<cols>'). On a model whose contract
already declares the key, the hook finds it and does nothing. Two rules, both learned the hard way
(#941):
- Pass the hook as a string:
post_hook=["{{ gold_pk_post_hook('word') }}"]. Called directly insideconfig()(post_hook=[gold_pk_post_hook('word')]), the macro renders when the model is parsed, when{{ this }}still points atpublic.<model>instead of thegoldtable. All 15 callers had that bug. Wherepublic.<model>was a serving view or missing, the hook failed the build; where it was a table that already had a key, it silently did nothing. - Don't name the key. Post-hooks run after the old table is renamed to
__dbt_backup, which still owns an index called<model>_pkey. A fixed name fails every rebuild after the first ("relation … _pkey already exists"). The macro now leaves the name to Postgres. A new key (add primary key …) gets<model>_pkey, or_pkey1while the backup holds the first. A key built from an existing unique index (add primary key using index …) takes that index's name, which for a dbtindexesentry is a generated hash.
Measured on mdm_person (local warehouse, 25 Nov 2026)
| Check | Result |
|---|---|
| Full rebuild (13.8M rows, ~5 min) with a reader querying every 0.1s | 2,812 reads, slowest 0.087s, none over 1s, no errors; swap_guard_check passed; nothing new in the Postgres log (no "does not exist", no "no transaction in progress") |
| Trigram index after consecutive builds | exactly one; ensure_search_indexes built nothing |
| Second build started during the first's index phase | refused in 0.12s ("another build … is running"); the first finished normally |
| A reader transaction holds the table open through the swap | the swap rolled back after 10s ("canceling statement due to lock timeout"); 3,012 reads, slowest 11.5s, none errored; the old table kept serving all rows; no tmp or backup table and no advisory lock left behind; re-run the model afterwards |
The cost is the timeout case: a build that can't swap within 10 seconds fails and must be re-run. That's the intended trade-off, since the alternative was freezing every reader for as long as the blocking query ran.
Other models
#938 moved every other model's index hooks into indexes
config (29 files), plus event_uncontested_item's unnamed one. It also gave swap_guard to the largest tables:
| Model | Size |
|---|---|
event_documents | 8.5 GB |
grant | 4.1 GB |
mdm_organization | 2.2 GB |
mdm_bridge_org_jurisdiction | 1.7 GB |
mdm_bridge_person_jurisdiction | 1.5 GB |
bills | 0.8 GB |
mdm_organization_nonprofit | 0.7 GB |
event_documents' ANALYZE became an after-commit post-hook, so it no longer runs under the swap's lock. No model in
dbt_project/models builds an index in a hook any more.
Still open: views over a rebuilt table
The swap is atomic and short, but dbt then runs drop table … __dbt_backup cascade. Views are bound to the old table's
OID, so the views over it (the public serving views, and dbt view models) are dropped with it:
- the
publicones come back only whenpublish_public_servingruns at the end of the run; - unselected dbt view models don't come back at all after a selected run.
Readers of public views can therefore still get "relation does not exist" while a rebuild runs. That is
#940. Until it's fixed, after a selected run, recreate the
views with ./scripts/dbt.sh run --select config.materialized:view.