Skip to content

fix(platform): wait out a restarting database when the backend boots - #4031

Merged
yannickmonney merged 7 commits into
mainfrom
fix/backend-boot-waits-out-database-restart
Oct 1, 2026
Merged

yannickmonney merged 7 commits into
mainfrom
fix/backend-boot-waits-out-database-restart

Conversation

@yannickmonney

@yannickmonney yannickmonney commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A backend process that starts while the app database is restarting now waits for the database instead of reporting an error and exiting. The wait lasts up to a minute, the same threshold /events already uses. A database that is still unreachable after that fails the start and is reported, exactly as before.

This came out of the triage of GlitchTip tale/tale#343, PostgresError: the database system is shutting down, imported as task TALE-406. #4030 has the full classification. Short version: #3506 and #3548 made a database restart routine for requests, jobs, pg-boss and /events (0.5.62 and later). Boot was the path they left out.

Closes #4030.

Problem

main.ts calls runBootMigrations first, and its first query is pg_advisory_lock. If the database is restarting at that moment, the query fails with the restart's own refusal: 57P03 the database system is shutting down, … is starting up, or ECONNREFUSED. main().catch then:

  • reports the refusal at error level (tale.lane: boot);
  • exits 1.

The orchestrator restarts the process with a backoff that grows to a minute, and every attempt reports again. The docs promise the opposite ("A database restart is not reported as an error"), recovery is delayed by that backoff, and each refusal message becomes its own error-level GlitchTip issue.

Change

  • backend/db/migrate.ts. runBootMigrations reruns its whole advisory-locked step through withRetry while isDatabaseUnavailable(error, { fromDatabase: true }) holds.
    • The pause starts at 1 s and doubles up to 5 s.
    • The wait lasts until ROUTINE_RESTART_MS (60 s) has passed since the first refusal. Time queued behind another process's migration lock, or spent applying migrations, before that refusal does not count.
    • The clock is monotonic (performance.now(), injectable as now), so a wall-clock step as the host syncs its time at boot neither cuts the wait short nor stretches it.
    • There is one clock per boot, on purpose: a second outage in the same boot shares it, so a database that keeps going away cannot hold the boot without it ever being reported.
    • fromDatabase is set because every client the step opens is a database client, including Better Auth's node-postgres migrator.
    • A rerun is what a restarted process did anyway:
      • the lock belongs to the session;
      • each app migration commits together with its app_migrations row or not at all, so even an ambiguous commit is skipped on the rerun;
      • Better Auth's migrator adds the tables and columns still missing;
      • the two post-auth statements are idempotent.
    • Any other error fails at once, as today. That includes 28P01, 3D000 and a migration that does not apply. An outage that outlasts the wait also still fails the boot.
    • The explicit unlock now runs only when the lock was taken and the failure does not say the database is away. Otherwise it only opened another connection to an absent database, adding a refused connection and a stack trace per attempt. Ending the session releases the lock either way.
  • backend/db/unavailable.ts.
    • Exports ROUTINE_RESTART_MS, the minute after which a database outage stops being a routine restart. realtime/sse.ts now takes its OUTAGE_REPORT_AFTER_MS from it (same value), so the two thresholds cannot drift apart.
    • EHOSTUNREACH and ENETUNREACH from a database client now count as the database being unavailable: a host that is down, or one whose network is not up yet as it boots. isTransientDbError already counted both.
  • @tale/shared/db/retry. withRetry gains maxDelayMs, a ceiling for one backoff pause; its default is unbounded, so existing callers are unchanged. An Infinity attempt count leaves the time budget alone to end the retries, and the log line then omits the /N total.
  • backend/main.ts. A comment at the migration call says a restart is waited out, and that only a longer outage reaches the fatal handler.
  • Docs (EN/DE/FR). One sentence in the observability page's restart paragraph.
  • Manual layer. Box PERF-B7 (backend start during a database restart), with a pins.md row and an automation.md row. The suite and readme counts went up by one.

Proof

