Skip to content

fix(relay): refuse host hellos fast when the database pool is timing them out; renewals jump the queue - #26362

Merged
Jinwoo-H merged 3 commits into
mainfrom
relay-surge-fail-fast
Oct 8, 2026
Merged

Jinwoo-H merged 3 commits into
mainfrom
relay-surge-fail-fast

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

When a lot of desktops reconnect to a relay cell at the same moment, the cell's small set of database connections jams. Every new desktop waits in line, gives up after 2 seconds and tries again, which keeps the line full. Meanwhile, desktops that were already connected can't renew their "I'm still here" leases. With this change, once the line is at least as long as the number of connections and the person at the front has already waited half of the 2-second limit, the cell turns new desktops away at once instead of letting them wait to fail. They come back a little later. Lease renewals now go to the front of the line.

What Changed

Before: at 18:34 UTC on 2026-10-06, Google's load balancer dropped about 1,046 desktop connections to the asia-east2 cells within 2 seconds. Each cell has 16 database connections. Up to 527 requests queued for them against a 2-second wait limit. The result was 17,912 failed queries, 3,026 failed desktop sign-ins and 14,542 failed lease renewals over about a minute. Desktops took up to 1.5-2 minutes to get back.

After:

  1. Fast refusal, only when a timeout is imminent. A cell answers a new desktop control connection with 503 Service Unavailable and Retry-After: 2, but only while both of these hold: at least a full pool's worth of requests (16 in asia-east2) is waiting for a database connection, and the oldest of them has already waited 1 s of the 2 s limit. One slow request can't trip it, and neither can a queue that is still moving. A desktop that already holds a live control and is rotating its lease (a rebind, the routine control rotation CodeRabbit flagged) is never refused. Phone connections are unaffected.
  2. Renewals go first. Ordinary database work now waits in a queue the cell controls (PostgresPoolPressure), not inside the pg library's own queue, so pg's queue normally holds only lease renewals, which use a separate priority lane. One edge case: when a renewal takes the connection a waiting general caller had already been granted, that caller re-queues inside pg. A later renewal can then wait behind it, about one caller since renewals flush once a second. That caller's worst-case wait becomes about 4 s instead of 2 s.
  3. No fan-out on a jammed pool. When a batched renewal fails, the code falls back to one statement per host, up to 200 of them. If the batch failed because it never got a connection, that fallback would only add 200 more waiters to the same jammed queue, so it now skips the fallback and marks those rows failed. Each host retries on its next 15-second tick, well inside its 105-second lease.
  4. A counter. hostHellosShedDelta in the runtime metrics counts refusals, so a refused herd is visible.

Why

What shipped desktops do with the refusal (wire compatibility). Cells already send this exact response: 503 on the control upgrade is what the connection-ledger cap returns today (relay-server.ts), so no client sees anything new.

  • Desktops dial without an unexpected-response listener (src/main/runtime/relay/relay-control-client.ts, createSocket). So ws reports the 503 as the error Unexpected server response: 503, and connect() rejects. The new test checks that exact path.
  • For a desktop that was already connected, the rejection lands in RelayOriginPool.resolveDrainTarget's catch (relay-origin-pool.ts). That catch calls RelayDrainRetrySchedule.schedule, which backs off with full jitter: the cap starts at 1 s and doubles up to 5 minutes (relay-drain-retry-schedule.ts). This has shipped since v1.4.160.
  • For a desktop's first connection, the rejection reaches RelayAuthCoordinator.scheduleRetry, which uses the same jittered schedule. shouldRetryRelayConnectionError returns true for any error that isn't an HTTP error.
  • Shipped desktops do not read Retry-After on this upgrade. They back off on their own jittered schedule, not in a hot loop. The header is there for future clients and costs nothing.

