Repository navigation
fix(relay): refuse host hellos fast when the database pool is timing them out; renewals jump the queue - #26362
Conversation
…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.
📝 WalkthroughWalkthroughPostgreSQL connections now use general and priority lanes. Control-activity renewals use priority queries. Pool-connect failures in batch renewals return Priority: ⬆️ High Merge Risk: 🟡 Moderate · up to 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)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
- Configuration used: Repository UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
aa14c944-b0e5-4f2b-a74d-7cb92adeeaa6
📒 Files selected for processing (10)
cloud/apps/relay/src/assignment-store.tscloud/apps/relay/src/control-renewal-batch-store.test.tscloud/apps/relay/src/database.tscloud/apps/relay/src/observed-relay-database.tscloud/apps/relay/src/postgres-pool-pressure.test.tscloud/apps/relay/src/postgres-pool-pressure.tscloud/apps/relay/src/postgres-priority-lane-postgres.test.tscloud/apps/relay/src/relay-host-hello-shed.test.tscloud/apps/relay/src/relay-observability.tscloud/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.
… 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.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
🟠 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 liftKeep general callers out of the pool queue ahead of priority callers.
When a priority query and a general query hold a two-connection pool,
takeGeneralSlotcan admit another general query intopool.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 liftApply 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 whenpool.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
📒 Files selected for processing (5)
cloud/apps/relay/src/database.tscloud/apps/relay/src/postgres-pool-pressure.test.tscloud/apps/relay/src/postgres-pool-pressure.tscloud/apps/relay/src/relay-host-hello-shed.test.tscloud/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).
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
🟡 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 winUse the 1,500 ms oldest-wait threshold without a waiter-count floor.
The current gate sheds only when
databasePoolWaiting >= config.databasePoolMaxand the oldest waiter reaches1_000ms. This can reject a full queue 500 ms earlier than intended. Whenconfig.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
📒 Files selected for processing (2)
cloud/apps/relay/src/relay-host-hello-shed.test.tscloud/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.
…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.
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:
503 Service UnavailableandRetry-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.PostgresPoolPressure), not inside thepglibrary's own queue, sopg'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 insidepg. 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.hostHellosShedDeltain 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:
503on the control upgrade is what the connection-ledger cap returns today (relay-server.ts), so no client sees anything new.unexpected-responselistener (src/main/runtime/relay/relay-control-client.ts,createSocket). Sowsreports the 503 as the errorUnexpected server response: 503, andconnect()rejects. The new test checks that exact path.RelayOriginPool.resolveDrainTarget's catch (relay-origin-pool.ts). That catch callsRelayDrainRetrySchedule.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.RelayAuthCoordinator.scheduleRetry, which uses the same jittered schedule.shouldRetryRelayConnectionErrorreturns true for any error that isn't an HTTP error.Retry-Afteron 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.
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: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:trueassign 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:connect()rejects, and the desktop lands inRelayOriginPool.resolveDrainTarget's catch, thenRelayDrainRetrySchedule.schedule, then the same sticky assign and the same cell.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.
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,wsandPostgresPoolPressure, with a test clock):503withRetry-After: 2, and a desktop-style client seesUnexpected server response: 503.postgres-pool-pressure.test.tsalso 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):postgres-pool-pressure.test.ts:pguses, so the existing error classifiers still recognize it.control-renewal-batch-store.test.ts: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-postgresfailed 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 typecheckis clean.I manually tested these changes locally
Automated tests added/updated, or explained why not below
AI Disclosure
Review
Agent skill upstream boundary
Notes
host hello proof failedagainst about 860 admitted in 20:02-20:08).host hello proof failedcount plushostHellosShedDelta, 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).hostHellosShedDeltashould 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.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)