Skip to content

fix(relay): serve readiness from last-known-good during auth or SQL blips - #21161

Merged
Jinwoo-H merged 2 commits into
mainfrom
relay-readiness-grace
Sep 17, 2026
Merged

Jinwoo-H merged 2 commits into
mainfrom
relay-readiness-grace

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​520 $\color{#cf222e}{\Huge{\mathbf{−}}}$​12 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​508
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​183 $\color{#cf222e}{\Huge{\mathbf{−}}}$​41 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​142

ELI5

Every relay machine answers a "are you ready for traffic?" question that the load balancer asks every 10 seconds. It used to answer "no" the instant the login service or the database hiccuped, even though it was still happily carrying thousands of live connections. The load balancer took it out of rotation, and everyone connected to it got dropped. Now a machine that answered "yes" a moment ago keeps answering "yes" for a while longer while that dependency is down, and it says so out loud in the logs and in its own answer.

What Changed

Before: /ready fetched the auth JWKS document (uncached, 2 second timeout) and then ran SELECT 1, and returned 503 on the first failure of either. The load balancer health check has an unhealthy threshold of 2 at a 10 second interval, so a shared dependency failure marked every cell unhealthy in about 30 seconds and every connected host was dropped. That is what happened on 2026-09-16: auth returned 5xx for roughly 40 minutes, all 23 cells went unhealthy, and about 15k connections were cut. The cells themselves were fine, and the real token verifier caches JWKS keys in process, so it kept verifying tokens the whole time.

After: /ready remembers when each dependency last answered successfully and keeps reporting ready while the failed one is inside its own window. Past the window it reports not ready exactly as before. A process that has never had a successful probe stays not ready, so a cold boot still gates on real dependencies.

Mechanism details:

  • Two windows, two clocks. ORCA_RELAY_READINESS_JWKS_GRACE_MS defaults to 15 minutes, ORCA_RELAY_READINESS_SQL_GRACE_MS to 3 minutes. Both are bounded to 0 through 3,600,000 ms, and 0 disables that window and restores the old fail-on-first-error answer. Each dependency tracks its own last success, so a healthy JWKS poll cannot hold a dead Postgres inside its window.
  • Both dependencies are probed on every poll. Previously a JWKS failure short-circuited the SQL probe, which would have let the SQL clock age with no evidence behind it. They now run concurrently and the results are combined.
  • Per-dependency grace events. Entering and leaving a window each log exactly once per dependency, as orca_relay_readiness_grace_entered and orca_relay_readiness_grace_left, carrying dependency, whether leaving was recovered or expired, the age of the last success, and the window in force. JWKS recovering at the same moment SQL fails logs both sides rather than nothing.
  • The readiness observation gained fields, and lost none. degraded: true, degradedDependencies, and failures (when both dependencies failed in the same poll) join the existing payload. The event name cells publish, orca_relay_readiness_check, is unchanged, so existing log queries and dashboards keep working. A degraded answer now logs at WARNING rather than INFO.
  • /ready says so in its body. Status code and the healthy body are unchanged: 200 with {"ok":true}. When the answer comes from a window it is 200 with {"ok":true,"degraded":true,"dependency":["sql"]}.
  • The polling cadence (cacheMs) and the observe callback are untouched.
  • MIG autohealing continues to use the dependency-free /health endpoint. That split is deliberate and is not changed here.

Why

The load balancer check turned an auth outage into a relay outage. A cell that cannot reach the JWKS host or Postgres cannot accept new hosts, but the connections it already carries keep working, so removing it from rotation destroys far more than it protects.

The two windows are different lengths because the two failures mean different things. Auth key rotation is rare and the token verifier caches keys in process, so a cell rides out a JWKS outage with no loss of function at all. A cell that cannot reach Postgres is more compromised, but still not usefully removed: each cell is its own load balancer backend, so failing readiness never re-routes a host, it only makes that hostname unreachable. A host that reaches a SQL-dead cell for a new session gets WRONG_CELL and is re-placed by the director, and existing control sockets survive a generic Postgres error. Three minutes rides a Cloud SQL failover; per-cell SQL faults are real, so the window stops well short of hiding one for a quarter of an hour.

Alternatives considered:

  • Drop the JWKS check from /ready. Rejected: it is the check that keeps a genuinely broken cell out of rotation at boot, and dropping it means a cell that can never verify a token still advertises itself as ready.
  • Drop the SQL probe. Rejected for the same reason, so a window applies to it instead.
  • Cache the JWKS fetch inside the readiness probe. That only hides the auth dependency; it gives the SQL probe no protection at all and makes the readiness answer silently stale with no signal.
  • One window for both dependencies. Rejected on review: 15 minutes is right for JWKS and too long for a per-cell SQL fault, and a single shared clock lets one healthy dependency mask the other.
  • Lengthen the load balancer unhealthy threshold. That slows every kind of removal, including the ones we want to be fast, and it is configured outside this repository.

Linked Issue

N/A. This came out of the 2026-09-16 auth incident review rather than a tracked issue.

Visual Proof

N/A. This is a backend health-check endpoint with no user interface.

Testing

Unit tests only. This is server-side logic with no platform-specific code, no path handling, and no client-facing wire change.

cd cloud/apps/relay && pnpm typecheck && pnpm test
cd cloud/apps/relay-ops && pnpm typecheck && pnpm test

Relay suite: Test Files 63 passed | 20 skipped (83), Tests 645 passed | 104 skipped (749).
Relay-ops suite: Test Files 12 passed (12), Tests 96 passed (96).

New tests in cloud/apps/relay/src/relay-readiness.test.ts, suite relay readiness last-known-good grace:

  • stays ready while a JWKS failure sits inside the default fifteen minute window
  • drops readiness once the JWKS window expires
  • gives SQL a shorter window than JWKS by default
  • keeps a process that never succeeded out of the grace window
  • measures the grace window on the injected clock, not wall time
  • logs once on entering grace and once on leaving it
  • reports an expired window once when the dependency never comes back
  • restarts the grace window from the most recent success
  • never serves grace when the window is disabled
  • keeps one clock per dependency so a healthy JWKS cannot hold SQL open
  • logs both sides of an overlap when one dependency recovers as the other fails
  • probes SQL on every poll even while JWKS is failing
  • serves a stale ready answer for at most the cache window after grace expires

New file cloud/apps/relay/src/relay-ready-endpoint.test.ts:

  • answers a healthy cell with the unchanged body
  • keeps the 200 the load balancer needs but marks a remembered answer
  • still fails the cell out of rotation once no window covers the failure

New tests in cloud/apps/relay/src/relay-observability.test.ts:

  • flags a readiness answer served from the last known good probe
  • separates entering the readiness grace window from leaving it

New tests in cloud/apps/relay/src/config.test.ts:

  • defaults readiness grace to fifteen minutes for JWKS and three for SQL

  • reads an unset readiness grace variable as the default, never as zero

  • 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

  • Deployment: neither environment variable is set anywhere in cloud/infra, so production runs on the defaults. Turning a window off, which is the kill switch for this change, needs a Terraform change to reach production. No Terraform edit is included here.
  • Empty environment values: an unset Cloud Run variable arrives as an empty string, and z.coerce.number() reads that as 0. Both variables preprocess '' back to undefined so an unset value means the default and never means "window off". Covered by a test.
  • relay-ops: the monitor and the resource inventory read only the HTTP status of /ready, never its body, so the added fields change nothing for them. The consequence worth knowing is that cell.<id>.ready stays 1 while a cell is serving from a window, which is the intended behaviour; the grace log events are where that state is visible.
  • Security: a window never extends token trust. Token verification is a separate path (relay-token-verifier.ts) and is unchanged; this only affects whether the load balancer keeps sending traffic to a cell. The observation payload still carries only the fixed failure reason strings, never error text, so nothing sensitive reaches the logs.
  • Backwards compatibility: both config fields are optional and fall back to the built-in defaults, so existing deployments need no environment change. No wire format, RPC parameter, or client-visible contract changed.
  • Cross-platform / SSH / mobile: not applicable. Server-side HTTP endpoint logic only.
  • Performance: the two probes now run concurrently rather than in sequence, so a poll is no slower than before. The added state is a handful of variables per process.

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)

…lips

The load balancer health check hits /ready, which re-probed the auth JWKS
endpoint and Postgres on every poll and reported not-ready on the first
failure. On 2026-09-16 an auth outage therefore took every cell out of the
load balancer within ~30s and dropped every connected host, even though the
token verifier caches keys in process and kept verifying tokens.

/ready now remembers when each dependency last answered and keeps reporting
ready while the failed one stays inside a grace window
(ORCA_RELAY_READINESS_GRACE_MS, default 15 minutes, 0 disables). A process
that has never succeeded still gates on the real dependencies, so cold boot
is unchanged. Grace answers carry degraded plus the failure reason on the
existing readiness observation, and entering or leaving grace logs once.

MIG autohealing still uses the dependency-free /health endpoint.
… poll

Review follow-ups on the last-known-good readiness window.

An unset environment variable arrives as an empty string, which z.coerce
reads as 0, so the single ORCA_RELAY_READINESS_GRACE_MS would have switched
the window off instead of falling back to its default. The two replacement
variables preprocess '' to undefined.

JWKS and SQL now get separate windows and separate clocks:
ORCA_RELAY_READINESS_JWKS_GRACE_MS defaults to 15 minutes, and
ORCA_RELAY_READINESS_SQL_GRACE_MS to 3 minutes. Each cell is its own load
balancer backend, so failing readiness never re-routes a host, it only makes
that hostname unreachable, and a host that lands on a SQL-dead cell gets
WRONG_CELL and is re-placed by the director. Three minutes rides a Cloud SQL
failover without hiding a per-cell fault for a quarter of an hour.

Both dependencies are probed on every poll. A JWKS failure used to
short-circuit the SQL probe, which let the SQL clock age with no evidence
behind it. Grace transitions are emitted per dependency, so JWKS recovering
while SQL fails logs both sides instead of nothing.

/ready keeps its 200 and its {ok:true} body when healthy, and adds
degraded plus the dependency list when the answer comes from a window.
@Jinwoo-H
Jinwoo-H marked this pull request as ready for review September 17, 2026 05:21

@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 — one minor semantic inconsistency in the readiness observation, plus an operational note.

Reviewed changes

  • Per-dependency last-known-good clocks — relay-readiness.ts replaces the fail-on-first-error probe with a RelayReadinessProbe that tracks a separate success timestamp per dependency and keeps the cell ready while a failed dependency sits inside its own window (jwks 15 min, sql 3 min, both 0-disablable).
  • Both dependencies probed every poll — check() runs probeJwks and probeSql concurrently through Promise.all, so a SQL clock can no longer age with no evidence behind it, and failures reports both when they fail together.
  • Grace events — entering, recovering, and expiring each emit exactly one orca_relay_readiness_grace_entered/_left event via recordReadinessGrace, carrying dependency, failure, lastSuccessAgeMs, and graceMs.
  • /ready body — still 503 when not ready and still {ok:true} when healthy, but a windowed answer is {ok:true, degraded:true, dependency:[...]}; a degraded answer logs at WARNING.
  • Config plumbing — ORCA_RELAY_READINESS_{JWKS,SQL}_GRACE_MS are bounded 0..3_600_000, with '' preprocessed back to undefined so an unset Cloud Run variable means the default, never "window off".
  • Tests — new relay readiness last-known-good grace suite (window boundaries, restart-from-last-success, per-dependency isolation, both sides of an overlap, SQL probed during JWKS failure, cache-vs-grace interaction), a new /ready endpoint suite, the two new observability records, and the config default/unset cases.

ℹ️ The new degraded state is visible only in logs, while the existing ops detectors still read /ready as a hard dependency check

/ready can now return 200 for up to 15 minutes while the auth JWKS endpoint is unreachable, and up to 3 minutes while Postgres is. relay-ops' incident-monitor.ts:415 (cell.<id>.ready equal 1) and the Terraform/ops docs (cloud/infra/terraform/README.md:313, cloud/docs/orca-relay-operations.md:103) describe /ready as the SQL/JWKS-backed gate, and nothing is updated to consume the new orca_relay_readiness_grace_entered event or the body's degraded flag. The PR body calls this out and says the grace logs are where the state is visible, but as it stands no monitor rule or alert keys off them, so the only automated cell-level detector reads green through a real auth outage.

Technical details
# New readiness state has no detector

## Affected sites
- `cloud/apps/relay-ops/src/incident-monitor.ts:415` — emits `cell.<id>.ready` from the HTTP status; stays 1 through a window.
- `cloud/infra/terraform/README.md:313` — "SQL/JWKS-backed `/ready` controls LB admission".
- `cloud/docs/orca-relay-operations.md:103` — "dependency-backed `/ready`" in the preflight description.

## Required outcome
- Decide whether a dependency outage should continue to surface as a cell-level fault while inside
  the grace window. If yes, add a signal that reads the new state (e.g. a rule on
  `orca_relay_readiness_grace_entered`, or have `/ready` consumers treat
  `degraded: true` as a distinct health state), and note the window in the ops doc that calls
  `/ready` dependency-backed.

## Open questions for the human
- Is the silence during the window intended to also suppress paging for an auth outage, or is the
  grace meant only to keep the cell in LB rotation while a separate signal still fires?

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

jwksLatencyMs: Math.max(0, jwksCompletedAt - startedAt),
sqlLatencyMs: failure?.startsWith('jwks_') ? 0 : Math.max(0, completedAt - sqlStartedAt),
...(failures.length > 1 ? { failures } : {}),
...(degraded.length > 0 ? { degraded: true, degradedDependencies: [...degraded] } : {}),

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.

When one dependency's window has expired while the other is still inside its window (e.g. JWKS failed 1 min ago, SQL failed 4 min ago), degraded is populated even though cached is false. The observation then reads ready: false with degraded: true, degradedDependencies: ['jwks'], which contradicts both the field's meaning (the answer is served from last-known-good) and what /ready exposes — the endpoint only emits degraded when ready() is true.

Technical details
# `degraded` is not gated on the overall ready answer

## Affected sites
- `cloud/apps/relay/src/relay-readiness.ts:165-175` — `degraded` is built from the per-dependency settlements only; `cached` is not consulted.

## Required outcome
- A record with `ready: false` must not claim it is being served from last-known-good, so the `degraded`/`degradedDependencies` fields should only appear when the combined answer is ready.

## Suggested approach
- Gate the spread on `cached && degraded.length > 0`. The per-dependency diagnosis is still available through `failure`/`failures` in the not-ready case.
Suggested change
...(degraded.length > 0 ? { degraded: true, degradedDependencies: [...degraded] } : {}),
...(cached && degraded.length > 0 ? { degraded: true, degradedDependencies: [...degraded] } : {}),

@coderabbitai

coderabbitai Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

Relay readiness now probes JWKS and SQL concurrently with independent grace periods. It reports degraded dependencies while prior successful checks remain within grace. It emits grace transition events and exposes a probe object with check() and degradedDependencies(). Configuration parses bounded grace values. The server wires these values and degradation data into the app. The /ready endpoint returns degraded dependency details, and observability records degraded checks and grace transitions.

Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to 187a2

A dependency can remain readiness-covered longer than its configured grace period after it fails, potentially keeping the relay ready while that dependency is unavailable. Correct the per-probe timestamping before merge.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed and covers the change, rationale, testing, visual proof, risks, and checklist. However, the required Linked Issue section contains “N/A,” while the template requires an iss… Add the issue reference in the Linked Issue section, for example “Fixes #1234.” If no issue exists, create or link an incident-review issue before merging.
Docstring Coverage ⚠️ Warning Docstring coverage is 8.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 9 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: preserving relay readiness during temporary authentication or SQL dependency failures.
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.
Full details: Description check

Explanation

The description is detailed and covers the change, rationale, testing, visual proof, risks, and checklist. However, the required Linked Issue section contains “N/A,” while the template requires an issue link.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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: 8f67c0e5-8a1b-4944-9e95-c0818fed7350

📥 Commits

Reviewing files that changed from the base of the PR and between 0699d73 and 187a2bf.

📒 Files selected for processing (9)
  • cloud/apps/relay/src/app.ts
  • cloud/apps/relay/src/config.test.ts
  • cloud/apps/relay/src/config.ts
  • cloud/apps/relay/src/relay-observability.test.ts
  • cloud/apps/relay/src/relay-observability.ts
  • cloud/apps/relay/src/relay-readiness.test.ts
  • cloud/apps/relay/src/relay-readiness.ts
  • cloud/apps/relay/src/relay-ready-endpoint.test.ts
  • cloud/apps/relay/src/relay-server.ts

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

Comment on lines +115 to +162
return { value, latencyMs: Math.max(0, now() - startedAt) }
}