Why oldest wait plus a count floor. The rule is: refuse a hello only when it would otherwise time out, so refusing can never leave a user worse off than today.

  • Healthy baseline: on 10-07 a healthy cell peaks at 2 waiters (p50, p90 and p99 of the interval maximum across all 17,274 samples from c27-c31 and c34). Deep queues are stalls, not routine load. Every interval that reached 100 or more waiters logged SQL failures and a wait of at least 1.9 s.
  • Why both signals: a queue length means something different on US cells (10 connections, about 10 ms per query) than on Asia cells (16 connections, Pacific round trips). The oldest waiter's age leads the 2 s timeout on any cell. The count floor stops a single slow waiter from tripping it. The acquire-timeout rate lags by 2 s of damage, so it stays an alert signal (feat(relay): alert on cell disconnect bursts and database pool herds #26363), not a gate.

Replay against the reviewer's 10-07 samples (all 17,274 thirty-second samples from c27-c31 and c34, ~/orca-lanes/review-26362-asia1007.tsv). Each sample is counted as a window where the instantaneous check would have been true at sampling time:

Rule Windows inside the 20:00 herd and c28 drain (20:00-20:09) Windows outside With SQL failures in the window With an acquire timeout (max wait ≥ 1.99 s)
Oldest ≥ 1 s and waiting ≥ 16 (this PR) 28 6 34 of 34 31 of 34
Waiting ≥ 32 (previous head) 24 7 31 of 31 28 of 31
  • The 6 windows outside the herd: 03:35 c30, 07:39 c30, 09:41 c29, 13:45 c30 and c27, and 14:15 c30. Three were full stalls with 68-96 SQL failures and 2 s waits.
  • The other three windows (03:35, 09:41 and 14:15) had their oldest waiter at 1.0-1.45 s and 1-3 SQL failures, but no acquire had reached 2 s yet. These are the closest calls, where a refusal came before the first timeout rather than after.

The c34 drain receiver (10-07 20:02-20:08) sheds under this rule in 10 of its 12 samples, and the data says it should. c34 admitted about 860 hosts in that window. At the same time it logged 3,623 host hello proof failed (215, 1,370, 868, 616, 465 and 89 per minute), and the oldest waiter sat at 1.90-2.00 s in all 11 samples. About four hellos in five were already timing out. The gate admits again as soon as the queue drops below 16 waiters or its oldest wait falls under 1 s. The capacity those doomed attempts were burning on their first one or two queries goes to the hellos that can still finish.

A refused desktop retrying the same cell (review F1). The director doesn't know a cell is refusing, so a desktop's sticky reconnect:true assign sends it back to the same cell. That is also what happens today, because the refusal only happens when the hello would have timed out anyway:

  • Today, a timed-out hello closes the socket with 4429. connect() rejects, and the desktop lands in RelayOriginPool.resolveDrainTarget's catch, then RelayDrainRetrySchedule.schedule, then the same sticky assign and the same cell.
  • With this change, the 503 lands in the same catch, so the backoff step and the next destination are identical. The only differences are that the desktop learns about 2 s sooner and adds no load to the pool.
  • What could make it worse: desktops reach later backoff steps sooner in wall-clock time. That only happens while the cell is timing hellos out, which is exactly when each extra attempt adds load.

A director-side signal that steers refused hosts elsewhere is a reasonable follow-up, kept out of this PR.

A failed renewal batch (review F5). A batch failure that isn't a connection failure (statement timeout, lock timeout, serialization failure) still falls back to as many as 200 per-host statements on the general lane, as it does today. That can trip the gate, but only if it leaves at least 16 waiting with the oldest at 1 s. With 200 statements behind 16 Asia connections, the tail waits around 4 s and times out. A hello admitted at that moment would queue behind them and time out too, so the refusal still only replaces a timeout. Bounding the fallback's concurrency would remove that load at its source, but it changes renewal timing, so I left it for a separate change.

Why priority instead of holding a connection back. I first held one of the 16 connections back for renewals. The existing asia-east2 drain test (drain-release-cell-row-contention-postgres.test.ts, 18 releases/s at 171 ms round trip) then failed: 5 of 180 drain releases timed out. One connection in 16 is all the margin that path has. Priority gives renewals the same protection without cutting capacity for anything else. A renewal waits for at most one in-flight statement, against a 15-second tick and a 105-second lease.

