Skip to content

fix: prevent Postgres migration stampede when a pending migration fails - #1875

Merged
ascorbic merged 3 commits into
mainfrom
fix/pg-migration-lock-stampede
Jul 8, 2026
Merged

ascorbic merged 3 commits into
mainfrom
fix/pg-migration-lock-stampede

Conversation

@ascorbic

@ascorbic ascorbic commented Jul 8, 2026 •

Copy link
Copy Markdown
Member

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_lock inside Postgres (98.58% of the reporter's query runtime, p50 ~3s per lock wait) and leaked an idle connection.

Three changes:

  1. Fail-fast migration lock (pg-migration-lock.ts, applied to the node pg and Hyperdrive dialects): acquireMigrationLock now uses pg_try_advisory_xact_lock. A busy lock routes into the existing bounded waitForConcurrentMigrator poll (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.
  2. Failure backoff (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 now destroy() their Kysely/pool — previously each one leaked a connection, matching the idle-connection buildup in the issue.
  3. Visibility (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 PostgresAdapter and keeps the class name, because detectDialect() identifies the dialect via adapter.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

  • Bug fix
  • Feature (requires maintainer-approved Discussion)
  • Refactor (no behavior change)
  • Translation
  • Documentation
  • Performance improvement
  • Tests
  • Chore (dependencies, CI, tooling)

Checklist

  • I have read CONTRIBUTING.md
  • pnpm typecheck passes (core + cloudflare; the pre-existing plugin-cli failure on main is a stale plugin-types dist, unrelated)
  • pnpm lint passes
  • pnpm test passes — full core suite (4771 tests) run with EMDASH_TEST_PG set against a local Postgres, plus the cloudflare suite (214 tests)
  • pnpm format has been run
  • I have added/updated tests for my changes (if applicable)
  • User-visible strings in the admin UI are wrapped for translation — n/a, no admin UI changes
  • I have added a changeset (if this PR changes a published package)
  • New features link to an approved Discussion — n/a, bug fix

AI-generated code disclosure

  • This PR includes AI-generated code — model/tool: Claude Code + Claude Fable 5

Screenshots / test output

New tests (TDD repro of the incident shape):

  • tests/integration/database/migration-lock-pg.test.ts (runs when EMDASH_TEST_PG is set):
    • fails fast in bounded time while another session holds the advisory lock (previously blocked indefinitely)
    • settles as success when the concurrent migrator finishes during the wait
    • concurrent callers against a genuinely failing migration all fail in bounded time with the real error surfaced, and bookkeeping is not silently advanced
  • tests/integration/runtime/create.test.ts: a failed migration is not re-attempted by the next create() call — it fails fast without building a new connection
  • tests/unit/database/pg-migration-lock.test.ts: wrapper preserves adapter capability flags and the PostgresAdapter constructor name that dialect detection relies on
 Test Files  334 passed (334)
      Tests  4771 passed (4771)   # core, EMDASH_TEST_PG enabled
 Test Files  15 passed (15)
      Tests  214 passed (214)     # @emdash-cms/cloudflare

🤖 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.

…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]>
Copilot AI review requested due to automatic review settings July 8, 2026 12:43
@changeset-bot

changeset-bot Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: ad24d3c

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 16 packages
Name Type
emdash Patch
@emdash-cms/cloudflare Patch
@emdash-cms/sandbox-workerd Patch
@emdash-cms/fixture-perf-site Patch
@emdash-cms/perf-demo-site Patch
@emdash-cms/cache-demo-site Patch
@emdash-cms/do-demo-site Patch
@emdash-cms/do-solo-demo-site Patch
@emdash-cms/admin Patch
@emdash-cms/auth Patch
@emdash-cms/blocks Patch
@emdash-cms/gutenberg-to-portable-text Patch
@emdash-cms/x402 Patch
create-emdash Patch
@emdash-cms/auth-atproto Patch
@emdash-cms/plugin-embeds Patch

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

@pkg-pr-new

pkg-pr-new Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@emdash-cms/admin

npm i https://pkg.pr.new/@emdash-cms/admin@1875

@emdash-cms/auth

npm i https://pkg.pr.new/@emdash-cms/auth@1875

@emdash-cms/auth-atproto

npm i https://pkg.pr.new/@emdash-cms/auth-atproto@1875

@emdash-cms/blocks

npm i https://pkg.pr.new/@emdash-cms/blocks@1875

@emdash-cms/cloudflare

npm i https://pkg.pr.new/@emdash-cms/cloudflare@1875

@emdash-cms/contentful-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/contentful-to-portable-text@1875

emdash

npm i https://pkg.pr.new/emdash@1875

create-emdash

npm i https://pkg.pr.new/create-emdash@1875

@emdash-cms/gutenberg-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/gutenberg-to-portable-text@1875

@emdash-cms/plugin-cli

npm i https://pkg.pr.new/@emdash-cms/plugin-cli@1875

@emdash-cms/plugin-types

npm i https://pkg.pr.new/@emdash-cms/plugin-types@1875

@emdash-cms/registry-client

npm i https://pkg.pr.new/@emdash-cms/registry-client@1875

@emdash-cms/registry-lexicons

npm i https://pkg.pr.new/@emdash-cms/registry-lexicons@1875

@emdash-cms/sandbox-workerd

npm i https://pkg.pr.new/@emdash-cms/sandbox-workerd@1875

@emdash-cms/x402

npm i https://pkg.pr.new/@emdash-cms/x402@1875

@emdash-cms/plugin-ai-moderation

npm i https://pkg.pr.new/@emdash-cms/plugin-ai-moderation@1875

@emdash-cms/plugin-atproto

npm i https://pkg.pr.new/@emdash-cms/plugin-atproto@1875

@emdash-cms/plugin-audit-log

npm i https://pkg.pr.new/@emdash-cms/plugin-audit-log@1875

@emdash-cms/plugin-color

npm i https://pkg.pr.new/@emdash-cms/plugin-color@1875

@emdash-cms/plugin-embeds

npm i https://pkg.pr.new/@emdash-cms/plugin-embeds@1875

@emdash-cms/plugin-field-kit

npm i https://pkg.pr.new/@emdash-cms/plugin-field-kit@1875

@emdash-cms/plugin-forms

npm i https://pkg.pr.new/@emdash-cms/plugin-forms@1875

@emdash-cms/plugin-webhook-notifier

npm i https://pkg.pr.new/@emdash-cms/plugin-webhook-notifier@1875

commit: ad24d3c

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
emdash-playground ad24d3c Jul 08 2026, 03:27 PM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
emdash-demo-cache ad24d3c Jul 08 2026, 03:26 PM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
emdash-demo-do ad24d3c Jul 08 2026, 03:26 PM

Copilot AI 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.

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.

Comment on lines +66 to +73
export function withFailFastPgMigrationLock(dialect: Dialect): Dialect {
return {
createAdapter: () => new PostgresAdapter(),
createDriver: () => dialect.createDriver(),
createIntrospector: (db) => dialect.createIntrospector(db),
createQueryCompiler: () => dialect.createQueryCompiler(),
};
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment on lines +370 to +372
throw new Error(
"Migration failed: another instance holds the migration lock and pending migrations were not applied within the wait window",
);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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).

Comment on lines +1651 to +1658
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}`,
);
}
};

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.)

@emdashbot emdashbot 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.

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 PostgresAdapter as the constructor name so detectDialect() still identifies Postgres.
  • Both Node pg and 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 {

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.

[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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@github-actions github-actions Bot added review/awaiting-author Reviewed; waiting on the author to respond and removed review/needs-review No maintainer or bot review yet labels Jul 8, 2026
…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]>
@github-actions github-actions Bot added review/needs-rereview New commits since the last review size/XL and removed size/L review/awaiting-author Reviewed; waiting on the author to respond labels Jul 8, 2026
@ascorbic ascorbic added the bot:review Trigger an emdashbot code review on this PR label Jul 8, 2026
@ascorbic
ascorbic requested a review from Copilot July 8, 2026 15:01

Copilot AI 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.

Pull request overview

Copilot reviewed 13 out of 13 changed files in this pull request and generated 2 comments.

Comment thread packages/core/src/db/postgres.ts Outdated
* Create a PostgreSQL dialect from config
*/
export function createDialect(config: PostgresConfig): PostgresDialect {
export function createDialect(config: PostgresConfig): Dialect {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment on lines +574 to 580
} 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);
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@github-actions github-actions Bot added review/awaiting-author Reviewed; waiting on the author to respond and removed review/needs-rereview New commits since the last review labels Jul 8, 2026
@ascorbic ascorbic added this to the 1.0 milestone Jul 8, 2026
…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]>
@github-actions github-actions Bot added the review/needs-rereview New commits since the last review label Jul 8, 2026
@github-actions github-actions Bot added size/L and removed review/awaiting-author Reviewed; waiting on the author to respond size/XL labels Jul 8, 2026
@ascorbic
ascorbic merged commit b116525 into main Jul 8, 2026
54 checks passed
@ascorbic
ascorbic deleted the fix/pg-migration-lock-stampede branch July 8, 2026 16:11
@emdashbot emdashbot Bot mentioned this pull request Jul 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/cloudflare area/core bot:review Trigger an emdashbot code review on this PR review/needs-rereview New commits since the last review size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Runtime Postgres migrations can stampede when a pending migration fails on Cloudflare Workers

2 participants