Unit tests.

  • backend/db/migrate.test.ts (new) runs the real runBootMigrations against a local server that refuses each connection's startup with a FATAL.
    • It waits out two 57P03 shutting down refusals (pauses [1000, 2000]), then fails at once on 28P01.
    • It fails the boot with the last 57P03 once the outage outlasts a 20 s wait (pauses [1000, 2000, 4000, 5000, 5000, 5000]).
    • It times the outage from its first refusal: when that refusal arrives 55 s into the step, the full 20 s wait still follows.
    • It fails at once, over a single connection, on 28P01.
    • It keeps its clock off the wall clock: with Date.now leaping an hour on every read, all three refusals are still waited out.
    • The first four cases fail against main's migrate.ts: it rejects at the first 57P03, never retries, and opens a second connection to unlock a lock it never took.
    • The wall-clock case fails against 53b905d2c's migrate.ts, whose clock was Date.now.
    • The clock test also fails against this PR's first head c46fbefd0, which had a budget from the start of the step: no pause at all.
  • backend/db/unavailable.test.ts adds EHOSTUNREACH and ENETUNREACH to the database-client socket cases.
  • packages/shared/src/db/retry.test.ts adds two cases: the delay stops doubling at maxDelayMs, and an Infinity attempt count runs until the budget at the capped delay (with the /N-less log line).

End to end, local and isolated. Setup:

  • a real PostgreSQL 16 on loopback;
  • the backend started with the image's own command line (ROLE=all);
  • SENTRY_DSN pointed at a local fake ingest;
  • a no-egress preload;
  • no production contact.
Start of a backend process… main (b420851b7; boot code identical to a703a9598) this branch
inside a database shutdown phase 1 error event PostgresError: the database system is shutting down (tale.lane: boot), exit 1 after 6 s Logs [db] transient error on attempt 1–4 … the database system is shutting down, then … ECONNREFUSED while the database was down. It answered /ping 6 s after the database came back, /ready 200, no event
with the database down for 80 s 1 error event Error: connect ECONNREFUSED, exit 1 at once (the orchestrator then restarts it) 13 retries over about 57 s, then one error event (tale.lane: boot) and exit 1. The persistent failure is still reported

The table shows the first head (c46fbefd0). On the second head (9919347cc), the same rounds behaved as follows:

  • inside the shutdown phase: 6 retries, /ping 1 s after the database came back, /ready 200, no event;
  • database down for 80 s: 14 retries, then one error event and exit 1, about 62 s after the first refusal.

The same rig showed the rest of the restart class unchanged. #4030 has the details:

  • a 50 s restart under load sent 0 events;
  • a 75 s shutdown phase sent one warning-level /events event, by design;
  • a backend stopped together with the database exited 0 in under 1 s;
  • across 6 fast shutdowns, 46 transactions failed at COMMIT and none of them committed anyway.

Independent review

