Repository navigation
Cache only settled bb connect gate lookups so a cancelled request cannot hang others - #5142
Merged
Merged
Conversation
…hers The gate's label, session, machine credential and desktop grant caches stored the pending D1 lookup and let later requests await it. In Workers a lookup belongs to the request that started it; when that request is cancelled, the lookup never settles, and every request for the same label or cookie in that isolate waited until the entry expired 15-20 s later. Since the gate deadline shipped these show up as 504s at the routing stage, about 6,500 across 179 hosts in three hours. The caches now store a lookup's result once it settles. Concurrent cold requests each query D1. Invalidating an entry still keeps a lookup that was in flight from writing it back. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test advanced fake time 3 s right after starting the dial, but the dial first awaits a real SHA-256 digest. On a loaded CI runner the digest had not finished, so the slow event saw the routing stage. The test now waits until the dial reaches the tunnel object. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Oct 20, 2026
## Human comments
## What was wrong
Since about Oct 19, sends and page loads over bb Connect keep failing
with `502 {"code":"connect_gate_error"}` ("bb connect hit a temporary
problem"). The failures come in fleet-wide waves across every colo and
host, up to 11,218 a minute at 17:24 UTC on Oct 20. Stored Workers Logs
record 65,273 of them on Oct 19 and 98,036 on Oct 20, against 5k–15k a
day the week before. They take about 5 ms and also hit
`/api/connect/desktop-session`, which touches only D1 (no Durable
Object), in the same minutes. So the throwing dependency is D1. The
exception text is `D1_ERROR: D1 DB is overloaded. Requests queued for
too long.` (staging tail of the same failure; production logged `{}` for
the error, which this PR also fixes).
D1 is overloaded because the gate's own query rate grew. #5142 (deployed
Oct 7 23:05 UTC) replaced the single-flight lookup caches with
`SettledLookupCache` so a cancelled request could not hang others. That
also dropped coalescing, so every request that misses the label,
session, or machine-credential cache at the same moment runs its own D1
query. A page load fires 20–30 parallel requests, so each cache expiry
became a 20–30-query herd per isolate. The herds also grow as D1 slows
down, because lookups stay in flight longer. Production D1 reads per
1,000 gate requests:
| Day (UTC) | Gate requests | D1 reads | Reads per 1k requests | Avg D1
queries/s |
| --- | --- | --- | --- | --- |
| Oct 5 | 12.9M | 5.13M | 397 | 70 |
| Oct 7 | 12.8M | 5.50M | 431 | 76 |
| **Oct 8** (first full day after #5142) | 13.5M | 7.32M | **542** | 97
|
| Oct 13 | 15.6M | 9.64M | 616 | 127 |
| Oct 17 | 17.2M | 12.21M | 710 | 160 |
| Oct 19 | 20.5M | 14.75M | 720 | 192 |
| Oct 20 (partial) | 15.9M | 12.04M | 758 | 156 |
D1 serves about 200–250 queries/s serially, measured on Oct 7. On Oct 20
the gate's per-minute peaks reach 12–15k reads (about 250 qps), so
bursts overflow D1's queue and every in-flight lookup fails.
## What changed
- `apps/connect/src/session.ts`: `SettledLookupCache` coalesces
concurrent misses again without sharing a promise across requests. The
first request for a key runs the lookup and records its settled outcome
on a plain object. Concurrent requests for the same key poll that object
on their own 10 ms timers and return its value, or rethrow its error. No
request ever awaits a promise created by another request, so #5142's
cancelled-request hang cannot come back. If a lookup has not settled
within `LOOKUP_JOIN_TIMEOUT_MS` (2 s), for example because its request
was cancelled, the next request takes over with a fresh lookup that
later waiters join. `fresh` lookups (tunnel dials) still always query
D1. TTLs and revocation behavior are unchanged.
- `apps/connect/src/worker.ts`: the catch-all logs `String(error)`. It
used to log the `Error` object, which Workers Logs stores as `{}`, so
production has no exception text.
No wire, CLI, or schema changes. Merging deploys the gate (one tunnel
reconnect wave, like any gate deploy).
Not changed: D1 stays the bottleneck as traffic grows (gate requests
went up 60% in two weeks). This PR undoes the #5142 regression; the
planned PlanetScale move is the structural fix.
## How you verified
- New tests in `apps/connect/src/session.test.ts`, all failing on main:
a 20-request burst runs 1 D1 lookup instead of 20; a failed lookup is
shared with its waiters instead of re-run; a lookup that never settles
is replaced after the join timeout by exactly one new lookup. The three
existing "earlier lookup never settled" tests still pass, so the #5142
hang stays fixed.
- `pnpm exec turbo run typecheck lint test --filter=@bb/connect`: 270
tests pass.
- Staging (`bb-connect-staging`, deployed main then this branch, same
scripts, same unauthenticated GETs):
| Staging run | main (9ecb9bc) | this branch |
| --- | --- | --- |
| 6 bursts of 40 concurrent requests to one label, 16 s apart | 240 D1
reads | 47 D1 reads |
| 20 hosts × bursts of 20 every 4 s, 60 s (6,000 requests) | 3,822 D1
reads | 1,026 D1 reads |
| 60 hosts × bursts of 20 every 4 s, 60 s (~17.5k requests, ~300 req/s)
| **9,604 gate 502s (55%)** | **0 gate 502s** |
The 502s on main are `D1_ERROR: D1 DB is overloaded. Requests queued for
too long.` At 100 hosts (~430 req/s) both builds saturate staging D1
(about 60% 502s each), so this is headroom, not immunity. Staging is
back on main's gate.
> AGENT GENERATED
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Human comments
What was wrong
The gate's label, session, machine credential and desktop grant caches (
apps/connect/src/session.ts,desktop-session.ts) stored the pending D1 lookup promise in isolate-global maps and let later requests await it. In Workers, a lookup belongs to the request that started it. When that request's client cancels mid-lookup (page navigation, an aborted fetch), the lookup never settles. Every later request for the same label or cookie in that isolate then waited on it until the entry expired, 15 s for labels and 20 s for sessions and credentials. Before #5113 those requests hung indefinitely; this is the "stuck submission" behind the composer that kept spinning. Since #5113 they end as504 timed out checking access (stage: routing). Productionbb_connect_gate_eventsrecorded about 6,500 routing stalls across 179 hosts in the three hours after that deploy, clustered per host in bursts no longer than the cache TTL (for example 56 stalls on one host within 14 s). The same failure mode in another Workers app: https://zenn.dev/coji/articles/cloudflare-workers-better-auth-hanging-promiseWhat changed
apps/connect/src/session.ts:SettledLookupCachereplacescacheGet/cacheStore. It stores a lookup's value after it settles and never hands a pending promise to another request. Deleting a key bumps a generation, so a lookup that was in flight when its entry was invalidated (session refresh, credential revocation) does not write a stale value back, as before. Failed lookups are still not cached.session.tsand the desktop grant cache indesktop-session.tsuse it.No wire, CLI or doc changes.
How you verified
Tests in
apps/connect/src/session.test.ts:Commands:
pnpm exec turbo run typecheck test lint --filter=@bb/connect(220 tests pass).Staging (
bb-connect-staging): on one HTTP/2 connection, a request is cancelled 60–200 ms after it is sent, while its lookup is in flight, then two normal requests follow. Before this change, every attempt inside that window (4 of 4) left the follow-up requests stuck in routing for 30 s and ending in 504. With this change, 6 of 6 attempts at 60, 80, 100, 120, 150 and 200 ms answered in 0.2–0.5 s (503 offline, since no bb was connected to that staging label, which means routing completed).Not changed: about 12,500
response-headstalls in the same window, where the request reached the bb but it did not answer within 30 s (many on/internal/session/open). That is a separate issue.🤖 Generated with Claude Code