Why not just enlarge the pool.

  • It doesn't fix the herd. About 210 desktops per cell, each needing roughly 3 queries at about 350 ms, would need around 110 connections per cell to drain in 2 seconds.
  • The shared Cloud SQL instance has about 19 free connections for the whole fleet.
  • This change opens no extra database connections.

Linked Issue

Fixes # (no issue; RCA of the 2026-10-06 18:34Z asia-east2 drop)

Visual Proof

N/A. This is a server-side relay change with no UI.

Testing

  • relay-host-hello-shed.test.ts (real server, ws and PostgresPoolPressure, with a test clock):

    • 120 queued queries whose oldest has waited 0.7 s: the upgrade is accepted, because the queue is deep but moving.
    • One query that has waited 2 s on a 2-connection pool: accepted, because it is under the count floor.
    • A full queue (2 waiters) aged 1 s: 503 with Retry-After: 2, and a desktop-style client sees Unexpected server response: 503.
    • A rebind over a live control is accepted even with a full queue aged 2 s.
    • Each of the four fails when its piece of the gate is removed.
  • postgres-pool-pressure.test.ts also checks that the gate reads the oldest wait as it is right now, not the last interval's maximum.

  • postgres-priority-lane-postgres.test.ts (real Postgres, 400 ms per statement, 4-connection pool, 40-query herd):

    • A priority renewal finishes in under 1.5 s while the herd's general queries time out. A general query sent at the same moment takes more than 1.9 s.
    • The test fails if priority work goes through the general queue.
  • postgres-pool-pressure.test.ts:

    • Priority work gets the next released connection ahead of queued general work.
    • A queued general caller times out with the same message pg uses, so the existing error classifiers still recognize it.
  • control-renewal-batch-store.test.ts:

    • The batch runs on the priority lane and the per-host fallback runs on the general lane.
    • A batch that fails with "no connection" does not fan out.
  • Full relay suite against a fresh Postgres (ORCA_RELAY_TEST_POSTGRES_URL): 1,040 passed, 1 skipped. At load average 55-65 on this machine, drain-release-cell-row-contention-postgres failed in some runs, as it did for the reviewer on the merge base. It passed 3/3 when rerun alone on a fresh database. pnpm --filter @orca-cloud/relay typecheck is clean.

  • 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 copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Canary before fleet-wide shedding. Roll this image first to the next drain target only, then compare that drain with the 10-07 c34 drain receiver (3,623 host hello proof failed against about 860 admitted in 20:02-20:08).
    • Abort and roll back the canary if: the cell's host hello proof failed count plus hostHellosShedDelta, per admitted host (controls gained), comes out above that baseline. Also abort if the cell's controls take longer to reach the drained population than c34 did (about 5.5 min).
    • Also watch: hostHellosShedDelta should be zero outside pool stalls. A nonzero count with no SQL failures in the same interval means the gate fired where no timeout was imminent.
  • Rides the next cell roll. Directors build the same code, but they serve no host control upgrades (they return 404 before the new check), so nothing changes for them.
  • No wire change. The new metrics field is additive.
  • Mobile and phone connections are not refused by this check.
  • Follow-up PR: alerts.

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)

…ed; renewals jump the queue

A reconnect herd (2026-10-06 18:34Z, 1,046 asia-east2 hosts dropped by the
load balancer at once) queued hundreds of host hellos behind each cell's
16-connection pool. They timed out after 2 s, the desktops redialled into
the same queue, and control-lease renewals starved behind them.

- Host control upgrades get an immediate 503 (Retry-After: 2) once 32
  callers wait for a pooled connection. Shipped desktops already treat
  that as a connect error and back off with jittered exponential retry.
- General work now queues in PostgresPoolPressure instead of pg-pool, so
  renewal statements (priority lane) take the next released connection.
