Skip to content

perf(relay): stop indexing the column every control renewal writes - #21286

Merged
Jinwoo-H merged 2 commits into
mainfrom
relay-drop-activity-expiry-index
Sep 17, 2026
Merged

Jinwoo-H merged 2 commits into
mainfrom
relay-drop-activity-expiry-index

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​351 $\color{#cf222e}{\Huge{\mathbf{−}}}$​24 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​327
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​135 $\color{#cf222e}{\Huge{\mathbf{−}}}$​19 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​116

ELI5

Relay keeps a row for every live connection saying when it expires. Phones refresh that row constantly, about 471 times a second across the fleet. The database also kept a sorted lookup table over the "when does this expire" column, so every single refresh had to update that sorted table too.

Only one thing ever read the sorted table: a cleanup job that runs twice a minute. That job is perfectly happy reading all 14,800 rows directly, which takes less than a millisecond. So we were paying on every refresh to save nothing.

This removes the sorted table, and gives each page of rows a bit of spare room so a refresh can be written in place instead of somewhere new.

What Changed

Nothing changes for anyone using Orca. This is a write-amplification fix inside Relay's database.

Two statements, both in POSTGRES_SCHEMA_MIGRATIONS:

  • DROP INDEX IF EXISTS relay_assignment_activity_expiry
  • ALTER TABLE relay_assignment_activity_leases SET (fillfactor = 70)

The mechanism is Postgres's heap-only-tuple (HOT) optimisation. An UPDATE can rewrite a row inside its existing page, touching no index at all, but only if two things hold: no indexed column changed, and the page has room for the second version. Renewals broke the first condition, because expires_at was indexed and expires_at is exactly what a renewal writes. Removing the index fixes that, but the default fillfactor of 100 leaves a freshly filled page with no free space, so the second condition still failed and the update still moved to a new page.

Measured on a fresh postgres:16-alpine over 14,800 representative rows, updating every row and reading WAL LSN deltas plus pg_stat_user_tables:

variant HOT WAL per renewal
index, fillfactor 100 (today) 0% 371 B
index, fillfactor 70 0% 246 B
no index, fillfactor 100 0.5% 298 B
no index, fillfactor 70 100% 80 B

Dropping the index alone is not the win; it is the precondition for the win. Both statements together take a renewal from 371 to 80 bytes of WAL, a 4.6x reduction on a write path that is roughly 15% of the instance's WAL.

Supporting changes in @orca-cloud/postgres-schema, both so that neither statement can take a lock on a warm boot or crash an instance on the migration boot:

  • A reloption lock-target kind, so the pre-check can ask whether fillfactor=70 is already set before sending an ALTER TABLE that would take a lock.
  • An index-by-name lock-target kind for the DROP INDEX. A DROP INDEX names no table, so the existing index check could not serve it; this one resolves by name through the search_path with relkind = 'i', which is how the DROP itself resolves, and skips when the index is absent.
  • A schema-deferrable marker, read from a statement's leading comment. A lock timeout on a marked statement logs orca_relay_postgres_schema_object_deferred and leaves the statement unapplied rather than failing the boot. Both statements here carry it; everything else keeps the old contract of failing loudly.

Why

Why this index can go. I checked every statement in cloud/apps/relay/src that touches this table. Exactly one filters on expires_at without a primary-key prefix: the release-expired-activity-leases sweep in assignment-store.ts, one of ten cleanup steps the director runs every 30 seconds. Every other reader looks the row up by its primary key, by cell_id, or aggregates the whole table. renewControlActivity, the 471/s path, finds its row by primary key and never consults this index.

The sweep's new plan, measured:

Seq Scan on relay_assignment_activity_leases  (cost=0.00..654.00 rows=1)
  Rows Removed by Filter: 14800
  Buffers: shared hit=469
  Execution Time: 0.697 ms

469 buffers, all cache hits, 0.7 ms, once every 30 seconds. The sweep also carries two NOT EXISTS anti-joins, so the index was never the dominant term anyway. The table already gets seq-scanned on operational paths that filter by cell_id, which has no index either.

Why fillfactor 70 rather than another value. 70 is where the measurement converges to 100% HOT with margin. A row is ~100 bytes against an 8 KB page, so 30% reserved is several rows of headroom per page. It costs heap size on a table whose indexes (31 MB) already outweigh its heap (7 MB), and in the measurement the table got smaller, not larger, because it stopped bloating.

Why not DROP INDEX CONCURRENTLY. It would need the schema runner to guarantee no surrounding transaction, and it waits on every transaction that can see the index, which is an unbounded wait on a busy instance. Plain DROP INDEX takes ACCESS EXCLUSIVE, but only to unlink a catalog entry, and POSTGRES_LOCK_TIMEOUT_MS (1000 ms) already bounds how long boot waits for it. It happens once.

Why not keep the index and only change fillfactor. Measured at 0% HOT across four rounds. A changed indexed column forbids HOT no matter how much page space is free.

Why a new pre-check kind instead of letting the ALTER TABLE run unchecked. relay-schema-lock-targets.test.ts enforces that nothing taking a relation lock reaches a warm boot without a catalog pre-check, and ALTER TABLE ... SET does take one (SHARE UPDATE EXCLUSIVE). Exempting it would have meant weakening that census. The reloption kind compares the whole name=value pair against pg_class.reloptions, so changing 70 to some other value re-runs rather than skipping forever.

Why the DROP INDEX needs its own pre-check and a deferral, not an exemption. It is true that once the index is gone the statement takes no lock, because Postgres resolves the name before it locks and IF EXISTS on a missing name is a notice. But that only describes the steady state. On the one boot that matters the index is still there, all 28 directors reach the statement at once, and it needs ACCESS EXCLUSIVE on a table written ~475/s against a 1000 ms lock_timeout. The runner throws on a lock timeout with no retry, which is right for a statement the boot depends on and wrong here: a failed boot restarts the instance, which re-queues the same DDL behind the same writers.

So the statement is in the census like any other lock-taking statement, with a pre-check that makes it disappear after the first success, and a marker that turns a lost lock race into a logged deferral instead of a restart. IF EXISTS is required by the parser for the same reason it is on DROP CONSTRAINT: a bare DROP on a missing index is an error the server should raise.

Linked Issue

Fixes #

Visual Proof

N/A - a database schema change with no user-visible surface. The measurements above are the evidence.

Testing

Ran against a fresh postgres:16-alpine container, removed afterwards.

  • cloud/apps/relay: pnpm test with ORCA_RELAY_TEST_POSTGRES_URL set. 86 files, 784 passed, 1 skipped. Without a database, 65 files, 671 passed. cloud/apps/push, the other consumer of the schema runner, is 139 passed. The Postgres-backed relay-schema-catalog-precheck-postgres.test.ts is the one that matters: it asserts a warm boot issues zero lock-taking statements, which only holds if the new reloption pre-check works.
  • cloud/packages/postgres-schema: pnpm test, 108 passed, up from 87.
  • cloud: pnpm typecheck and pnpm lint clean across all 7 projects.

End-to-end boot checks against a real server, beyond the suite:

  • Cold boot on an empty database, then a second boot. Second boot logs orca_relay_postgres_schema_object_present for fillfactor=70 and sends no ALTER TABLE. Resulting state: reloptions = {fillfactor=70}, and the only index on the table is its primary key.
  • Upgrade path, the production shape: created relay_assignment_activity_expiry by hand and reset fillfactor to the default, then booted. The boot dropped the index and set fillfactor, ending at idx=0, reloptions={fillfactor=70}.

Two test files failed on a second run against an already-populated database and passed on a fresh one; that is a known property of this suite, not related to this change.

Platforms: the change is server-side SQL, applied by Relay at boot on Linux (Cloud Run). No client, no path handling, no shell.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Added: the concurrent-drop race in the schema runner; the deferral path, including that it fires only on a lock timeout, that an unmarked statement still fails, that the marker is read only from a leading comment, and that the boot keeps going after a deferral so nothing behind it is skipped; the index-by-name and reloption target shapes, including a changed fillfactor value, a refused multi-option SET, a refused multi-index DROP, and a bare DROP with no IF EXISTS; and pins in the relay census that exactly these two statements are deferrable and that nothing re-creates an index on expires_at.

The decisive one runs against a real server: with the index recreated and the table held in ACCESS EXCLUSIVE by another session, both statements defer, the boot completes, the index is verifiably still there, and a second run with the lock released drops it and sets fillfactor.

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Rollout and locking. On the migration boot every director sees the index and sends the drop. ACCESS EXCLUSIVE for the drop is a catalog unlink, held for microseconds, but the wait for it is the exposure, bounded at 1000 ms by the existing lock_timeout. Three outcomes are now all safe: the winner drops it; a loser that raced past the name resolution gets 42704, which the runner treats as already-applied; a loser that cannot get the lock at all gets 55P03, which it logs as deferred and carries on, leaving the work for its next boot. Every boot after the first sends neither statement, because both are pre-checked.

A stall that keeps the lock unavailable therefore costs one extra boot cycle per director, not a crash loop. Nothing else about the boot changes, and no other statement becomes deferrable.

Fillfactor takes effect gradually. Setting the parameter does not rewrite existing pages. Pages adopt it as they refill, so the table converges over its own renewal cycle, minutes at 471/s. An operator can make it immediate with pg_repack, but nothing here requires that, and a VACUUM FULL would take ACCESS EXCLUSIVE for the length of a table rewrite and should not be used on the live instance.

Rollback is re-creating the index with CREATE INDEX CONCURRENTLY and reverting the commit. The RULE comment beside SCHEMA already forbids adding a brand-new index to the schema without building it out of band first, and that still holds.

Backwards compatibility. No wire change, no client change. A director running the previous image against a database where the index is already gone is fine: nothing in the old code names the index, and its sweep just seq-scans.

SQLite. Both statements live in POSTGRES_SCHEMA_MIGRATIONS, which the SQLite path does not run. The CREATE INDEX is removed from the shared SCHEMA, so new SQLite databases simply never create it; an existing local file keeps a harmless leftover.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

relay_assignment_activity_expiry indexes expires_at on
relay_assignment_activity_leases, and expires_at is what every control
renewal updates: ~471 calls/s, all of them non-HOT because a changed
indexed column forbids HOT. The index has one reader, the 30s expiry
sweep, which seq-scans the whole 14.8k-row table in under a millisecond.

Drop it, and set fillfactor to 70 so a renewal has room for a second
row version on its own page. Measured on postgres:16-alpine over 14.8k
rows, WAL bytes per renewal and HOT ratio:

  index, fillfactor 100 (today)     0% HOT   371 B
  index, fillfactor 70              0% HOT   246 B
  no index, fillfactor 100        0.5% HOT   298 B
  no index, fillfactor 70         100% HOT    80 B

Both are needed: the index makes HOT illegal, and the default fillfactor
leaves no page space to make it possible.

Neither statement can use the catalog pre-check as it stood. DROP INDEX
IF EXISTS resolves the name before it locks, so once the index is gone
it costs a catalog miss and takes no lock on the table - pinned in the
lock-target census as the one exempt statement. ALTER TABLE SET does
take a lock, so it gets a new 'reloption' target kind that asks
pg_class.reloptions for the name=value pair, keeping the invariant that
no lock-taking statement reaches a warm boot unchecked.
@pullfrog

pullfrog Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

This run was cancelled 🛑

The workflow was cancelled before completion. Please check the link below for details.

Pullfrog  | View workflow run | via Pullfrog | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The relay schema removes the activity lease expiry index and sets fillfactor = 70. Schema lock targets support index-by-name and exact reloption values. Schema application skips error 42704 for absent conditional index drops and defers marked statements after lock timeouts. Tests cover catalog checks, migrations, lock targets, classification, and deferred retries.

Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to 01fca

Valid semicolon-terminated schema migrations can fail during boot with an unparsed lock-target error. Accept terminal semicolons before merging.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 10 functions across 10 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the primary performance change: removing the index maintained on the column updated during control renewals.
Description check ✅ Passed The description is detailed and covers the required explanation, changes, rationale, testing, visual proof, compatibility considerations, and checklist. The required Linked Issue field is incomplete b…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

…lock timeout

The drop had no catalog pre-check, so it was sent on every boot, and a
55P03 from it was fatal: apply-postgres-schema throws on a lock timeout
with no retry. On the migration boot that combination is a crash loop.
All 28 directors reach the same DROP INDEX at once, it needs ACCESS
EXCLUSIVE on a table written ~475/s with lock_timeout at 1s, and a boot
that fails restarts the instance to re-queue the same DDL behind the
same writers.

Two changes:

- A new 'index-by-name' lock target. A DROP INDEX names no table, so the
  existing index check could not serve it; this one resolves by name
  through the search_path with relkind = 'i', which is how the DROP
  itself resolves, and skips when absent. DROP INDEX now counts as
  lock-taking in the census, so it is covered rather than exempt, and
  IF EXISTS is required the way it is on DROP CONSTRAINT.

- A 'schema-deferrable' marker, read from a statement's leading comment.
  A 55P03 on a marked statement logs
  orca_relay_postgres_schema_object_deferred and leaves the statement
  unapplied instead of failing the boot; the next boot re-sends it. Both
  activity-lease migrations carry it. Everything else keeps the old
  contract and still fails loudly. SchemaApplySummary gains a deferred
  count so a boot that skipped work is distinguishable from one with
  nothing to do.

Verified against a real server: with the index present and the table
held in ACCESS EXCLUSIVE by another session, both statements defer, the
boot completes, nothing is half-applied, and the next boot finishes the
job. A warm boot now sends neither statement at all.
@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

Addressed the review condition in 01fca873fb.

The drop now has a catalog pre-check (index-by-name: resolves by name through the search_path with relkind = 'i', skips when absent), and DROP INDEX counts as lock-taking in the census rather than being exempt. A 55P03 on either of the two activity-lease migrations now logs orca_relay_postgres_schema_object_deferred and leaves the statement for the next boot instead of failing the boot; every other statement keeps the old fail-loudly contract. SchemaApplySummary gained a deferred count.

Proof against a real server, not just unit tests: with the index recreated and the table held in ACCESS EXCLUSIVE by another session, both statements defer, the boot completes, the index is verifiably still present, and the next run with the lock released finishes the job. A warm boot sends neither statement.

Suites: relay 784 passed with Postgres, postgres-schema 108, push 139, pnpm typecheck clean.

@Jinwoo-H
Jinwoo-H merged commit 8e8a9b3 into main Sep 17, 2026
24 checks passed
@Jinwoo-H
Jinwoo-H deleted the relay-drop-activity-expiry-index branch September 17, 2026 20:53

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟠 Major · Accept a trailing statement terminator. · schema-lock-target.ts:131-137

cloud/packages/postgres-schema/src/schema-lock-target.ts:131-137
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Accept a trailing statement terminator.

applyPostgresSchema passes each statement to requireSchemaLockTarget without removing semicolons. sqlWithoutComments also preserves them. Therefore, DROP INDEX IF EXISTS i; and ALTER TABLE t SET (fillfactor = 70); fail their respective regexes, then match MUST_PARSE and throw unparsed_schema_lock_target.

relayPostgresSchemaStatements removes separators only from SCHEMA.split(';'). It appends POSTGRES_SCHEMA_MIGRATIONS unchanged, so statement splitting does not guarantee that semicolons are absent. Accept an optional terminal semicolon in both patterns and cover both forms in parser tests.

Proposed fix
-const DROP_INDEX = new RegExp(`^DROP\\s+INDEX\\s+(?:CONCURRENTLY\\s+)?IF\\s+EXISTS\\s+${QUALIFIED}\\s*$`, 'i')
+const DROP_INDEX = new RegExp(
+  `^DROP\\s+INDEX\\s+(?:CONCURRENTLY\\s+)?IF\\s+EXISTS\\s+${QUALIFIED}\\s*;?\\s*$`,
+  'i'
+)

 const SET_RELOPTION = new RegExp(
   `^ALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?${QUALIFIED}\\s+` +
-    `SET\\s+\\(\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*([A-Za-z0-9_.]+)\\s*\\)\\s*$`,
+    `SET\\s+\\(\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*([A-Za-z0-9_.]+)\\s*\\)\\s*;?\\s*$`,
   'i'
 )

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 4da1f5bf-daba-41e9-9f3e-7b45a5f3e5d7

📥 Commits

Reviewing files that changed from the base of the PR and between 106f882 and 01fca87.

📒 Files selected for processing (9)
  • cloud/apps/relay/src/database.ts
  • cloud/apps/relay/src/relay-schema-catalog-precheck-postgres.test.ts
  • cloud/apps/relay/src/relay-schema-lock-targets.test.ts
  • cloud/packages/postgres-schema/src/apply-postgres-schema.test.ts
  • cloud/packages/postgres-schema/src/apply-postgres-schema.ts
  • cloud/packages/postgres-schema/src/catalog-object-precheck.ts
  • cloud/packages/postgres-schema/src/index.ts
  • cloud/packages/postgres-schema/src/schema-lock-target.test.ts
  • cloud/packages/postgres-schema/src/schema-lock-target.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • cloud/packages/postgres-schema/src/apply-postgres-schema.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.

ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…tablyai#21286)

* perf(relay): stop indexing the column every control renewal writes

relay_assignment_activity_expiry indexes expires_at on
relay_assignment_activity_leases, and expires_at is what every control
renewal updates: ~471 calls/s, all of them non-HOT because a changed
indexed column forbids HOT. The index has one reader, the 30s expiry
sweep, which seq-scans the whole 14.8k-row table in under a millisecond.

Drop it, and set fillfactor to 70 so a renewal has room for a second
row version on its own page. Measured on postgres:16-alpine over 14.8k
rows, WAL bytes per renewal and HOT ratio:

  index, fillfactor 100 (today)     0% HOT   371 B
  index, fillfactor 70              0% HOT   246 B
  no index, fillfactor 100        0.5% HOT   298 B
  no index, fillfactor 70         100% HOT    80 B

Both are needed: the index makes HOT illegal, and the default fillfactor
leaves no page space to make it possible.

Neither statement can use the catalog pre-check as it stood. DROP INDEX
IF EXISTS resolves the name before it locks, so once the index is gone
it costs a catalog miss and takes no lock on the table - pinned in the
lock-target census as the one exempt statement. ALTER TABLE SET does
take a lock, so it gets a new 'reloption' target kind that asks
pg_class.reloptions for the name=value pair, keeping the invariant that
no lock-taking statement reaches a warm boot unchecked.

* fix(relay): pre-check the activity-expiry drop and let it defer on a lock timeout

The drop had no catalog pre-check, so it was sent on every boot, and a
55P03 from it was fatal: apply-postgres-schema throws on a lock timeout
with no retry. On the migration boot that combination is a crash loop.
All 28 directors reach the same DROP INDEX at once, it needs ACCESS
EXCLUSIVE on a table written ~475/s with lock_timeout at 1s, and a boot
that fails restarts the instance to re-queue the same DDL behind the
same writers.

Two changes:

- A new 'index-by-name' lock target. A DROP INDEX names no table, so the
  existing index check could not serve it; this one resolves by name
  through the search_path with relkind = 'i', which is how the DROP
  itself resolves, and skips when absent. DROP INDEX now counts as
  lock-taking in the census, so it is covered rather than exempt, and
  IF EXISTS is required the way it is on DROP CONSTRAINT.

- A 'schema-deferrable' marker, read from a statement's leading comment.
  A 55P03 on a marked statement logs
  orca_relay_postgres_schema_object_deferred and leaves the statement
  unapplied instead of failing the boot; the next boot re-sends it. Both
  activity-lease migrations carry it. Everything else keeps the old
  contract and still fails loudly. SchemaApplySummary gains a deferred
  count so a boot that skipped work is distinguishable from one with
  nothing to do.

Verified against a real server: with the index present and the table
held in ACCESS EXCLUSIVE by another session, both statements defer, the
boot completes, nothing is half-applied, and the next boot finishes the
job. A warm boot now sends neither statement at all.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant