Skip to content

fix(relay): wait out a cold proxy at boot instead of exiting the cell - #21516

Merged
Jinwoo-H merged 2 commits into
mainfrom
fix/relay-boot-database-retry
Sep 18, 2026
Merged

Jinwoo-H merged 2 commits into
mainfrom
fix/relay-boot-database-retry

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor

ELI5

When a relay cell machine starts up, two programs start at the same time: the relay itself, and a small helper that opens the connection to the database. The relay asked for the database straight away, gave up after two seconds when the helper was not ready yet, and killed itself. The machine then restarted it and everything was fine. This teaches the relay to wait a moment and ask again instead of dying.

What Changed

Before (what an operator sees): during a fleet roll, a freshly started cell logs Connection terminated due to connection timeout and the container exits before it ever serves a request. Container-OS restarts it and the next boot succeeds one to three seconds later. On the 2026-09-18 roll (21 cells) every cell did this between zero and seven times — one cell restarted seven times in 23 seconds — including two canary cells carrying no hosts at all. Nothing is lost, but each crash costs a boot cycle and the container die events make it hard to tell a healthy roll from a failing one.

After: the same cold start logs one or two orca_relay_boot_database_retry lines and then serves. No container exit, no restart, and the rollout log says plainly what happened.

Mechanism: the boot sequence opens the database (openRelayDatabase) before anything else — schema apply, then a small region backfill. Both use a pool with a 2 second connect timeout, which exists to keep a request from hanging on the pool; the very first acquire of the process runs while cloud-sql-proxy is still starting, so it can legitimately exceed that. The rejection reaches a top-level await in the entrypoint, which ends the process.

That first open now runs through openRelayDatabaseAtBoot, which retries only when Postgres could not be reached at all, bounded by a 45 second wall-clock window with exponential backoff (250ms, 500ms, 1s, 2s, then 4s).

Retried:

  • the pool's two connect-timeout messages (timeout exceeded when trying to connect, Connection terminated due to connection timeout),
  • Connection terminated unexpectedly only when it was seen at the acquire boundary, so a socket that ended mid-statement is never repeated,
  • SQLSTATE 08001 and 08006 (client cannot establish / connection failure).

Not retried — the process exits on the first attempt, as today:

  • 55P03 lock not available, 57014 statement timeout, 53300 too many connections, 40001/40P01 serialization and deadlock, 57P03 cannot connect now,
  • everything else: a rejected password, a malformed URL, a programming error.

That exclusion is deliberate and is the one place this differs from the request path's transient classifier. A boot retry re-runs the schema apply, and applyPostgresSchema refuses to repeat a DDL lock timeout on purpose: relation locks are granted in queue order, so repeating the statement parks every writer behind it again for another timeout. Retrying a 55P03 up to sixteen times in a 45 second window is the mechanism behind the 2026-09-16 outage, so the boot loop must not re-queue it. The director's startup reconcile (reconcileCellAdmissionAtStartup) keeps the full classifier — it re-runs one statement, not DDL, and waiting out 55P03 is exactly what it is for.

Each wait emits orca_relay_boot_database_retry (attempt, delayMs, bounded error code, connectionTimeout), a late success emits orca_relay_boot_database_recovered, and giving up emits orca_relay_boot_database_failed (attempts, retryable, code) before the process exits. Error codes are emitted only from the existing recognised-code list, never raw messages, because a driver message can carry a credential.

Readiness semantics, schema-apply behaviour, and the runtime pool timeouts are untouched: this only changes what happens between "process starts" and "database handle exists", which is before anything reports ready.

The bounded retry loop itself already existed in reconcileCellAdmissionAtStartup (director startup reconcile). Rather than write a second copy, it is lifted into database-startup-retry.ts and both callers use it. The reconcile keeps its exact attempt budget, flat 250ms delay, and both of its log events — a flat delay is expressed as a backoff cap equal to the base.

Why

The crash is systematic, not load-dependent: it happens on cells with no hosts and is independent of Cloud SQL pressure. It is a race between two processes in the same container, and the relay is the one that can wait.

Alternatives considered:

  • Raise the pool connect timeout. Rejected: that timeout is a runtime property. Making it generous enough to cover a proxy cold start would slow down detection of a genuinely unreachable database on every request for the life of the process, to fix a problem that only exists in the first second of it.
  • Keep relying on the container restart. It does work, and no host connection is lost. But it burns a boot cycle per crash and pollutes the signal a roll is verified against, which is exactly when the noise is most expensive.
  • Retry only the region backfill. The failure is a pool acquire, and the schema apply acquires from a pool too, so scoping the retry to the backfill would leave the same race one step earlier. Retrying the whole open is safe because openRelayDatabase closes what it built before it throws, and the schema apply is idempotent and catalog-pre-checked — but only because the retry gate excludes lock timeouts, so no DDL is ever re-queued.
  • Reuse the request path's transient classifier as-is. Rejected in review: it includes 55P03, which would have had a contended boot re-queue the same DDL sixteen times.
  • Retry forever / retry unconditionally. A cell that can never reach its database must stay dead and be replaced, not sit half-alive. Hence the bounded window and the transient-only gate.