- A renewal batch that never got a connection no longer fans out into
  one statement per host.
- hostHellosShedDelta counts refusals in the runtime metrics.
@coderabbitai

coderabbitai Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

📝 Walkthrough

Walkthrough

PostgreSQL connections now use general and priority lanes. Control-activity renewals use priority queries. Pool-connect failures in batch renewals return database_error for every row without per-host retries. When the pool has at least databasePoolMax waiters and its oldest waiter has waited at least 1,000 ms, the relay rejects non-rebind host-control upgrades with HTTP 503 and Retry-After: 2. The relay records shed host hellos in its observability metrics.

Priority: ⬆️ High

Merge Risk: 🟡 Moderate · up to 910cc

Under database pressure, renewals may remain delayed and host connections may either be rejected too early or wait until timeout instead of receiving a retryable response.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 41.18% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 17 functions across 10 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 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 both main changes: fast refusal of host hellos during database-pool timeouts and priority handling for renewals.
Description check ✅ Passed The description is detailed and covers the required explanation, rationale, testing, visual proof, compatibility notes, rollout plan, and checklist. The Linked Issue section explicitly has no issue nu…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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: aa14c944-b0e5-4f2b-a74d-7cb92adeeaa6
📥 Commits

Reviewing files that changed from the base of the PR and between a551aa5 and f2c4ad2.

📒 Files selected for processing (10)
  • cloud/apps/relay/src/assignment-store.ts
  • cloud/apps/relay/src/control-renewal-batch-store.test.ts
  • cloud/apps/relay/src/database.ts
  • cloud/apps/relay/src/observed-relay-database.ts
  • cloud/apps/relay/src/postgres-pool-pressure.test.ts
  • cloud/apps/relay/src/postgres-pool-pressure.ts
  • cloud/apps/relay/src/postgres-priority-lane-postgres.test.ts
  • cloud/apps/relay/src/relay-host-hello-shed.test.ts
  • cloud/apps/relay/src/relay-observability.ts
  • cloud/apps/relay/src/relay-server.ts

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

Comment thread cloud/apps/relay/src/relay-server.ts Resolved
… length

asia-east2 queues of 50-196 waiters are routine and keep moving, so a
32-waiter limit would refuse hellos that were going to succeed. Shed only
while the oldest pool waiter has waited 1.5 s of the 2 s acquire timeout,
when a new hello would time out anyway; a refused desktop gets the same
connect error and backoff it gets today, 2 s sooner. Rebinds over a live
control (lease rotation) are never refused.
@Jinwoo-H Jinwoo-H changed the title fix(relay): refuse host hellos fast when the database pool is saturated; renewals jump the queue fix(relay): refuse host hellos fast when the database pool is timing them out; renewals jump the queue Oct 8, 2026

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

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (2)

🟠 Major · Keep general callers out of the pool queue ahead of priority… · postgres-pool-pressure.ts:105-112

cloud/apps/relay/src/postgres-pool-pressure.ts:105-112
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Keep general callers out of the pool queue ahead of priority callers.

When a priority query and a general query hold a two-connection pool, takeGeneralSlot can admit another general query into pool.connect(). If a priority renewal arrives next, the pool queues it behind that general query. The next released connection goes to general work, so the renewal does not get the promised priority. The [email protected] pool removes pending callers in queue order. (github.com)

Schedule both lanes before calling pool.connect(), or otherwise prevent a general caller from entering the pool queue ahead of priority work. Add a mixed-lane test with an already active priority query.

🟠 Major · Apply one acquisition deadline across both queues. · postgres-pool-pressure.ts:135-141

cloud/apps/relay/src/postgres-pool-pressure.ts:135-141
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Apply one acquisition deadline across both queues.

If a general caller waits almost two seconds for a general slot, the subsequent pool.connect() starts another two-second wait. Priority work can take the released connection while that general caller waits in the pool queue. The general query can therefore fail nearly four seconds after it requested a connection, rather than at the configured two-second acquire timeout. The pool starts its timeout when pool.connect() queues the caller. (github.com)

Enforce the remaining acquire budget after slot admission, including the underlying pool acquisition.


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 58c94e68-4a59-4048-ab7a-cdf1a17640e4
📥 Commits

Reviewing files that changed from the base of the PR and between f2c4ad2 and edb3f6f.

📒 Files selected for processing (5)
  • cloud/apps/relay/src/database.ts
  • cloud/apps/relay/src/postgres-pool-pressure.test.ts
  • cloud/apps/relay/src/postgres-pool-pressure.ts
  • cloud/apps/relay/src/relay-host-hello-shed.test.ts
  • cloud/apps/relay/src/relay-server.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.

Per review: require both an oldest waiter of at least 1 s and a pool's worth
of waiters, so one slow waiter cannot trip it, and state the real baseline
(p99 of 2 waiters on 10-07).

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

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟡 Minor · Use the 1,500 ms oldest-wait threshold without a waiter-count floor. · relay-server.ts:533-540

cloud/apps/relay/src/relay-server.ts:533-540
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Use the 1,500 ms oldest-wait threshold without a waiter-count floor.

The current gate sheds only when databasePoolWaiting >= config.databasePoolMax and the oldest waiter reaches 1_000 ms. This can reject a full queue 500 ms earlier than intended. When config.databasePoolMax > 1, one waiter can exceed 1,500 ms without triggering shedding. The host hello then waits for the pool timeout and can retry into the pressured queue instead of receiving the retryable 503.

Set the threshold to 1,500 ms, remove the waiter-count condition, and update the existing tests so a full queue at 1,000 ms is admitted while one waiter older than 1,500 ms is shed.

Suggested fix
-export const HOST_HELLO_SHED_OLDEST_WAIT_MS = 1_000
+export const HOST_HELLO_SHED_OLDEST_WAIT_MS = 1_500
...
       if (
         !isRebind &&
-        readRelayDatabasePoolPressure(database).databasePoolWaiting >= config.databasePoolMax &&
         readRelayDatabasePoolOldestWaitMs(database) >= HOST_HELLO_SHED_OLDEST_WAIT_MS
       ) {

ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 61a026dc-9e1e-4563-893a-db8074762f64
📥 Commits

Reviewing files that changed from the base of the PR and between edb3f6f and 910ccb4.

📒 Files selected for processing (2)
  • cloud/apps/relay/src/relay-host-hello-shed.test.ts
  • cloud/apps/relay/src/relay-server.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.

Jinwoo-H added a commit that referenced this pull request Oct 8, 2026
…26363)

* feat(relay): alert on cell disconnect bursts and database pool herds

Two alert policies that separate a load-balancer mass disconnect from a
database stall, after the 2026-10-06 18:34Z asia-east2 drop:

- Disconnect burst: over 120 code-1006 desktop control closes on one cell
  in a minute, counted from the cell's own close line. The LB's
  internal_error log entries carry the stream start as their timestamp
  (median 2.4 h before the drop), so an LB-log rate never shows the pulse.
- Pool herd: a cell runtime sample with more than 50 requests queued for a
  PostgreSQL connection (interval maximum, bar in the filter).

Also publishes orca_relay_host_hellos_shed for the refusal counter from
#26362, and pins both filters to the relay's text in a contract test.

* fix(relay): raise the cell pool-herd alert bar to 200 waiters

asia-east2 cells reach 184-196 waiters outside any herd, so >50 would have
fired in 84 episodes since 2026-10-03. >200 fires in 10, covering every known
herd. Drops the false 'healthy peak is 2 waiters' baseline from the policy text.

* docs(relay): describe pool-herd baseline as stalls, not routine load

A healthy cell peaks at 2 waiters (p99); the 50-196 readings are single-cell
stalls that already time out. The 200 bar is unchanged.
@Jinwoo-H
Jinwoo-H merged commit 3062b9d into main Oct 8, 2026
23 checks passed
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