Repository navigation
fix: prevent Postgres migration stampede when a pending migration fails - #1875
Conversation
…ed migrations When a pending migration kept failing on Cloudflare Workers, every cold isolate and every request in warm isolates re-attempted it, queueing on Kysely's blocking pg_advisory_xact_lock inside Postgres and leaking a connection per failed attempt (#1744). - Wrap Postgres dialects (node pg + Hyperdrive) so the migration lock uses pg_try_advisory_xact_lock; a busy lock routes into the existing bounded concurrent-migrator poll instead of parking a connection. - Remember migration failures per database entrypoint and skip re-attempts for 30s; destroy the failed attempt's pool. - Log runtime init failures on the anonymous middleware path instead of swallowing them silently. Closes #1744 Co-Authored-By: Claude Fable 5 <[email protected]>
🦋 Changeset detectedLatest commit: ad24d3c The changes in this PR will be included in the next version bump. This PR includes changesets to release 16 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
@emdash-cms/admin
@emdash-cms/auth
@emdash-cms/auth-atproto
@emdash-cms/blocks
@emdash-cms/cloudflare
@emdash-cms/contentful-to-portable-text
emdash
create-emdash
@emdash-cms/gutenberg-to-portable-text
@emdash-cms/plugin-cli
@emdash-cms/plugin-types
@emdash-cms/registry-client
@emdash-cms/registry-lexicons
@emdash-cms/sandbox-workerd
@emdash-cms/x402
@emdash-cms/plugin-ai-moderation
@emdash-cms/plugin-atproto
@emdash-cms/plugin-audit-log
@emdash-cms/plugin-color
@emdash-cms/plugin-embeds
@emdash-cms/plugin-field-kit
@emdash-cms/plugin-forms
@emdash-cms/plugin-webhook-notifier
commit: |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-playground | ad24d3c | Jul 08 2026, 03:27 PM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-demo-cache | ad24d3c | Jul 08 2026, 03:26 PM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-demo-do | ad24d3c | Jul 08 2026, 03:26 PM |
There was a problem hiding this comment.
Pull request overview
This PR addresses a production failure mode on Postgres-backed deployments (notably Cloudflare Workers/Hyperdrive) where failing pending migrations could trigger repeated concurrent migration attempts, causing advisory-lock queuing, slow requests, and connection leakage.
Changes:
- Introduces a fail-fast Postgres migration lock wrapper (try-lock + bounded polling) and applies it to Postgres dialects.
- Adds per-entrypoint backoff + cleanup on migration failure during runtime DB init to avoid immediate retries and leaked connections.
- Improves observability by logging runtime init failures on the anonymous middleware path, and adds targeted PG/unit/integration test coverage.
Reviewed changes
Copilot reviewed 13 out of 13 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| packages/core/tsdown.config.ts | Ensures the new pg-migration-lock module is built as a published entrypoint. |
| packages/core/tests/utils/test-db.ts | Wraps Postgres test dialects so PG tests exercise the production fail-fast lock behavior. |
| packages/core/tests/unit/database/pg-migration-lock.test.ts | Pins adapter capability preservation and the constructor-name contract used for dialect detection. |
| packages/core/tests/integration/runtime/create.test.ts | Verifies migration-failure backoff prevents immediate retry/reconnection on subsequent create() calls. |
| packages/core/tests/integration/database/migration-lock-pg.test.ts | Adds integration coverage for try-lock behavior, bounded waiting, and failing-migration concurrency. |
| packages/core/src/emdash-runtime.ts | Adds per-entrypoint migration-failure backoff and destroys failed init DB instances to prevent connection leaks. |
| packages/core/src/db/postgres.ts | Applies the fail-fast migration lock wrapper to the Node Postgres dialect. |
| packages/core/src/database/pg-migration-lock.ts | Implements the PostgresAdapter override using pg_try_advisory_xact_lock + sentinel error routing. |
| packages/core/src/database/migrations/runner.ts | Treats Postgres “lock busy” as a concurrent-migrator race and waits boundedly before surfacing an error. |
| packages/core/src/astro/middleware.ts | Logs anonymous-path runtime init failures instead of silently swallowing them. |
| packages/core/package.json | Exposes the new emdash/database/pg-migration-lock subpath export. |
| packages/cloudflare/src/db/hyperdrive.ts | Applies the fail-fast migration lock wrapper to Hyperdrive’s singleton migrator dialect. |
| .changeset/pg-migration-lock-stampede.md | Adds patch release notes for the behavior change across core + cloudflare packages. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| export function withFailFastPgMigrationLock(dialect: Dialect): Dialect { | ||
| return { | ||
| createAdapter: () => new PostgresAdapter(), | ||
| createDriver: () => dialect.createDriver(), | ||
| createIntrospector: (db) => dialect.createIntrospector(db), | ||
| createQueryCompiler: () => dialect.createQueryCompiler(), | ||
| }; | ||
| } |
There was a problem hiding this comment.
Added in 15e57cb — withFailFastPgMigrationLock now throws at wrap time if the dialect's adapter isn't a Kysely PostgresAdapter, with a unit test covering it.
| throw new Error( | ||
| "Migration failed: another instance holds the migration lock and pending migrations were not applied within the wait window", | ||
| ); |
There was a problem hiding this comment.
Addressed in 15e57cb — the busy-timeout now throws a distinct ConcurrentMigrationTimeoutError whose message says the holder may still be applying migrations rather than implying failure. The distinct type also lets the runtime treat it differently (see the backoff exemption).
| const throwIfBackingOff = () => { | ||
| const failure = holder.failures.get(cacheKey); | ||
| if (failure && Date.now() - failure.at < DB_INIT_FAILURE_BACKOFF_MS) { | ||
| throw new Error( | ||
| `Database initialization is backing off after a recent migration failure: ${failure.message}`, | ||
| ); | ||
| } | ||
| }; |
There was a problem hiding this comment.
Fixed in 15e57cb — throwIfBackingOff now deletes the record once the window has elapsed, so the map only ever holds active backoffs. (In practice it's bounded at one entry per configured database entrypoint, but tidier is tidier.)
There was a problem hiding this comment.
This is the right fix for #1744. The approach is sound: replacing Kysely's blocking pg_advisory_xact_lock with a fail-fast try-lock, routing the busy case into the existing concurrent-migrator wait loop, adding per-isolate failure backoff, and destroying the Kysely instance on migration failure directly addresses the stampede and connection leak reported. The implementation follows EmDash's conventions:
- SQL is parameterized via
sql.lit()with no raw interpolation. - The wrapper keeps
PostgresAdapteras the constructor name sodetectDialect()still identifies Postgres. - Both Node
pgand Hyperdrive dialects are wrapped. - A changeset covers both published packages.
- Tests reproduce the incident shape on Postgres and the backoff behavior on SQLite.
I read the changed files, traced the lock/wait/backoff paths, and checked call sites (dialect detection, adapter capabilities, Hyperdrive request-scoped DB). I found no logic bugs or regressions in the core change.
One concern worth weighing before merge: MIGRATION_RACE_WAIT_MS defaults to 10s, which was tuned for local SQLite/D1 migrations. With remote Postgres over Hyperdrive, a cold-start rolling deploy that has many pending migrations could take longer than 10s. Waiter isolates would then fail with "another instance holds the migration lock ... not applied within the wait window" and enter the 30s backoff, even though the holder is making legitimate progress. If migrations routinely take >10s on Postgres, consider either raising the default for Postgres or exposing a runtime-configurable timeout so operators can set it above their observed migration duration. This is a non-blocking suggestion.
| @@ -129,6 +130,12 @@ const MIGRATION_LOCK_TABLE = "_emdash_migrations_lock"; | |||
|
|
|||
| export interface MigrationOptions { | |||
There was a problem hiding this comment.
[suggestion] MIGRATION_RACE_WAIT_MS defaults to 10s, which is sensible for SQLite/D1 but may be short for remote Postgres migrations during a rolling deploy. If the lock-holding isolate is legitimately still applying migrations, waiter isolates will time out and fail before the holder finishes, then back off for 30s. Consider whether Postgres should use a longer default (or make it runtime-configurable) so a slow-but-healthy migration doesn't cause transient init failures during deploys.
There was a problem hiding this comment.
Good catch — addressed structurally in 15e57cb rather than by raising the constant. Timing out behind another instance's in-flight migrations now throws ConcurrentMigrationTimeoutError, which getDatabase() exempts from the 30s failure backoff: the waiter's request fails, but the next request waits again immediately, so init recovers the moment the slow-but-healthy holder finishes. Only a migration that actually fails (in this isolate's own attempt) triggers the backoff. That keeps the 10s window as a per-request bound without turning a slow deploy into 30s of refused inits.
…r misuse - Throw ConcurrentMigrationTimeoutError when another instance held the migration lock past the wait window, and exempt it from the 30s init backoff: a slow-but-healthy migrator shouldn't cause waiter isolates to stop retrying (addresses the wait-window concern without raising MIGRATION_RACE_WAIT_MS). - Reject non-Postgres dialects in withFailFastPgMigrationLock at wrap time. - Drop expired failure records from the backoff map. Co-Authored-By: Claude Fable 5 <[email protected]>
| * Create a PostgreSQL dialect from config | ||
| */ | ||
| export function createDialect(config: PostgresConfig): PostgresDialect { | ||
| export function createDialect(config: PostgresConfig): Dialect { |
There was a problem hiding this comment.
Good catch — fixed in ad24d3c. Reworked as FailFastPostgresDialect, a PostgresDialect subclass overriding only createAdapter(), so createDialect keeps returning PostgresDialect and instanceof holds (test added). This also made the earlier runtime dialect guard unnecessary — the constructor takes PostgresDialectConfig, so misuse is now a type error.
| } catch (error) { | ||
| // Non-fatal — EmDashHead falls back to base SEO contributions — | ||
| // but log it: a persistently failing init (e.g. a failing | ||
| // migration, #1744) is otherwise invisible on the anonymous | ||
| // path, silently degrading every public page. | ||
| console.error("[emdash] runtime init failed (page renders without CMS data):", error); | ||
| } |
There was a problem hiding this comment.
Addressed in ad24d3c — the log is now throttled to once per 30s per isolate (matching the migration-failure backoff window), keeping the first failure visible without one line per request on a busy stuck site.
…t-failure log - Replace the object-literal dialect wrapper with FailFastPostgresDialect, a PostgresDialect subclass overriding only createAdapter(), so emdash/db/postgres keeps returning PostgresDialect (no type-level break) and the non-Postgres misuse guard becomes unnecessary by construction. - Throttle the anonymous-path runtime-init failure log to once per 30s per isolate so a stuck site doesn't flood logs on every request. Co-Authored-By: Claude Fable 5 <[email protected]>
What does this PR do?
Fixes the runtime-migration stampede reported in #1744: on Cloudflare Workers with Postgres (e.g. via Hyperdrive), a pending migration that keeps failing caused every cold isolate — and every request in warm isolates — to re-attempt it. Each attempt queued on Kysely's blocking
pg_advisory_xact_lockinside Postgres (98.58% of the reporter's query runtime, p50 ~3s per lock wait) and leaked an idle connection.Three changes:
pg-migration-lock.ts, applied to the nodepgand Hyperdrive dialects):acquireMigrationLocknow usespg_try_advisory_xact_lock. A busy lock routes into the existing boundedwaitForConcurrentMigratorpoll (the same recovery path SQLite/D1 races use) instead of parking a connection inside the database. The lock id matches Kysely's stock adapter so old and new builds still serialize during rolling deploys.emdash-runtime.ts): a migration failure is remembered per database entrypoint and re-attempts are skipped for 30s (checked before and under the init lock). Cold isolates still get one attempt each, so transient failures self-heal. Failed attempts nowdestroy()their Kysely/pool — previously each one leaked a connection, matching the idle-connection buildup in the issue.middleware.ts): runtime init failures on the anonymous path were silently swallowed; they now log, so a site stuck in this state is no longer invisible.Implementation note: the lock wrapper subclasses Kysely's
PostgresAdapterand keeps the class name, becausedetectDialect()identifies the dialect viaadapter.constructor.name— a delegating wrapper with its own class name made every dialect helper emit SQLite SQL against Postgres (caught by the new PG integration tests; there's now a unit test pinning that contract). The shared PG test utilities also route through the wrapper so all Postgres tests exercise the production lock behavior.Closes #1744
Type of change
Checklist
pnpm typecheckpasses (core + cloudflare; the pre-existingplugin-clifailure onmainis a staleplugin-typesdist, unrelated)pnpm lintpassespnpm testpasses — full core suite (4771 tests) run withEMDASH_TEST_PGset against a local Postgres, plus the cloudflare suite (214 tests)pnpm formathas been runAI-generated code disclosure
Screenshots / test output
New tests (TDD repro of the incident shape):
tests/integration/database/migration-lock-pg.test.ts(runs whenEMDASH_TEST_PGis set):tests/integration/runtime/create.test.ts: a failed migration is not re-attempted by the nextcreate()call — it fails fast without building a new connectiontests/unit/database/pg-migration-lock.test.ts: wrapper preserves adapter capability flags and thePostgresAdapterconstructor name that dialect detection relies on🤖 Generated with Claude Code
Try this PR
Open a fresh playground →
A full working EmDash site, deployed from this branch. Each visit gets its own session-scoped sandbox: no login needed and no shared state. Try the admin, edit content, hit the public site.
Tracks
fix/pg-migration-lock-stampede. Updated automatically when the playground redeploys.