A read-only adversarial review of c46fbefd0 found no high-severity defect. Its findings and what became of them:

  • Medium: the knowledge boot steps send the same event. Reproduced and filed as bug(platform): a knowledge-database restart at backend boot is reported as an error and skips the BM25 index check #4035; not fixed here.
  • Low-medium: the wait was a budget from the start of the step. Fixed in 9919347cc: the outage is now timed from its first refusal, and the clock test pins it.
  • Low: the classifier missed EHOSTUNREACH and ENETUNREACH. Fixed.
  • Low: the unlock ran after a lock the outage had already dropped. Fixed.
  • Low: the rerun-safety note overclaimed Better Auth's migrator. Reworded: Better Auth emits a field's index only together with its column, so an interruption between the two leaves the index missing. That gap is pre-existing, and a process restart has it too.
  • Low: the PERF-B7 steps. Reworded: the restart count is now read relative to the manual restart, and the steps use compose service names.
  • Kept as is:
    • fromDatabase: true (needed for Better Auth's bare node-postgres socket errors) has no unit test. Reaching that path needs a real database; the Backend integration check runs the happy path.
    • Class 08 and a typo'd host or port now surface after the minute's wait instead of at once.
    • The backoff has no jitter, so N containers retry in step: one connection each every 5 s.

Second review (TALE-416, Agent #2). The verdict was approve with optional notes a–e. The reviewer's real-PostgreSQL rounds passed on 3b4a5c93a: a mid-migration 57P01, Better Auth's pool refused while the lock session stays alive, 65 s queued behind the lock and then a cut, api and worker started together into an outage, and 57P03 for 30 s. What became of the notes in cc36b1f41:

Checks (run locally)

  • Shared package:
    • packages/shared: vitest passes (40 files, 634 tests);
    • tsc --noEmit passes.
  • Platform:
    • the tests of the changed files and of the modules that import them: 38 files and 598 tests pass on cc36b1f41 (597 on 9919347cc, 570 on the first head). The run covered:
      • backend/db/, realtime/sse, error-reporting, auth.database-unavailable, http-shutdown, chat/routes, jobs/boss, jobs/runner, rest/v1, store-health;
      • two transactSerializable users and core/knowledge/pool;
      • every tests/guards/*, including the integration-scope guard;
      • the source-scanning guards (rest/error-codes, tasks/errors, handler_names, both shim tests, openapi/spec, rate-limit, invalid-body-response).
    • tsc over the changed backend files plus backend/main.ts (its whole import graph) passes.
    • Type-aware oxlint on the six changed TS files is clean.
  • Docs and manual layer:
    • the docs suite (services/docs) passes: 37 files, 222 tests;
    • bun run lint:manual and check-guide.ts on performance.md are OK.
  • Repository gates:
    • oxfmt --check, lint:conflicts and opengrep (0 findings) are clean;
    • commitlint and the pre-commit hooks passed.

CI on the final head cc36b1f41: all 58 checks are green, 13 skipped by design.

  • Backend integration passed 1261/1261 across 210/210 lanes.
  • Unit, Type check and Lint ran for @tale/platform.
  • Playwright raised no recovered-flake notice.
  • The PR is MERGEABLE/CLEAN against main 1ad5a5ecc.

The earlier runs below are kept as they were.

CI on 53b905d2c. That head has origin/main 929e9b162 merged in, which includes TALE-405's #4033. The manual layer composes with it: its PERF-B8 and this PR's PERF-B7 both stay, and the totals read PERF- 20 and 1064. Every check is green except one, Backend integration, which passed 1259 of 1260 checks.

The one failure is not caused by this PR. It is the busy-retry lane's known race, "busy retry, racing: while a delegated start holds the agent row …", which open #4027 fixes (test-only). The race:

  • the lane holds a delegated start open while a concurrent lane's audited write bumps the shared audit chain head;
  • the held start's first attempt fails with 40001;
  • the retry it queued behind wins, so the order flips.

Each failing run logs could not serialize access due to concurrent update just before the failure. Evidence that it is this race:

  • The same code from this PR passed 1260 of 1260 on 3b4a5c93a.
  • c46fbefd0 passed in full.
  • The lane passes 3 out of 3 times alone.
  • The PR changes nothing that lane runs. withRetry with no maxDelayMs computes the same delays, and transactSerializable passes none.

History:

  • c46fbefd0: green.
  • 9919347cc: the same race, 1252 of 1253.
  • Next two pushes: started no workflow, because the PR had become CONFLICTING on the manual box totals and GitHub runs no pull_request workflow then.
  • 3b4a5c93a: green, including Backend integration (1260 of 1260 across 210 lanes). Unit, Type check and Lint ran for platform, shared and docs ("cache miss, executing"). Playwright had no recovered-flake notice.
  • 53b905d2c: the race again.

The token cannot re-run a job (403). Once #4027 lands, merging main, or a maintainer's re-run of the job, should turn the check green.

Not run here: the whole-workspace tsc and type-aware lint, the full platform suite, backend:integration, and E2E. The memory cap prevents the first ones, and the box has no Docker for E2E. CI runs them on this PR. This PR touches the backend, so the Backend integration check is owed.

Not in this PR

Recorded in #4030, each needs a decision:

Coordination. TALE-405 (GlitchTip #109, BackendApiError UPSTREAM_UNAVAILABLE) owns the browser and edge side and stays out of services/platform/backend/**. This PR touches no SPA, UI or proxy file. Refs #3273.

A backend process that started while the app database was restarting
failed the migrator's first query with the restart's own refusal (57P03
"the database system is shutting down", "... is starting up", or a
refused connection). The boot lane reported it at error level and the
process exited; the orchestrator restarted it with a growing backoff and
every attempt reported again. GlitchTip tale/tale#343 carries that title.

runBootMigrations now reruns its whole advisory-locked step while the
database is unavailable (isDatabaseUnavailable), 1 s doubling to 5 s
apart, for up to ROUTINE_RESTART_MS: the 60 s after which /events
already reports an outage. Any other error, and an outage that outlasts
the wait, still fail the boot and are reported. A lock that was never
taken is no longer "unlocked" over a second connection.

withRetry gains maxDelayMs, and an Infinity attempt count leaves the
time budget alone to end the retries.
yannickmonney added a commit that referenced this pull request Oct 1, 2026
#4031 adds PERF-B7 (a backend start during a database restart) to the same suite. Numbering this box PERF-B8 keeps the two IDs distinct whichever pull request lands first; the second to merge recounts the suite and readme totals.
Review follow-ups for the boot wait:

- The wait was a budget from the start of the migration step, so time
  queued behind another process's migration lock (or spent applying
  migrations) used it up: a restart 55 s into the step failed the boot
  at once. The outage is now timed from its first refusal.
- A lock that was taken is no longer "unlocked" after a failure that
  says the database is away: that only opened a new connection to it,
  and ending the session releases the lock anyway.
- EHOSTUNREACH and ENETUNREACH from a database client count as the
  database being unavailable (a host that is down, or whose network is
  not up yet as it boots), as isTransientDbError already counts them.
- The rerun-safety note no longer overclaims Better Auth's migrator,
  and PERF-B7 reads the restart count relative to the manual restart
  and uses compose service names like PERF-B5/B6.
Backend integration failed one check on 9919347: "busy retry, racing: while a delegated start holds the agent row ..." in checkAutomatedRetryAgentBusy (1252/1253 across 209/209 lanes). The same lane passed on c46fbef and passes alone on this head three times out of three; it is a known race in that lane, unrelated to the boot wait. The token cannot re-run a job, so this empty commit re-runs the checks.
…ited out

main.ts calls runBootMigrations with no hint that the call can now pause for up to a minute while the database restarts. Say so where the boot sequence is read, and that only a longer outage reaches the fatal handler. The empty commit before this one did not start any workflow.
…s-out-database-restart

# Conflicts:
#	services/platform/tests/manual/readme.md
…s-out-database-restart

# Conflicts:
#	services/platform/tests/manual/suites/performance.md
Review notes on #4031, folded into one push:

- e1: the outage's clock is performance.now() (injectable for tests), so
  a wall-clock step as the host syncs its time at boot neither cuts the
  wait short nor stretches it. A test leaps Date.now an hour per read and
  still sees every refusal waited out.
- a: the clock stays one per boot, on purpose. Resetting it on progress
  would let a database that keeps going away hold the boot without it
  ever being reported. The docstring now says exactly that, including
  that a second outage shares the time between the two.
- d, e2: the docs say the start fails if the database is still
  unreachable after the minute, and that a wrong host or port in
  DATABASE_URL takes about a minute to fail it.

Note b (do not wait out a connection lost under the migration lock) was
tried and dropped. Under a transaction, postgres.js reports an
administrator's shutdown as CONNECTION_CLOSED or ECONNRESET, never
57P01, so the rule failed a routine restart mid-migration. A probe on a
real PostgreSQL 16 showed it: the boot exited where the previous head
reran and completed. A crashing migration is a follow-up instead.
@yannickmonney

Copy link
Copy Markdown
Contributor Author

Independent review (TALE-416): approved at cc36b1f41.

  • Revision reviewed. 53b905d2c → cc36b1f41 brings: a monotonic, injectable clock; the docstring stating the deliberate one-clock-per-boot design; and EN/DE/FR wording, including that a wrong host or port takes about a minute to fail.
    • The rule "fail fast on a connection lost under the lock" was dropped. Under a transaction, postgres.js reports a fast shutdown as CONNECTION_CLOSED, so the rule would fail a routine restart. The author and I each confirmed this on real Postgres.
  • Real PostgreSQL 16 on cc36b1f41, loopback, through a synthetic fault proxy (scenario names as in the TALE-416 evidence):
    • S-A: the lock session is terminated mid-migration while new connections are refused. Result: 145/145, no lock left.
    • S-A4: termination while the transaction sits between statements. Result: done.
    • S-F: an in-flight 57P01, 57P02 or socket reset under the lock, each waited out.
    • S-B: Better Auth's pool refused (bare ECONNREFUSED, the fromDatabase path). Result: done.
    • S-C: 65 s queued behind another session's lock, then the outage. Result: done.
    • S-D: api and worker with the database down throughout. Each fails about 62 s after its first refusal, with exactly one tale.lane: boot error event.
    • S-E: api and worker through 30 s of 57P03. /ping is 200 5.3 s after the database returns, with 0 events.
    • Base controls fail as the issue describes, including PostgresError: the database system is shutting down at boot.
  • CI on cc36b1f41 (merge ref into f3cc8e18a):
    • Backend integration was a real run: 1261/1261 across 210/210 lanes.
    • Platform test, test:ui, test:browser, typecheck and lint executed. The shared and docs-typecheck replays match hashes executed at 3b4a5c93a.
    • Playwright: 66 passed plus 1 pre-existing fixme, no diagnostics notice, no attempt artifact.
    • The red runs on 9919347cc and 53b905d2c were test(platform): keep a held delegated start off the audit chain head #4027's lane race. I reproduced it locally on main with and without this PR, and it is now fixed on main.
  • Follow-ups, not this PR: bug(platform): a knowledge-database restart at backend boot is reported as an error and skips the BM25 index check #4035 (knowledge boot), bug(platform): a knowledge-database failure answers the platform's DATABASE_UNAVAILABLE and is reported nowhere #4037 (knowledge-database failures answer the platform's DATABASE_UNAVAILABLE), bug(platform): a Postgres server process that dies under an open transaction crashes the backend (postgres.js null-socket write) #4041 (postgres.js null-socket crash on a backend crash).

@yannickmonney
yannickmonney merged commit 845f3bd into main Oct 1, 2026
71 checks passed
@yannickmonney
yannickmonney deleted the fix/backend-boot-waits-out-database-restart branch October 1, 2026 10:11
tale-review-bot pushed a commit that referenced this pull request Oct 30, 2026
A backend process that started while the knowledge database was
restarting or still starting reported the refusal as an error event (the
default corpus bootstrap, on the worker and all roles) and skipped the
BM25 index verification of the default corpus for the life of the
process, so an index a crash-mode stop corrupted was neither detected
nor kept from taking writes. knowledge-db is not among the backend's
compose dependencies, so such a start is an ordinary event.

The boot's knowledge steps now wait out the knowledge database with
createBootDatabaseWait, the helper #4031 added for the app database, on
a clock of their own: bootDefaultKnowledge (domains/knowledge/boot.ts)
waits up to ROUTINE_RESTART_MS (60 s) from the knowledge database's
first refusal, then bootstraps the schema and verifies the indexes.
healBm25Indexes takes the wait, reruns a scan the database refused whole
on a fresh session, and reports a database that stays unavailable as the
new status `unavailable`, with a warning instead of an error line; the
report's effects still run once. An outage past the wait is reported
once per boot, at error level with the boot's tag, and each step it
skipped logs a warning saying it stays skipped until the process
restarts. Any other failure is handled as before. The observability and
container docs (EN/DE/FR) follow.

Closes #4035
Task: TALE-51
tale-code-bot added a commit that referenced this pull request Oct 31, 2026
A backend process that started while the knowledge database was
restarting or still starting reported the refusal as an error event (the
default corpus bootstrap, on the worker and all roles) and skipped the
BM25 index verification of the default corpus for the life of the
process, so an index a crash-mode stop corrupted was neither detected
nor kept from taking writes. knowledge-db is not among the backend's
compose dependencies, so such a start is an ordinary event.

The boot's knowledge steps now wait out the knowledge database with
createBootDatabaseWait, the helper #4031 added for the app database, on
a clock of their own: bootDefaultKnowledge (domains/knowledge/boot.ts)
waits up to ROUTINE_RESTART_MS (60 s) from the knowledge database's
first refusal, then bootstraps the schema and verifies the indexes.
healBm25Indexes takes the wait, reruns a scan the database refused whole
on a fresh session, and reports a database that stays unavailable as the
new status `unavailable`, with a warning instead of an error line; the
report's effects still run once. An outage past the wait is reported
once per boot, at error level with the boot's tag, and each step it
skipped logs a warning saying it stays skipped until the process
restarts. Any other failure is handled as before. The observability and
container docs (EN/DE/FR) follow.

Closes #4035
Task: TALE-51
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.

bug(platform): a backend that starts during a database restart reports an error and exits

1 participant