export function createRelayReadiness(
database: RelayDatabase,
jwksUrl: string,
options: RelayReadinessOptions = {}
): () => Promise<boolean> {
): RelayReadinessProbe {
const fetchImpl = options.fetch ?? fetch
const timeoutMs = options.timeoutMs ?? 2_000
const cacheMs = options.cacheMs ?? 10_000
const now = options.now ?? Date.now
const settleJwks = createDependencyGrace(
'jwks',
options.jwksGraceMs ?? RELAY_READINESS_JWKS_GRACE_MS
)
const settleSql = createDependencyGrace('sql', options.sqlGraceMs ?? RELAY_READINESS_SQL_GRACE_MS)
let cachedAt = Number.NEGATIVE_INFINITY
let cached = false
let lastObservedReady: boolean | undefined
let degraded: RelayReadinessDependency[] = []

return async () => {
if (now() - cachedAt < cacheMs) return cached
const startedAt = now()
let jwksCompletedAt = startedAt
let sqlStartedAt = startedAt
let failure: RelayReadinessFailure | undefined
const probeJwks = async (): Promise<RelayReadinessFailure | undefined> => {
try {
let response: Response
try {
response = await fetchImpl(jwksUrl, { signal: AbortSignal.timeout(timeoutMs) })
} catch (error) {
failure = fetchFailure(error)
throw error
} finally {
jwksCompletedAt = now()
}
if (!response.ok) {
failure = 'jwks_http_failed'
throw new Error(failure)
}
sqlStartedAt = now()
try {
await database.query('SELECT 1 AS ready')
} catch (error) {
failure = 'sql_failed'
throw error
}
const response = await fetchImpl(jwksUrl, { signal: AbortSignal.timeout(timeoutMs) })
return response.ok ? undefined : 'jwks_http_failed'
} catch (error) {
return fetchFailure(error)
}
}

const probeSql = async (): Promise<RelayReadinessFailure | undefined> => {
try {
await database.query('SELECT 1 AS ready')
return undefined
} catch {
// The load balancer only needs the boolean; the safe reason is emitted below.
// The load balancer only needs the boolean; the safe reason is all that is emitted.
return 'sql_failed'
}
}

const check = async (): Promise<boolean> => {
if (now() - cachedAt < cacheMs) return cached
const startedAt = now()
const [jwks, sql] = await Promise.all([timed(now, probeJwks), timed(now, probeSql)])
const completedAt = now()
cached = failure === undefined
const jwksSettlement = settleJwks(completedAt, jwks.value)
const sqlSettlement = settleSql(completedAt, sql.value)

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '60,200p' cloud/apps/relay/src/relay-readiness.ts
rg -n 'completedAt|lastSuccess|graceMs|timed\\(' cloud/apps/relay/src/relay-readiness.ts cloud/apps/relay/src/relay-readiness.test.ts

Repository: stablyai/orca

Length of output: 4771


🏁 Script executed:

#!/bin/bash
sed -n '1,260p' cloud/apps/relay/src/relay-readiness.test.ts
printf '\n--- related references ---\n'
rg -n -C 3 'cacheMs|jwksGraceMs|sqlGraceMs|createDependencyGrace|lastSuccessAt|completedAt' cloud/apps/relay/src cloud/apps/relay

Repository: stablyai/orca

Length of output: 41022


Use each dependency's completion time for its grace clock.

completedAt is recorded only after both probes finish. If JWKS succeeds quickly and SQL finishes much later, the JWKS success is recorded at the SQL completion time. A subsequent JWKS failure can therefore remain grace-covered longer than jwksGraceMs after the actual successful JWKS probe.

Return a completion timestamp from timed, then pass each dependency's timestamp to its settlement function.

Proposed fix
 async function timed<T>(
   now: () => number,
   run: () => Promise<T>
-): Promise<{ value: T; latencyMs: number }> {
+): Promise<{ value: T; latencyMs: number; completedAt: number }> {
   const startedAt = now()
   const value = await run()
-  return { value, latencyMs: Math.max(0, now() - startedAt) }
+  const completedAt = now()
+  return {
+    value,
+    latencyMs: Math.max(0, completedAt - startedAt),
+    completedAt
+  }
 }
-    const jwksSettlement = settleJwks(completedAt, jwks.value)
-    const sqlSettlement = settleSql(completedAt, sql.value)
+    const jwksSettlement = settleJwks(jwks.completedAt, jwks.value)
+    const sqlSettlement = settleSql(sql.completedAt, sql.value)

@Jinwoo-H
Jinwoo-H merged commit 69787e7 into main Sep 17, 2026
46 checks passed
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…lips (stablyai#21161)

* fix(relay): serve readiness from last-known-good during auth or SQL blips

The load balancer health check hits /ready, which re-probed the auth JWKS
endpoint and Postgres on every poll and reported not-ready on the first
failure. On 2026-09-16 an auth outage therefore took every cell out of the
load balancer within ~30s and dropped every connected host, even though the
token verifier caches keys in process and kept verifying tokens.

/ready now remembers when each dependency last answered and keeps reporting
ready while the failed one stays inside a grace window
(ORCA_RELAY_READINESS_GRACE_MS, default 15 minutes, 0 disables). A process
that has never succeeded still gates on the real dependencies, so cold boot
is unchanged. Grace answers carry degraded plus the failure reason on the
existing readiness observation, and entering or leaving grace logs once.

MIG autohealing still uses the dependency-free /health endpoint.

* fix(relay): split readiness grace per dependency and probe both every poll

Review follow-ups on the last-known-good readiness window.

An unset environment variable arrives as an empty string, which z.coerce
reads as 0, so the single ORCA_RELAY_READINESS_GRACE_MS would have switched
the window off instead of falling back to its default. The two replacement
variables preprocess '' to undefined.

JWKS and SQL now get separate windows and separate clocks:
ORCA_RELAY_READINESS_JWKS_GRACE_MS defaults to 15 minutes, and
ORCA_RELAY_READINESS_SQL_GRACE_MS to 3 minutes. Each cell is its own load
balancer backend, so failing readiness never re-routes a host, it only makes
that hostname unreachable, and a host that lands on a SQL-dead cell gets
WRONG_CELL and is re-placed by the director. Three minutes rides a Cloud SQL
failover without hiding a per-cell fault for a quarter of an hour.

Both dependencies are probed on every poll. A JWKS failure used to
short-circuit the SQL probe, which let the SQL clock age with no evidence
behind it. Grace transitions are emitted per dependency, so JWKS recovering
while SQL fails logs both sides instead of nothing.

/ready keeps its 200 and its {ok:true} body when healthy, and adds
degraded plus the dependency list when the answer comes from a window.
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