Linked Issue

No GitHub issue: this came out of the 2026-09-18 production fleet roll rather than a filed report.

Fixes #

Visual Proof

N/A — server-side boot behaviour with no UI surface. The observable change is in the cell's container log (orca_relay_boot_database_retry instead of a process exit).

Testing

  • cd cloud/apps/relay && pnpm test src/boot-database-open.test.ts src/cell-admission-startup.test.ts src/database-transient-error.test.ts src/postgres-query-failure.test.ts — 4 files, 40 tests passed.

  • Full relay unit project (npx vitest run --project relay): 67 files, 716 passed, 1 skipped.

  • Full relay Postgres project against a throwaway postgres:16-alpine: 24 files, 130 passed.

  • pnpm typecheck and pnpm build in cloud/apps/relay: clean.

  • New tests cover: a connect timeout retried and then succeeding; an 08006 connection failure retried; a rejected credential exiting on the first attempt; 55P03, 57014 and 53300 each exiting on the first attempt with no retry event, so the schema apply is never re-queued; and the retry budget exhausting within the 45 second window and emitting the final failure event.

  • Platforms: the relay runs on Linux (Container-Optimized OS) only; tested on macOS by unit test, and the change is platform-independent Node.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

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

Security: no new logged field can carry a credential — error codes pass through the existing recognised-code allowlist and messages are never logged. Backwards compatibility: no wire, schema, or readiness change; a cell running this code is indistinguishable from the old one once booted. Performance: the retry path only runs before the process serves anything, and a healthy boot takes the exact same path as before.

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)

A cell container starts its relay process beside a cloud-sql-proxy that is
itself still dialling. The first pool acquire therefore competes with a proxy
cold start, and the 2s connect timeout that protects the request path fires
before the proxy is listening. `openRelayDatabase` rejects out of the region
backfill, the top-level await rejects, and the process exits; COS restarts the
container and the next boot succeeds 1-3s later. The 2026-09-18 fleet roll saw
0-7 of these per cell, including on cells with zero hosts, so it is a property
of the boot sequence rather than of database load.

The boot open now retries on transient errors only, inside a 45s wall-clock
window with exponential backoff from 250ms to 4s. The classifier is the one the
request path already uses, so a rejected credential or a bad URL still exits on
the first attempt. Each wait logs `orca_relay_boot_database_retry` and a
give-up logs `orca_relay_boot_database_failed`, both with the bounded error
category, so a rollout can tell a slow boot from a stuck one without reading
container exit codes.

The bounded startup retry is lifted out of `reconcileCellAdmissionAtStartup`,
which had the same loop; its attempt budget, flat delay, and both log events are
unchanged (a flat delay is a cap equal to the base).
@coderabbitai

coderabbitai Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: b32b5091-ee86-4b51-af67-c19f4fb0b22e

📥 Commits

Reviewing files that changed from the base of the PR and between 3e792fa and 3a4e495.

📒 Files selected for processing (4)
  • cloud/apps/relay/src/boot-database-open.test.ts
  • cloud/apps/relay/src/boot-database-open.ts
  • cloud/apps/relay/src/cell-admission-startup.ts
  • cloud/apps/relay/src/database-startup-retry.ts

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


📝 Walkthrough

Walkthrough

The change adds a shared bounded retry helper for transient database startup failures. Cell admission reconciliation uses this helper. Relay boot database opening now retries unreachable database failures with backoff and logs retry, recovery, and failure events. The database open input type is exported. PostgreSQL error-code categorization is centralized. Tests cover recovery, immediate failures, lock-contention failures, and retry exhaustion.

Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to 3a4e4

Relay startup can exceed its 45-second retry budget by a full final database-open attempt. Add a post-sleep deadline check before merging.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 7 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description is detailed and covers the change, rationale, testing, risks, and checklist. However, the required Linked Issue section is incomplete because it states there is no issue and leaves `Fi… Add the GitHub issue reference in the Linked Issue section, or provide the repository-approved reference for the production incident. Do not leave the required Fixes # field empty.
✅ Passed checks (3 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 summarizes the main change: retrying database startup during a cold proxy instead of exiting the relay cell.
Full details: Description check

Explanation

The description is detailed and covers the change, rationale, testing, risks, and checklist. However, the required Linked Issue section is incomplete because it states there is no issue and leaves Fixes # empty.

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

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 3dbf68e7-48a3-40da-97b8-6a8e1ae232e5

📥 Commits

Reviewing files that changed from the base of the PR and between fc3a5d7 and 3e792fa.

📒 Files selected for processing (7)
  • cloud/apps/relay/src/boot-database-open.test.ts
  • cloud/apps/relay/src/boot-database-open.ts
  • cloud/apps/relay/src/cell-admission-startup.ts
  • cloud/apps/relay/src/database-startup-retry.ts
  • cloud/apps/relay/src/database.ts
  • cloud/apps/relay/src/index.ts
  • cloud/apps/relay/src/postgres-query-failure.ts

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

Comment on lines +43 to +45
const delayMs = Math.min(retryDelayMs(policy, attempt), remainingMs)
observer.onRetry?.({ attempt, delayMs, error })
await new Promise((resolve) => setTimeout(resolve, delayMs))

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Check the deadline again before the next operation.

delayMs can consume all remaining time. The loop then starts another operation() after retryDeadline. This final attempt can extend startup by the full database connection timeout.

Check Date.now() after the sleep. If the deadline has expired, call onGaveUp and rethrow the current error.

Proposed fix
       const delayMs = Math.min(retryDelayMs(policy, attempt), remainingMs)
       observer.onRetry?.({ attempt, delayMs, error })
       await new Promise((resolve) => setTimeout(resolve, delayMs))
+      if (Date.now() >= retryDeadline) {
+        observer.onGaveUp?.({ attempts: attempt, error, transient })
+        throw error
+      }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const delayMs = Math.min(retryDelayMs(policy, attempt), remainingMs)
observer.onRetry?.({ attempt, delayMs, error })
await new Promise((resolve) => setTimeout(resolve, delayMs))
const delayMs = Math.min(retryDelayMs(policy, attempt), remainingMs)
observer.onRetry?.({ attempt, delayMs, error })
await new Promise((resolve) => setTimeout(resolve, delayMs))
if (Date.now() >= retryDeadline) {
observer.onGaveUp?.({ attempts: attempt, error, transient })
throw error
}

The boot open re-runs the schema apply, and applyPostgresSchema refuses to
repeat a DDL lock timeout on purpose: relation locks are granted in queue order,
so a repeat parks every writer behind the same statement again. Gating the boot
retry on the full request-path classifier would have re-queued it up to 16 times
in 45s on sustained 55P03 - the mechanism behind the 2026-09-16 outage.

The boot call site now has its own predicate: pool connect failures (both
connect-timeout messages and an acquire-marked early-ended socket) plus 08001
and 08006. Lock and overload SQLSTATEs - 55P03, 57014, 53300 - exit on the first
attempt. The retry predicate moves onto the policy because what a step re-runs,
not the request path, decides what it may repeat; the startup reconcile keeps
the full classifier, which is what lets it wait out 55P03.

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

ℹ️ No critical issues — two defer-able test/observability nits.

Reviewed changes

  • Boot database retry — index.ts now opens the database through openRelayDatabaseAtBoot, which retries openRelayDatabase only on transient errors within a 20-attempt / 45s window using exponential backoff (250ms → 4s plus jitter).
  • Shared startup retry — the director reconcile retry loop is lifted into database-startup-retry.ts and both callers use it; reconcile keeps its exact attempt budget, flat 250ms delay (baseDelayMs === maxDelayMs), and both log events.
  • Bounded error categories — postgresErrorCodeCategory is extracted from reportPostgresQueryFailure and reused by the new boot logs, which emit only allowlisted codes plus a connectionTimeout boolean.

The refactor preserves reconcile semantics exactly, and retrying the whole open is safe: openRelayDatabase closes what it built on throw, the untimed schema pool closes in its finally, and the schema apply is catalog-prechecked and idempotent. The classifier covers the fleet's Connection terminated due to connection timeout via message match, and no raw driver text reaches the logs.

ℹ️ Nitpicks

  • boot-database-open.test.ts:43 asserts only delayMs: expect.any(Number), so the exponential 250ms → 4s sequence the PR body documents is not pinned — a regression to a flat delay would still pass. Asserting the first few delays would protect the mechanism.
  • postgres-query-failure.ts:5 omits 28P01, so a password-auth boot failure logs code: 'unknown' on the new orca_relay_boot_database_failed event (asserted at boot-database-open.test.ts:60). Since boot diagnostics are the point of the new event, adding that fixed SQLSTATE (no credential risk) would make the most common permanent failure identifiable.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

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

✅ No new issues found.

Reviewed changes (delta since 3e792fa)

  • Narrowed boot retry gate — the boot open now retries only isBootDatabaseUnreachable: the pool's connect-timeout messages, an acquire-boundary Connection terminated unexpectedly, and SQLSTATE 08001/08006. 55P03, 57014, 53300, 40001, 40P01, and 57P03 are now terminal at boot, so the schema apply is never re-queued behind writers.
  • Per-caller retry predicate — DatabaseStartupRetryPolicy gains an optional isRetryable; the shared loop defaults to isRelayDatabaseTransientError, so the director reconcile keeps the full classifier, attempt budget, and both log events unchanged. The observer field rename transient → retryable is applied consistently.
  • Tests — new cases pin 55P03/57014/53300 exiting on the first attempt with no retry event, plus 08006 being retried.

I checked the DDL rationale against apply-postgres-schema.ts: with retryLockTimeout unset it throws 55P03 immediately rather than re-queueing, so excluding it from the boot gate is exactly what avoids the 2026-09-16 re-queue pattern. The observed fleet error (Connection terminated due to connection timeout) is still matched by isPostgresPoolConnectFailure, so the fix still covers the reported crash.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@Jinwoo-H
Jinwoo-H merged commit ce5d8c0 into main Sep 18, 2026
25 checks passed
@Jinwoo-H
Jinwoo-H deleted the fix/relay-boot-database-retry branch September 18, 2026 21:55
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