Skip to content

perf(serving): a stream lost to a misrouted subscription reconnects at once - #776

Merged
allisonmahmood merged 2 commits into
mainfrom
perf/749-cheaper-reconnect
Oct 18, 2026
Merged

allisonmahmood merged 2 commits into
mainfrom
perf/749-cheaper-reconnect

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Oct 18, 2026 •

Copy link
Copy Markdown
Owner

When a subscription POST is refused as 409 invalid_request but still names the current stream generation and latest sequence, the stream has been lost: a current-generation loss. The shell tears it down, then waited its jittered backoff (250–500 ms right after a hello) before reconnecting. In the traced production load on #754, that wait sat in front of the first query.

Two refusals produce this loss:

  • StreamReplaced, from a host that doesn't hold the stream, such as a misrouted POST;
  • StaleSequence, from a document that just closed.

Fix

  • One immediate reconnect. On a 409 the shell reads the body. If it is invalid_request and the POST still names the current generation and latest sequence, the stream reconnects at once instead of waiting for the backoff.
  • The allowance comes back only when the document reconciles. A new hello doesn't restore it. A second loss before then waits for the backoff, as on main, so a persistent misroute can't loop faster than it does today.
  • Everything else keeps its handling:
  • ADR-0010 is updated. The stickiness cookie lasts one day (duration_seconds=86400), which is what AppStack.ts sets. The new reconnect rule is recorded next to the backoff.

What "reconciled" means

This uses the shell's existing reconciled state: the server has admitted this stream's latest sequence, and every desired subscription has been answered past its fence, by a snapshot, an up-to-date or a refusal. It is the state that already clears the Reconnecting pill.

It's the first point where the shell has proof that its POSTs reach the stream's host. A hello only proves the GET landed somewhere, and an empty set still needs its replace admitted. So between any two immediate reconnects there is at least one full, successful round trip through the stream's host.

Tests

stream.spec.ts, with the page clock paused so that no backoff timer can fire unless the test runs the clock:

  • Allowance.
    • A current-generation loss reconnects at once.
    • The new stream admits its replace while its answers are held, so it hasn't reconciled; a loss there waits for the backoff.
    • Once the answers arrive, the next loss reconnects at once again.
    • Every reconnect carries the generation it replaces.
    • Fails on main: no second hello arrives without the clock.
  • Other refusals.
    • A stale-sequence 409 leaves the stream alone.
    • 401 session_refresh_required, 409 principal_changed and 429 rate_limited each tear the stream down and wait for the backoff.
    • The unreconciled replacement's own current-generation loss then still reconnects at once, so these refusals didn't spend the allowance.
    • Passes on main and here.

I checked that each test catches the bug it pins:

  • restoring the allowance on admitted fails the first test;
  • spending it on any refusal fails the second.

pnpm verify passes locally: check, postgres-concurrency, cli-smoke, tier2-smoke and browser.

Numbers

Setup:

  • a local brightline instance, opening New Business (tier 2) as a persona;
  • a temporary, uncommitted server hook that refused every subscription POST of a document's first generation as StreamReplaced;
  • 10 loads each, timed in the shell from the 409 response.
From the refusal to… main (backoff) this branch
the new stream's request median 358 ms (274–473) 15 ms (14–18)
its hello 368 ms (282–480) 24 ms (21–30)
the first query answer 410 ms (317–781) 51 ms (49–59)

With every POST refused, a persistent misroute, over 10 s:

  • main reconnected 23 times, 300–570 ms apart;
  • this branch reconnected 27 times: the first after 23 ms, then 294–498 ms apart.

The allowance adds one immediate reconnect per unreconciled streak. Jitter alone moves the count over a 10 s window, so the totals don't measure that exactly.

Unchanged here. On main, hello resets the backoff's failure count, so a persistent misroute already reconnects every 0.25–0.5 s indefinitely instead of backing off further.

Part of #749. Steps 1 and 2, diagnosing the cause from #758's wide events and fixing it, need production data.

Made by Claude Opus 5.5 via Claude Code; reviewed with GPT-6.1-Sol.

…t once

A subscription POST refused as 409 invalid_request while it still names
the current generation and latest sequence tears the stream down. The
shell then waited its jittered backoff before reconnecting. Now the
first such loss reconnects at once. The allowance returns only when a
stream reconciles (latest sequence admitted, every subscription
answered), not on hello, so a persistent misroute falls back to the
backoff. Other refusals, including session, principal and rate limits,
keep the backoff.

ADR-0010 now records the one-day stickiness cookie the infrastructure
sets, and the new reconnect rule.

Part of #749

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added area:server Touches the server area area:ci CI, shared testing infrastructure, development scripts and tooling area:docs Touches the docs area size:m 100-500 changed lines labels Oct 18, 2026
An admitted but unanswered replacement keeps the allowance spent, and
session, principal and rate-limit refusals leave it for the next
current-generation loss. The shell's comments name the classification
a current-generation loss, which StaleSequence on a closing document
also is.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@allisonmahmood
allisonmahmood merged commit 86d4124 into main Oct 18, 2026
13 checks passed
@allisonmahmood
allisonmahmood deleted the perf/749-cheaper-reconnect branch October 18, 2026 21:39
allisonmahmood added a commit that referenced this pull request Oct 18, 2026
…nnecting every half second (#780)

The shell reset its reconnect backoff on every `hello`. When a host
accepts a document's stream but every subscription POST fails, each
reconnect gets a fresh `hello`, so the delay never got past its first
step. This happens with a persistent misroute (the POSTs are refused as
a current-generation loss) or a `429` on every POST. A document that
couldn't reconcile reopened its stream every 0.25–0.5 s for as long as
it stayed open, and each reopen cost the server a stream open and a
resolve.

## Fix

- **The backoff starts over only when a stream reconciles.** This is the
shell's existing `reconciled` state: the latest sequence is admitted and
every subscription is answered. It's the same boundary that re-arms
#776's immediate reconnect. A `hello` only proves the GET landed
somewhere.
- **A persistent misroute or rate limit now backs off.** The delay
doubles from 500 ms to its 30 s cap, jittered down to as little as half.
- **#776's one immediate reconnect is unchanged.** It still doesn't
count as a failure.
- **The session-refresh budget still resets on `hello`.** A `hello`
proves the refreshed session was accepted, and that's what the budget
guards. Moving the reset to reconciliation would let a long unreconciled
streak use up the three refreshes across ordinary token expiries. The
stream would then stop refreshing and loop on `401`s.
- **Unchanged:**
  - a successful refresh still reconnects at once and adds no failure;
  - generation fencing;
- the tier 2 bind deadline, which still takes the later of the two
delays.
- **ADR-0010** now records when the backoff resets.

## Tests

`stream.spec.ts` runs with the page clock paused. An init script records
the page clock at each stream open and at each abort, so every reconnect
delay is exact. The test sorts each delay into its backoff step: the nth
failure in a row waits between 250·2ⁿ and 500·2ⁿ ms.

| Test | Steps on this branch | On main |
| --- | --- | --- |
| Every POST misrouted (`409 invalid_request`); a stream admitted with
its answers held is lost; one reconciles; misrouted again | at once, 0,
1, 2, 3, 4, then at once, 0 | at once, 0, 0, 0, 0, 0, at once, 0 |
| Every POST `429`; a stream admitted with its answers held is lost; one
reconciles; `429` again | 0, 1, 2, 3, 4, then 0 | all 0 |
| A session refresh in the middle of a `429` streak | 0, 1, at once (the
refresh), 2 | 0, 0, at once, 0 |

The step after the admitted stream (4, not 0) pins the boundary:
resetting on `admitted` rather than on reconciliation fails both
scenario tests.

All three fail on main and pass here. The session test also checks that:
- the refresh happens exactly once;
- it reconnects without a timer;
- no notice is shown.

#776's tests and the existing session tests are unchanged and pass.

`pnpm verify` passes locally: format, lint, typecheck, synth, the
offline tests, postgres-concurrency, cli-smoke, tier2-smoke and browser
(80 tests). The new tests and #776's main test also passed 5 runs each.
The follow-up test commit passes the stream spec (28 tests) and `pnpm
check`.

## Numbers

Setup:
- a local brightline instance, opening Kudos (tier 1) as a persona;
- a temporary, uncommitted hook in `RuntimeStream.update` that refused
every subscription POST;
- stream opens counted in Chromium over 30 s from the first open.

| Every POST refused as | main | this branch |
| --- | --- | --- |
| `StreamReplaced` (misroute) | 78 reconnects, 264–521 ms apart | 7
reconnects: 37 ms (the immediate one), then 370, 872, 1284, 2788, 5165
and 13019 ms |
| `RateLimited` (`429`) | 82 reconnects, 262–507 ms apart | 6
reconnects: 463, 639, 1697, 2122, 7061 and 12282 ms |

Over 150 s of misroute on this branch, the gaps reach the cap: 17.0,
19.4, 15.1, 24.1 and 25.6 s. Without the hook, Kudos and New Business
(tier 2) each open one stream and their POSTs return `200`.

Closes #777

Made by Claude Opus 5.5 via Claude Code; reviewed with GPT-6.1-Sol.

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
allisonmahmood added a commit that referenced this pull request Oct 19, 2026
…ng Reconnecting (#783)

Release 14's What's new entry, written from \`7694bab\`. It covers
everything merged since release 13's \`through\` (\`c9b8fc4\`), and sets
the \`patchy\` release to \`0.14.0\` (\`packages/patchy/package.json\`
and \`CURRENT_RELEASE\`).

| Change | PRs |
| --- | --- |
| Improved: Tools with server code answer faster | #756, #764, #768,
#769, #771, #772, #773, #775, #778 |
| Improved: Your company's tools and pages open sooner | #759, #761,
#766, #770 |
| Fixed: Tools stop flashing Reconnecting while they load | #755, #776,
#780 |
| Improved: Publishing is quicker | #729 |
| Improved: New tools start with a tidy layout | #763 |
| Improved: Your usual is easier to scan | #721 |
| Fixed: A page that isn't there says what to do | #762 |
| Fixed: A logo Patchy can't read is refused, not a crash | #728 |
| Behind the scenes: richer logs for live data | #758 |

#720 is release 13's own entry, so it's left out.

Made by Claude Opus 5.5 via Claude Code.

Co-authored-by: Claude Opus 5.5 <[email protected]>
allisonmahmood added a commit that referenced this pull request Oct 19, 2026
# What changed

Subscription POSTs sometimes reached the host that doesn't hold the
document's stream, got a 409 `stream_replaced`, and the shell tore the
stream down and reconnected (8 of the last 15 production document
opens). The target group stuck on our `patchy_stream_affinity`
application cookie, scoped to `/api/runtime`. ALB app-cookie stickiness
only holds when a request carries both that cookie and the ALB's own
`AWSALBAPP-*` cookie, which is `Path=/`. Every other request (the page,
its scripts, the frame's `~content`) carried only the ALB cookie, so the
ALB round-robined it and its response cleared stickiness
(`AWSALBAPP-n=_remove_`). When the frame's content response landed after
the stream opened, the subscription POSTs that followed alternated
hosts.

The load balancer now owns stickiness with its own cookie, and ours is
gone:

- **Infra.** The `Hosts` target group uses duration-based stickiness
(`stickiness.type=lb_cookie`, the ALB's `AWSALB` cookie), still one day.
The ALB sets `AWSALB` on the page's own response, before the shell sends
anything else. Once a browser holds that cookie and its host is healthy,
every request from it reaches that host. Two tabs opened at once without
a cookie, or a drain, can briefly put a stream on another host than the
cookie names; on target loss the ALB picks a healthy host and updates
the cookie. The existing 409 → immediate reconnect (#776) covers those
gaps. The tier 2 spike script gets the same attributes.
- **Server.** The stream no longer sets `patchy_stream_affinity`. The
subscription request event drops `affinityCookie`/`affinityMatched` and
keeps `balancerCookie`, now keyed on the `AWSALB` name, never its value.
`documentConnected: false` plus `replica` still identifies a misroute.
Wire bodies are unchanged. Without the cookie the stream API needs no
`secure` flag, so its `layer` and `layerLocal` become one `layer`.
- **Docs.** The runtime stream description and `docs/API.md`, ADR-0010's
stickiness contract (with why app-cookie stickiness failed), ADR-0012's
production topology, the Operations refusal query and spike notes, and
the Analytics glossary.

Closes #749

## How it was verified

- [x] `pnpm check` and `pnpm verify` pass locally (format, lint,
typecheck, synth, tests, postgres-concurrency, cli-smoke, tier2-smoke,
browser).
- [x] Updated tests: the infra stack test pins the new attributes; the
stream API and wide event tests cover the remaining `balancerCookie`
field.

The synthesized `Hosts` target group:

```
deregistration_delay.timeout_seconds  = 90
stickiness.enabled                    = true
stickiness.type                       = lb_cookie
stickiness.lb_cookie.duration_seconds = 86400
```

A read-only `curl -s -D - -o /dev/null
https://cloud.patchyhq.com/api/release` shows the cause today: the
response sets `AWSALBAPP-0..3=_remove_; Path=/`.

The ALB's routing can't be exercised locally. This rests on the
synthesized template and AWS's documented duration-based stickiness.
After the deploy, the refusal query in `docs/OPERATIONS.md` should show
the `stream_replaced` misroutes stop, with `balancerCookie = true` on
subscription POSTs.

## Release impact

- [x] **Breaking** — requires action from anyone already running this
- [ ] **Not breaking** — no action required

Only for a multi-replica deployment whose ingress keyed on
`patchy_stream_affinity`: the server no longer sets it, so that ingress
must switch to its own stickiness cookie on every path (for ALB,
`lb_cookie`). This PR does that for production's stack. Single-replica
setups and the local dev loop need nothing.

- **What does a revert leave behind?** Browsers keep an `AWSALB` cookie,
which app-cookie stickiness ignores. Deploying the older commit puts the
target group back on `app_cookie` and the server sets
`patchy_stream_affinity` again. No schema or data changes.
- **Does the release before it still work with that?** Yes, with the
misroutes this PR fixes.

Made by Claude Opus 5.5 via Claude Code; reviewed with GPT-6.1-Sol.

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:ci CI, shared testing infrastructure, development scripts and tooling area:docs Touches the docs area area:server Touches the server area size:m 100-500 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant