A canary deployment service sounds like a load balancer with a dial on it. “Send 5% of traffic to v2, 95% to v1, turn the dial as confidence grows.” That framing survives exactly until you ask the three questions that actually define the system. First: who decides a given request goes to the canary, and does the same user keep seeing the same version for the length of their session - because a user who gets v2 on page load and v1 on the next AJAX call sees a half-migrated app, broken in ways no version is broken on its own. Second: how does a weight change (5% becomes 10%) take effect across every proxy in the fleet - because if proxy A has flipped to 10% while proxy B is still on 5%, the effective split is undefined, and worse, if the change is not applied atomically a single request can be routed against a half-written config and land on a version that does not exist yet. Third: what happens in the update window - the span between “operator saves 10%” and “every proxy is serving 10%” - because during that window, if you are not careful, requests hit the wrong version, stickiness breaks, and a bad canary that you are trying to dial down keeps taking traffic on the proxies that have not heard yet. The real problem is this: route a configurable percentage of live traffic to a new service version across a fleet of stateless edge proxies, keep every user pinned to one version for their whole session via a header, and propagate every weight change atomically and consistently to the entire fleet - through a consensus-backed config broadcast - so that no request is ever routed by a partially-applied config and no user is ever flipped mid-session.
Everything hard here - deterministic split, header stickiness, and above all the atomic fleet-wide config swap - serves two non-negotiable properties: routing is a cheap local decision on the proxy (a hash and a threshold compare, in the request hot path, zero network calls) and a weight change is a single atomic version bump the whole fleet adopts together (every proxy flips from config version N to N+1 as one unit, never reading a half-applied state). You do not call a central router per request; you push the routing rules to the proxy and decide in-process. You do not let proxies poll and drift; you broadcast a versioned, immutable config snapshot from a consensus-backed store and swap the active pointer atomically. Let me build it properly.
Functional Requirements (FR)
In scope:
- Define a traffic split for a service. An operator declares, per service (say
checkout), a set of version backends (v1-> stable pool,v2-> canary pool) and a weight for each (v1: 95, v2: 5). The service routes live traffic in those proportions. - Progressive rollout. Ramp the canary weight over time: 1%, 5%, 25%, 50%, 100%. Each change takes effect across the whole proxy fleet. Support an instant rollback (set canary to 0%) and an instant promote (canary to 100%, becomes the new stable).
- Header-based session stickiness. Within a session, a user always sees the same version. A request carries (or is assigned) a stickiness key in a header/cookie; given that key, the routing decision is deterministic and stable across every proxy and every request in the session, even as weights change for new sessions.
- Blue-green as a special case. Blue-green is just a split that is 0/100 and flips to 100/0 atomically. The same machinery handles it - a single atomic weight swap.
- Multiple concurrent canaries. Different services roll out independently; one service can have more than two versions in flight (an A/B/C split) if needed.
- Atomic, consistent config propagation. A weight change (or backend set change) is applied fleet-wide atomically: every proxy moves from config version N to N+1 as one indivisible step. No request is ever routed against a partially-written config, and no proxy serves a weight that the operator never set.
- Rollback and audit. Every config change is versioned, attributable (who/when/what), and instantly revertible to any prior version.
Explicitly out of scope (say it so you own the scope):
- Automated canary analysis / SLO-based auto-promotion. The service exposes per-version metrics (error rate, latency) and accepts weight changes from an external controller, but the statistical “is the canary healthy, auto-advance or auto-rollback” decision is a separate analysis system that drives this one via the API. I design the data plane and the config plane, not the judgment.
- Deploying the actual backends. Standing up the
v2pool (pulling images, scheduling pods, health checks) is the orchestrator’s job. I route to pools that already exist and are registered. - Service discovery internals. I consume a registry of
(version -> healthy endpoint list); I do not build the registry. - TLS termination, WAF, rate limiting. The edge proxy does these; they are orthogonal to the split logic and I will not redesign them.
- Cross-service request tracing. I emit enough to attribute a request to a version; distributed tracing is a consumer of that, not part of this design.
The one decision that drives everything: the routing decision must be a local, in-proxy computation over a pushed, versioned config snapshot, and config changes must be swapped atomically fleet-wide via a consensus-backed broadcast, not polled piecemeal - because any per-request call to a central router adds latency to every request in the hot path, and any non-atomic propagation lets a request read a half-applied config and hit a version that does not exist or a weight nobody set. Unlike a load balancer you reconfigure by editing each node (drift, split-brain on weights) here the fleet adopts one immutable version together; unlike a router you query per request (an RTT on every call) here you decide in-process from the snapshot. That pairing - decide locally, swap atomically - is the whole problem.
Non-Functional Requirements (NFR)
- Scale: a global edge fleet of ~2,000 proxy instances fronting hundreds of services, serving an aggregate ~2M requests/sec at peak. Each service has a handful of versions live at once (usually 2). Config changes are rare (a rollout is maybe a dozen weight bumps over an hour; thousands of changes/day across all services) but each must reach all ~2,000 proxies consistently. Session stickiness keys number in the hundreds of millions of active sessions, but none of them are stored centrally - stickiness is computed, not looked up.
- Latency: the routing decision adds effectively zero latency to a request - a hash and a threshold compare over an in-RAM table, single-digit microseconds, because it sits in front of every request the edge serves. Config change propagation: an operator’s weight change reaches and is atomically applied on every proxy within ~1 second, and a rollback (canary to 0) within the same budget because it is the same mechanism.
- Availability: 99.99%+ on the data plane (routing). If the entire config plane is down, proxies must keep routing from their last-known-good config snapshot - a config-plane outage must never stop traffic or blank the routing table. The config plane (consensus store + distributor) targets high availability but can tolerate brief write unavailability: during it, no new rollouts advance, but existing traffic keeps flowing on the current version.
- Consistency: two layers. Config application is linearizable per version - the consensus store assigns a total order to config versions, and a proxy only ever serves a fully-received, committed version, atomically swapped; it never serves a blend of N and N+1. Across the fleet, propagation is eventually consistent but bounded (~1s) and, crucially, monotonic: proxies move forward through versions, never backward, and the effective split converges to the new weights within the window. Stickiness is strongly deterministic: same stickiness key + same config version => same version everywhere, always.
- Durability: the config history (every version of every service’s split) is the source of truth and must be durable and totally ordered - it is small but losing it loses the ability to roll back and reason about what was live. The consensus log is the durable, replicated record. Proxies hold only a cached snapshot (regenerable).
- The real budget is atomic, consistent, bounded propagation with a correct update window. It is fine for different proxies to be on version N vs N+1 for up to a second; it is not fine for a single proxy to route against a half-applied config, for a user to flip versions mid-session, or for a rollback to be slow. The whole design decides routing locally and swaps config versions atomically under a consensus-assigned order.
Back-of-the-Envelope Estimation (BoE)
Real numbers with the arithmetic, because they dictate the architecture.
Routing decision volume (why it must be local):
Aggregate edge traffic at peak: ~2,000,000 requests/sec.
Every request needs a routing decision (which version pool?).
If each decision were a call to a central router: 2M req/sec to that router,
plus a network RTT (~0.5-1ms) added to EVERY edge request. Fatal on both
counts - you have put a synchronous hop in front of all traffic.
=> the routing decision is IN-PROXY, local: hash the stickiness key, compare to
a threshold table in RAM. ~single-digit microseconds, zero I/O. We serve
ZERO routing calls centrally. The config plane only PUSHES rules, rarely.
Per-proxy decision cost:
2M req/sec / ~2,000 proxies = ~1,000 req/sec per proxy average (far higher at
hot proxies, but still tiny per-decision). Each decision: one 64-bit hash
(xxHash of the stickiness key + service salt) + one lookup of the service's
weight table (a few cache lines) + a threshold compare. << 1 microsecond of
CPU. Negligible against TLS and upstream I/O the proxy already does.
Config change / propagation volume (rare but must be atomic and fleet-wide):
Config changes are rare: a rollout is ~10-15 weight bumps; say ~3,000 changes/day
across all services. 3,000 / 86,400 ≈ ~0.035 changes/sec. Trivial write rate.
BUT each change must reach ALL ~2,000 proxies and be applied atomically.
The consensus store commits ONE small entry (a new config version for one
service: a few hundred bytes - backend set + weights + version number).
The distributor fans that one commit out to 2,000 proxies: 2,000 small
messages (~1KB) = ~2MB total per change, pushed in well under a second.
The cost is not the write rate; it is the ATOMIC FLEET-WIDE SWAP per change and
the guarantee that the window between "proxy A on N+1" and "proxy B on N+1"
never routes a request against a half-applied config.
Storage:
Config snapshot per service: backend sets + weights + version ≈ a few hundred
bytes to a few KB. Hundreds of services => the WHOLE fleet config is ~a few MB.
Fits trivially in RAM on every proxy and in the consensus store.
Config history (every version, append-only, for rollback/audit):
~3,000 versions/day * a few hundred bytes * 365 ≈ low hundreds of MB/year.
Tiny. The consensus log keeps a bounded recent window; older versions
snapshot to a cheap object store for audit.
Stickiness: ~hundreds of millions of active sessions, but ZERO stored - the
version for a session is RECOMPUTED from its key by hashing. No session table.
Per-request routing/attribution logs (which version served each request):
this is the ONLY high-volume stream - 2M/sec of small records - and it is
sampled/batched to an analytics pipeline, out of the critical path.
Consensus / distribution capacity (the crux):
Consensus store (Raft group of 3-5 nodes): must totally-order and durably commit
~0.035 writes/sec. This is laughably under capacity - Raft handles thousands
of writes/sec. Consensus is NOT here for throughput; it is here for a single
total order of config versions and atomic commit, so the fleet can never
disagree about what version N means or which came first.
Distribution fan-out: ~2,000 proxies hold a persistent watch/stream to the
distributor tier. On a commit, the distributor pushes the new version to all
2,000. 2,000 persistent connections is trivial for a handful of distributor
nodes (this is NOT a C10M problem; it is 2,000 connections). The watch is
mostly idle; it carries a tiny message only when config changes.
The takeaways: routing is a ~2M/sec firehose we must serve zero of by pushing the weight tables into the proxy and deciding in-process; config writes are rare (0.035/sec) so consensus is used for ordering and atomicity, not throughput; the fan-out is a modest 2,000 persistent watches (not a mega-fanout problem), so the hard part is purely the correctness of the atomic swap, not its scale; and storage is tiny because the data is small config and stickiness is computed, not stored. The hard parts are therefore: deterministic split + header stickiness that survives weight changes, the atomic consensus-backed config swap (the core challenge), the API/schema for versioned config, and graceful degradation so routing never depends on a live config plane.
High-Level Design (HLD)
The architecture splits along the fundamental seam of a traffic splitter: the config plane (declare splits, order and commit versions - rare writes, must be linearizable and durable) is separate from the data plane (decide routing locally, serve traffic - 2M req/sec, must be fast and never block). Config flows outward from a small consensus-backed store, through a stateless distributor, to every edge proxy, which caches the current immutable snapshot and routes in-process. A weight change is committed as a new totally-ordered version and broadcast; each proxy receives the full new snapshot and atomically swaps its active pointer from N to N+1.
CONFIG PLANE (rare writes, linearizable, durable)
┌──────────┐ set weights ┌───────────────┐ propose ┌────────────────────┐
│ Operator │──v2: 5%───────>│ Config API │─────────>│ Consensus Store │
│ / Canary │ rollback 0% │ (validate, │ │ (Raft, 3-5 nodes): │
│ Controller│ │ compile snap, │ commit │ TOTAL ORDER of │
└──────────┘ │ version N+1) │<─────────│ config versions, │
└───────┬────────┘ N+1 ok │ durable log + audit │
│ committed version N+1 └────────┬────────┘
▼ (full immutable snapshot) │ source of truth
┌────────────────────────────┐ │
│ Distributor (stateless) │<────────────┘ (watch the log)
│ watches committed versions,│
│ pushes snapshot to fleet │
└──────────────┬─────────────┘
─────────────────────────────────────── │ push version N+1 to all proxies
DATA PLANE (2M req/sec, local, never blocks) (persistent watch per proxy)
┌──────────────┬─────────────┴───────────┬──────────────┐
▼ ▼ ▼ ▼
┌───────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐
│ Edge Proxy│ │ Edge Proxy│ ... │ Edge Proxy│ │ Edge Proxy│
│ holds TWO │ │ ~2,000 │ fleet │ snapshots │ │ │
│ snapshots:│ │ proxies │ │ active=N+1│ │ │
│ active=N, │ │ │ │ swap is │ │ │
│ staged=N+1│ │ │ │ one ptr │ │ │
└─────┬─────┘ └─────┬─────┘ └─────┬─────┘ └─────┬─────┘
│ route │ │ │
▼ decision ▼ ▼ ▼
┌───────────────────────────────────────────────────────────────┐
│ Per request: key = header/cookie stickiness key │
│ bucket = hash(service_salt + key) mod 10000 │
│ pick version where bucket falls in its weight band (active N) │
│ -> forward to that version's backend pool (from registry) │
└───────────────────────────────────────────────────────────────┘
│ v1 pool │ v2 (canary) pool
▼ ▼
┌───────────┐ ┌───────────┐ Service Registry supplies
│ stable v1 │ │ canary v2 │ (version -> healthy endpoints);
│ backends │ │ backends │ proxy load-balances within pool.
└───────────┘ └───────────┘
Config change flow (operator to committed version):
- An operator (or an automated canary controller) calls the Config API: “set
checkouttov1:90, v2:10.” The API validates it (weights sum to 100, every referenced version has a registered backend pool, no unknown versions), compiles a full immutable snapshot for that service, and proposes it to the Consensus Store as the next versionN+1. - The consensus store (a Raft group) assigns
N+1a place in the total order of config versions and durably commits it to a replicated log. Commit means a quorum has persisted it. This is the linearization point:N+1now exists, officially, afterN, for everyone.
Propagation flow (committed version to every proxy, atomic swap):
- The Distributor watches the committed log. On commit of
N+1, it pushes the full new snapshot (not a delta - the whole service config, so a proxy never has to merge partial state) down the persistent watch each proxy holds. - Each Edge Proxy receives
N+1into a staged slot while continuing to route from its active slot (N). Only once the entire snapshot is received and validated does the proxy perform a single atomic pointer swap:active := N+1. In-flight requests that already readactive=Nfinish onN; every request after the swap readsN+1. There is no moment where a request reads a half-written table, because the snapshot was fully staged before the pointer moved.
Routing flow (per request, zero network, deterministic):
- A request arrives at a proxy. The proxy reads the active snapshot (a single atomic pointer read), extracts the stickiness key from the configured header/cookie (or mints one and sets it on the response if absent), and computes
bucket = hash(service_salt + key) mod 10000. - The proxy maps
bucketto a version via the weight bands (v1: [0,9000), v2: [9000,10000)for a 90/10 split), looks up that version’s healthy backend endpoints from the service registry, load-balances within that pool, and forwards. The chosen version is stamped into a response header and the attribution log. Single-digit microseconds, in-process, no config-plane call.
The key insight: routing is a pure local function over an immutable, atomically-swapped snapshot, and config change is a single totally-ordered version the whole fleet adopts by staging-then-swapping. The config plane keeps a small config linearizable and durable via consensus; the data plane caches the current version and decides in-process. Nothing in the request path calls the config plane, and nothing about a change lets a proxy read a partial config. That separation is what makes routing free while a weight change lands atomically fleet-wide in about a second.
Component Deep Dive
The hard parts, naive-first then evolved: (1) the split decision and header stickiness - how to route a percentage and pin a session without a central lookup; (2) atomic, consistent config propagation via consensus - how a weight change reaches 2,000 proxies without any request hitting a half-applied config (the core challenge); (3) stickiness survival across weight changes - how a pinned user stays pinned while new sessions see the new weights; (4) graceful degradation and backend health - how routing survives a dead config plane and never sends traffic to an unhealthy version.
1. The split and header stickiness: why a central router and a session table fail, then local hash bucketing
Naive approach: every request calls a central “router” service that holds the weights and keeps a session_version(session_id -> version) table so a user stays on the same version; the router answers “send this one to v1 or v2.”
Where it breaks:
- A network call per request is fatal. The routing decision sits in front of every edge request - 2M/sec. Routing each to a central service adds a synchronous RTT to every request and asks that service to serve 2M/sec. Both are non-starters; the entire value of an edge split (cheap, instant, in-path) evaporates.
- The session table explodes and races. Hundreds of millions of active sessions means hundreds of millions of rows, each written on first contact; two concurrent first-requests for the same new session race to insert; and you are maintaining a giant hot table to remember something a hash can recompute for free.
- Stickiness breaks on the central router’s own failover. If the table lives behind a store that fails over, or an entry expires, a user’s pin is lost and they flip versions mid-session - the exact bug you built the table to prevent.
- Cross-proxy disagreement. If stickiness is a lookup, two proxies serving the same user must consult the same store (another hop, another dependency) or they will disagree.
Evolution: push the weight table to the proxy and make the split a deterministic hash of the stickiness key into stable buckets, storing nothing. The core trick, same as consistent assignment anywhere: a good hash of the same input always yields the same output, so stickiness needs no stored state - every proxy recomputes the identical bucket from the same key.
Per request, for service "checkout" with active split v1:90, v2:10:
key = request header X-Sticky-Id (or cookie; minted + set if absent)
bucket = hash( "checkout" + ":" + key ) mod 10000 # xxHash/Murmur, [0,10000)
# weight bands for v1:90, v2:10 => v1: [0, 9000), v2: [9000, 10000)
version = (bucket < 9000) ? "v1" : "v2"
=> the SAME key lands in the SAME bucket on EVERY proxy, EVERY request, with
ZERO stored state and ZERO network calls. The split is just band membership.
Stickiness falls out for free. Because the bucket depends only on service + key (never on which proxy, never on time), every request carrying the same X-Sticky-Id computes the same bucket and therefore the same version - on any proxy, for the whole session. No session table, no central lookup, no cross-proxy coordination. A user pinned to v2 stays on v2 because their bucket (say 9400) is fixed; it does not wander.
Where does the stickiness key come from? On the first request of a session with no key, the proxy mints one (a random 128-bit id), computes the version, and sets it as a cookie / response header. Every subsequent request echoes it, so the whole session is deterministic from request two onward, and even request one is deterministic given the minted key (the proxy computes the bucket from the key it just minted). The operator configures which header/cookie carries the key per service (X-Sticky-Id, a session cookie, or a user id header from auth) so stickiness can key on user, session, or device as the product needs.
Why this is correct at scale: the decision is O(1) CPU, zero I/O, zero storage - a hash, a modulo, a band compare, over a weight table already in RAM. 2M decisions/sec is trivial because each is nanoseconds of local math on data we already pushed, with no shared state to contend on. Determinism gives stickiness for free - no locks, no session table, no store to fail over. We replaced a per-request router call and a hundred-million-row session table with a stateless hash - the move that makes routing free and stickiness automatic.
2. Atomic consensus-backed config propagation: why editing proxies and plain pub/sub fail, then a totally-ordered version staged and swapped
This is the hard part the problem is really about: a weight change must reach ~2,000 proxies and be applied so that no request is ever routed by a partially-applied config and the fleet never disagrees about what a version means or which came first.
Naive approach: the operator pushes the new weights to each proxy (a config file per node, reloaded), or publishes the change on a best-effort pub/sub channel that proxies apply as messages arrive.
Where it breaks:
- Non-atomic per-field application routes against a half-written config. If a proxy applies a change field by field (update v1 weight, then v2 weight), a request arriving between the two writes sees
v1:90, v2:10becomingv1:75, v2:10- weights that sum to 85, a band gap, and a bucket that maps to no version or the wrong one. A request can hit a version the operator never intended, or a backend pool that is being removed. - No total order means split-brain on “version N.” Two near-simultaneous changes (operator bumps to 10% while the canary controller rolls back to 0%) delivered over best-effort pub/sub can arrive in different orders at different proxies. Half the fleet ends on 10%, half on 0%, and there is no authority that says which is the current version. The effective split is now undefined and unrecoverable without manual intervention.
- Lost or reordered messages leave permanent drift. Best-effort pub/sub can drop a message to some proxies; those proxies are silently stuck on an old version forever, and nothing detects it. A rollback that does not reach 3% of the fleet means 3% of traffic keeps hitting the bad canary.
- The update window routes wrong. Even if each proxy is individually atomic, without a controlled window a rollback is only as fast as the slowest delivery, and during the window different proxies serve wildly different weights with no bound or ordering.
Evolution: commit each config change as a single totally-ordered, immutable version in a consensus log, push the whole snapshot, and apply it with a stage-then-atomic-swap on each proxy. Two mechanisms together give correctness: consensus for a single total order + atomic commit, and immutable whole-snapshot swap for per-proxy atomicity.
Operator / controller sets new weights
│ Config API: validate (weights sum to 100, versions exist), compile
│ FULL immutable snapshot for the service
▼
PROPOSE snapshot to Consensus Store (Raft)
│ Raft assigns it the next log index => a GLOBAL TOTAL ORDER.
│ Commit = quorum persisted. Now "version N+1" officially exists,
│ after N, identically for everyone. Concurrent proposals are
│ SERIALIZED by Raft - one wins index N+1, the other gets N+2.
▼
Distributor watches the committed log; on commit of N+1, pushes the
FULL SNAPSHOT of N+1 down each proxy's persistent watch.
│
▼
Each proxy: receive N+1 into a STAGED slot (keep routing from ACTIVE=N).
validate it fully (well-formed, bands cover [0,10000)).
ATOMIC SWAP: active_ptr := staged(N+1). <-- single pointer store
│ In-flight requests that read active=N finish on N.
│ Every request after the swap reads N+1. No request EVER reads a blend.
▼
Proxy ACKs version N+1 back to the distributor (fleet convergence tracking).
Why consensus, specifically. The consensus store is not here for throughput (0.035 writes/sec is nothing). It is here for two guarantees nothing cheaper gives you: (a) a single total order of config versions, so “version N+1” means exactly one thing fleet-wide and concurrent changes are serialized rather than racing, and (b) durable atomic commit via quorum, so a committed version survives node failures and a half-proposed version is never observed. Raft’s log index is the version number. This is what kills the split-brain: the operator’s 10% and the controller’s rollback cannot both be “the current version” - one is N+1 and the other is N+2, and the fleet converges on the latest committed index, monotonically.
Why whole immutable snapshot, not a delta. Pushing the full compiled snapshot (not “change v2 from 5 to 10”) means a proxy never merges partial state - it stages a complete, self-consistent config and swaps to it in one pointer store. There is no field-by-field window on the proxy. Snapshots are tiny (a few hundred bytes to a few KB per service), so shipping the whole thing costs nothing and buys atomicity.
Why stage-then-swap makes the per-proxy application atomic. The proxy holds two slots. It routes from active while receiving staged. The only mutating operation on the hot path’s view is a single atomic pointer swap (one aligned word store, or an RCU-style publish). Readers (the request path) either see the old pointer or the new pointer, never a torn read, and never a partially-populated table - because the staged snapshot was fully built before the pointer moved. In-flight requests that grabbed active=N complete against N (consistent for their whole lifetime); new requests get N+1. This is classic read-copy-update: build the new version off to the side, flip one pointer, let readers drain.
The update window, made correct and bounded. Between the swap on the first proxy and the last, the fleet straddles N and N+1. This is acceptable and bounded because: every proxy serving N is serving a fully-consistent, operator-intended config (just the previous one), and every proxy serving N+1 is serving a fully-consistent new one - no proxy is ever inconsistent within itself, so no request hits a non-version. The window is bounded to ~1s by the push latency. And because versions are monotonic by Raft index, a proxy never regresses N+1 -> N. For a rollback (set canary to 0%), the effective worst case during the window is that a few proxies briefly still send the configured small percentage to the canary - bounded in both fraction and time, and strictly shrinking - never an unbounded or growing exposure.
Proxy routing-view swap (read-copy-update, lock-free on the read path):
active_ptr -> Snapshot{version:N, bands:{v1:[0,9000), v2:[9000,10000)}}
on receive(N+1):
staged = parse_and_validate(N+1) # full snapshot, off to the side
assert staged.bands cover [0,10000) exactly, weights sum to 100
atomic_store(active_ptr, staged) # THE swap: one word, indivisible
retire old snapshot after in-flight readers drain (RCU grace period)
request path:
snap = atomic_load(active_ptr) # one version, never torn
route using snap.bands # consistent for this request
Convergence tracking and stuck-proxy detection. Each proxy ACKs the version it has swapped to. The distributor (and the config plane) track the minimum version across the fleet; “the fleet is on N+1” means all proxies have ACKed >= N+1. An operator’s dashboard shows convergence (“1,998/2,000 on v10, 2 lagging”) so a stuck proxy is visible, not silent. A proxy that misses a push detects the gap (versions are monotonic integers; a jump from N to N+2 or a watch reconnect triggers a full snapshot refetch of the latest committed version). This closes the “lost message = permanent silent drift” hole: the version number is the sync point, and any gap self-heals by refetch.
Why this is correct at scale: config writes are rare and small, so consensus is free on throughput and used purely for order + atomicity; the fan-out is a modest 2,000 persistent watches pushing a few MB total per change; per-proxy application is a lock-free atomic swap of an immutable snapshot so the 2M/sec read path never blocks and never tears; and the fleet converges monotonically and visibly within ~1s with any gap self-healing by refetch. Consensus gives one total order and atomic commit; whole-snapshot stage-then-swap gives per-proxy atomicity; together they guarantee no request is ever routed by a half-applied config and the fleet never disagrees about what is live - which is exactly the core challenge.
3. Stickiness across weight changes: why re-bucketing on every change fails, then fixed buckets with a moving band and optional pin cookies
Naive approach: when weights change, recompute each session’s version from the new weights - or, worse, re-randomize assignments so the new proportions are exact immediately.
Where it breaks:
- Users flip mid-session. If raising the canary from 10% to 25% re-randomizes who is in the canary, some users who were on
v1jump tov2(or the reverse) in the middle of their session - the half-migrated-app bug. Stickiness is destroyed by the very act of ramping, which is when you most need it. - Dialing down must not strand active sessions badly either. Rolling the canary from 25% to 10% should stop new exposure, but naively re-bucketing yanks active canary users back to
v1mid-flow, which can be as jarring as the forward flip (lost canary-side session state).
Evolution: keep the bucket fixed per key and only move the band boundary, so a weight change re-slots only the minimum necessary sessions, deterministically - and offer an explicit pin for sessions that must never move. Because the bucket is a pure function of service + key and does not depend on the weights, changing weights only moves the threshold between bands.
Fixed bucket per key; only the band boundary moves with the weight:
key K has bucket 9400 (fixed forever).
v1:90 / v2:10 -> v2 band [9000,10000) -> K(9400) is on v2
v1:75 / v2:25 -> v2 band [7500,10000) -> K(9400) STILL on v2 (band grew down)
v1:95 / v2:5 -> v2 band [9500,10000) -> K(9400) moves to v1 (band shrank up)
Ramping UP the canary (10->25%) only lowers the v2 band's left edge from 9000 to
7500: every key already in [9000,10000) STAYS in v2 (never flips back), and only
keys in [7500,9000) newly ENTER v2. Forward ramp is MONOTONIC for canary users -
nobody on the canary gets kicked off as you ramp up.
Dialing DOWN (25->10%) raises the edge 7500->9000: keys in [7500,9000) leave the
canary. That is the POINT of dialing down (reduce exposure), but it can move an
active session. For sessions that must never move, use a hard pin (below).
Hard pins for sessions that must not move at all. For flows where even a dial-down must not re-slot an active session (a user mid-checkout on the canary), the proxy, on first routing a session, can write the chosen version into the stickiness cookie itself (X-Sticky-Id=<key>; v=v2). On subsequent requests the proxy honors the pinned v=v2 directly (if that version still exists and is healthy) instead of re-bucketing, so the session is immune to band moves for its lifetime. New sessions get no pin and follow the current band, so the new-session split still converges to the configured weights. This is the knob: band-based stickiness (cheap, converges, monotonic on ramp-up) by default; hard cookie-pin (immune to any weight change) for sessions that require it. A pin is dropped only if its version is removed or goes unhealthy, in which case the session fails over to the current band - correctness over stickiness when a version literally no longer exists.
Why this is correct at scale: stickiness is stateless (recomputed from the key) with the bucket fixed and only the band moving, so a weight change re-slots the minimum set of sessions and never flips a canary user off during a ramp-up; the optional cookie-pin makes a session immune to weight changes without any server-side session store (the pin rides in the client’s own cookie); and both are local, zero-I/O decisions on the proxy. Fixing the bucket and moving only the band gives sticky, monotonic ramps for free; the cookie-pin handles the rare session that must never move - all without a single central session lookup.
4. Graceful degradation and backend health: why a hard config dependency and version-blind routing fail, then last-known-good plus health-filtered pools
Naive approach: the proxy needs a live config-plane connection to route; and once a request is bucketed to v2, it is sent to the v2 pool regardless of whether those backends are healthy.
Where it breaks:
- The config plane becomes a hard dependency of all traffic. If routing stalls or errors when the consensus store or distributor is unreachable, a config-plane outage becomes a total traffic outage - catastrophic, and the opposite of what an edge should do. The config plane changes rarely; it must never gate the serving of traffic.
- Routing to a dead version serves errors on purpose. A canary pool whose backends are crash-looping (that is often why you are canarying) still receives its configured percentage, so you deliberately serve errors to that slice until a human notices and dials down. Routing must not be blind to backend health.
- Reconnect storms. If all 2,000 proxies reconnect to the distributor at once after a partition heals, they can hammer the config plane right when it is recovering.
Evolution: last-known-good config on the proxy, health-filtered backend pools, and jittered reconnect - so routing is a soft dependency on the config plane and never sends traffic to an unhealthy version. Three rules make the config plane a soft dependency.
1. LAST-KNOWN-GOOD, NEVER BLOCK ON CONFIG.
The proxy always routes from its ACTIVE in-RAM snapshot. If the config plane
is unreachable, it keeps serving the last committed version it has - possibly
slightly stale weights, but a fully-consistent, operator-intended config.
Routing NEVER waits on the config plane. Persist the active snapshot to local
disk so a proxy restart during a config-plane outage still boots with a valid
config instead of an empty table.
2. HEALTH-FILTERED POOLS, FAIL OVER ACROSS VERSIONS.
The service registry supplies (version -> HEALTHY endpoints) and the proxy
also runs its own passive/active health checks. If a bucketed version's pool
has NO healthy backends, the proxy fails the request over to the other
version's healthy pool (and flags it) rather than serving a guaranteed error.
A collapsing canary thus sheds its own traffic back to stable automatically,
which is the safe default while the controller dials it to 0.
3. RECONNECT WITH JITTERED BACKOFF + VERSION RESYNC.
On watch disconnect, reconnect with exponential backoff + random jitter so a
partition heal does NOT produce a synchronized 2,000-proxy stampede. On
reconnect, the proxy sends its current version; if it lags the committed head,
it refetches the latest full snapshot (closing any gap from missed pushes).
The config plane is additive to routing, not required by it. Routing works the instant a snapshot is cached (from a push or from disk); the watch only keeps it fresh. So a config-plane outage does not stop traffic - the fleet serves last-known-good and resyncs when the plane returns, each proxy refetching the latest committed version so it never misses the change it slept through. The one hard invariant preserved throughout: the routing decision is a pure local function over an in-RAM snapshot that always returns a version, and that version’s pool is health-filtered, so a request is always sent somewhere serving - never blocked on config, never knowingly sent to a dead pool.
Why this is correct at scale: the serving path has no hard dependency on the config plane (routes from last-known-good, persisted to disk); backend failures are contained by health-filtered pools with cross-version failover, so a sick canary sheds its own traffic; and reconnect storms are broken up by jitter + version resync, which also self-heals any missed push. The config plane is a soft dependency by design - traffic keeps flowing on last-known-good when it is down, and no request is ever routed to a version that cannot serve it - which is the only acceptable posture for a component in front of all traffic.
API Design & Data Schema
Traffic splits into a low-volume config plane (declare/change splits - operators and controllers), a push-based distribution channel (proxies hold a watch for new versions), and the routing decision itself, which is deliberately absent as a network endpoint - it is a proxy-local computation. The config API is the only human/controller-facing surface.
REST / RPC endpoints
# --- Config plane: declare and change splits (low volume, authenticated) ---
PUT /api/v1/services/checkout/split
Body: { "versions":[
{"name":"v1","backend_pool":"checkout-v1"},
{"name":"v2","backend_pool":"checkout-v2"} ],
"weights": { "v1":90, "v2":10 }, # must sum to 100
"sticky_key": { "source":"cookie", "name":"X-Sticky-Id" },
"hard_pin": true } # write chosen version into cookie
-> 200 { "service":"checkout", "version":11, "committed":true }
# validated, compiled to a full snapshot, proposed to consensus => version 11.
# Raft commit is the linearization point; distributor pushes 11 to the fleet.
PATCH /api/v1/services/checkout/split { "weights": { "v1":75, "v2":25 } } # ramp up
-> 200 { "version":12 } # fixed buckets, v2 band grows down; canary users STAY.
POST /api/v1/services/checkout/rollback { "to_version": 10 }
-> 200 { "version":13 } # re-commits snapshot 10's content as new version 13.
# instant safe revert; same atomic-swap mechanism; fleet converges in ~1s.
POST /api/v1/services/checkout/promote { "version":"v2" }
-> 200 { "version":14, "weights": { "v2":100 } } # canary becomes 100% (blue-green flip).
GET /api/v1/services/checkout/split
-> 200 { "version":14, "weights": {...}, "convergence": { "on_version":14,
"acked":1998, "total":2000, "lagging":["proxy-7a3","proxy-9c1"] } }
GET /api/v1/services/checkout/history
-> 200 { "versions":[ {"version":12,"weights":{"v1":75,"v2":25},
"by":"controller","ts":...,"reason":"slo_ok_advance"} ] } # audit + rollback source
# --- Distribution: each proxy holds this watch open for new committed versions ---
GET /internal/v1/config/watch
Headers: X-Proxy-Id: proxy-7a3, X-Known-Version: 11 (last version it holds)
-> 200, streaming (long-lived; the propagation channel)
... stays open ...
event: snapshot data: { "service":"checkout", "version":12, "weights":{...},
"versions":[...], "sticky_key":{...} } # FULL snapshot
# proxy stages the snapshot, validates, atomic-swaps active:=12, then ACKs.
POST /internal/v1/config/ack { "proxy_id":"proxy-7a3", "version":12 }
-> 204 # feeds fleet convergence tracking (min-version across fleet).
# --- Routing has NO runtime endpoint: the proxy computes the version locally. ---
# bucket = hash(service_salt + sticky_key) mod 10000 -> band -> version. Microseconds.
The routing decision has no runtime endpoint - the proxy computes the version locally from the active snapshot. This is the point: the highest-QPS operation (2M/sec) makes zero config-plane calls.
Data store schemas
1. Consensus Store - a replicated, totally-ordered log (Raft group, 3-5 nodes). The source of truth for config versions. Small, low-write, must be linearizable and durable. A log, not a general-purpose DB, because the one thing we need is a single total order of immutable config versions with atomic quorum commit - exactly what a Raft log is. Throughput is a non-issue (0.035 writes/sec); ordering and atomicity are the whole reason it is here.
config_log (Raft replicated, append-only, index = version number):
index (PK, = global version), service, snapshot_json, proposed_by,
reason, committed_ts
-- snapshot_json is the FULL compiled config for that service version:
-- { versions:[{name, backend_pool}], weights:{...}, bands:[...],
-- sticky_key:{source,name}, hard_pin, service_salt }
-- bands are PRECOMPUTED at compile time so the proxy never derives them:
-- weights v1:90,v2:10 => bands v1:[0,9000), v2:[9000,10000)
-- Raft guarantees: total order by index, quorum-durable, atomic commit.
2. Config Snapshot (per service) - the immutable artifact the proxy caches. Not a separate store - it is the committed snapshot_json, held in RAM on each proxy (active + staged slots) and persisted to local disk for restart. Versioned, immutable, swapped atomically.
Snapshot (in-RAM on proxy; also on local disk as last-known-good):
{ "service":"checkout", "version":12, "service_salt":"s_chk3",
"sticky_key": { "source":"cookie", "name":"X-Sticky-Id" }, "hard_pin":true,
"versions": [ {"name":"v1","backend_pool":"checkout-v1"},
{"name":"v2","backend_pool":"checkout-v2"} ],
"bands": [ {"version":"v1","lo":0,"hi":7500},
{"version":"v2","lo":7500,"hi":10000} ] } # cover [0,10000) exactly
(~a few hundred bytes/service; whole-fleet config is a few MB; swapped by one ptr)
3. Service Registry - the version -> healthy endpoints map (consumed, not owned). Supplies the actual backend endpoints per version, kept current by health checks. The proxy watches it (or polls a local agent) and load-balances within the chosen version’s healthy set. Not part of this design’s truth, but the routing path reads it after choosing a version.
registry (consumed from service discovery):
backend_pool (PK), endpoints:[ {addr, healthy, weight} ], updated_ts
-- "checkout-v2" -> [ {10.2.0.4:8080, healthy:true}, {10.2.0.5:8080, healthy:false} ]
-- proxy routes only to healthy; if a version has zero healthy, fails over.
4. Attribution / routing log - high-volume, sampled, off the critical path. Which version served each request, for canary analysis and debugging. The only high-volume stream; batched and sampled to an analytics pipeline, never on the routing hot path.
routing_events (sampled, batched to analytics pipeline):
ts, service, sticky_key_hash, chosen_version, config_version, backend_addr,
status_code, latency_ms
-- 2M/sec at full rate => SAMPLE (e.g. 1%) + batch; feeds canary health analysis.
Why these choices: the config truth is tiny, must be totally ordered and atomically committed - a Raft log is exactly right, and the trivial write rate makes consensus free; the snapshot is read by 2M req/sec, small, immutable - an in-RAM artifact swapped by one pointer, not a per-request DB read; distribution is rare events needing a consistent fleet-wide push - a watch channel carrying full snapshots, not a delta stream that forces merges; and the registry is health state owned elsewhere that the routing path consults after choosing a version. There is no store at all on the routing decision path because the version is computed from the cached snapshot, not queried. Each layer gets the mechanism its access pattern demands - Raft for the small ordered truth, an in-RAM immutable snapshot for the hot read path, a watch push for propagation - and the hottest operation touches none of the stores.
Bottlenecks & Scaling
Where it breaks first, in order, and the fix for each:
1. Routing on the request path (breaks catastrophically if done wrong). ~2M decisions/sec in front of all edge traffic - any network call per decision is fatal.
Fix: the decision is a local in-proxy computation (hash(service_salt + sticky_key) mod 10000 -> band -> version) over an in-RAM snapshot - zero I/O, zero stored state, deterministic. We serve none of these centrally. The only config dependency is the small snapshot, pushed on change. This removes the biggest wall by not building it.
2. Atomic, consistent config propagation (the core challenge). A change must reach ~2,000 proxies with no request ever routed by a half-applied config and no fleet disagreement on versions. Fix: consensus for total order + atomic commit, full immutable snapshots, and per-proxy stage-then-atomic-swap. Raft’s log index is the version; concurrent changes are serialized, not raced; each proxy stages the full snapshot and flips one pointer (RCU), so the 2M/sec read path never sees a torn or partial config. Fleet converges monotonically within ~1s.
3. The update window. Between the first proxy swapping to N+1 and the last, the fleet straddles two versions. Fix: the window is bounded (~1s) and internally consistent - every proxy serves a whole, operator-intended version (N or N+1), never a blend, so no request hits a non-version. Versions are monotonic (no regression), and for a rollback the stale exposure is bounded in both fraction and time and strictly shrinking. Convergence tracking makes a lagging proxy visible, not silent.
4. Stuck / drifted proxies (silent permanent divergence). A proxy that misses a push could serve an old version forever. Fix: versions are monotonic integers; a gap or watch reconnect triggers a full-snapshot refetch of the latest committed version, and each proxy ACKs its version so the config plane tracks the fleet minimum and surfaces laggards. The version number is the sync point; drift self-heals.
5. Stickiness breaking on weight changes. Ramping must not flip users mid-session. Fix: the bucket is fixed per key; only the band boundary moves. Ramp-up only grows the canary band downward, so canary users never flip back (monotonic); a weight change re-slots the minimum set of sessions. For sessions that must be immune to any change, a hard cookie-pin writes the chosen version into the client’s own cookie - no server-side session store.
6. Config plane as a single point of failure. The consensus store and distributor must not gate traffic. Fix: the config plane is a soft dependency - proxies route from last-known-good (in RAM, persisted to disk) when it is unreachable; routing never blocks on it. The Raft group is itself replicated (survives minority node loss); the distributor is stateless (any node can serve any proxy’s watch, regenerable from the committed log). A total config-plane outage freezes rollouts but never stops traffic.
7. Routing to an unhealthy version. A bucketed version whose pool is dead would serve guaranteed errors. Fix: pools are health-filtered from the service registry plus local checks; if the chosen version has no healthy backends, the proxy fails over to the other version’s healthy pool (and flags it). A collapsing canary sheds its own traffic back to stable automatically while the controller dials it to 0.
8. Shard keys, stated plainly. Consensus store -> not sharded; it is one small totally-ordered log (optionally one Raft group per large region, but a single global order per service is the simplest correct choice given the trivial write rate). Distribution -> proxies connect to any stateless distributor node (load-balanced), each node serving the full committed log; no per-service shard needed at 2,000 watches. Routing -> no shard key at all, nothing is stored per user; the hash is the bucketing of sessions into weight bands, computed at the edge. The unit of config is the service version; the session is bucketed by a stateless hash and never stored. The only high-volume thing (attribution logs) is sharded by service into the analytics pipeline, off the hot path.
9. Hot proxy / hot service. A proxy fronting a very popular service takes disproportionate request load. Fix: request load is handled by horizontal proxy scaling and the edge LB spreading connections - adding proxies adds routing capacity, and each proxy’s decision is already O(1). Config-side there is no hot spot: a popular service is still one small snapshot pushed to the fleet, and a huge fan-out of requests never touches the config plane because routing is local.
10. Multi-region. The config plane can run as a global Raft group (edits are rare, so the cross-region commit latency on the ~0.035 writes/sec is irrelevant) or a per-region group fed from a global order; either way each region runs stateless distributor nodes that push committed snapshots to that region’s proxies, so a change commits once and fans out region-locally - still ~1s because the pushes are region-local, only the commit may cross regions. A session evaluated in any region gets the identical version because routing is a pure hash of the same service_salt + sticky_key - determinism makes stickiness automatically consistent across regions with zero per-session replication. The hardest multi-region problem (consistent per-user routing everywhere) simply does not exist here; only the small config replicates, and the consensus order keeps every region agreeing on what version is live.
Wrap-Up
The trade-offs that define this design:
- Decide locally, do not query. The routing decision is a pure local function over an in-RAM snapshot - a hash into fixed buckets plus a band compare - so there is no per-request router call (which would add an RTT to every edge request and ask us to serve 2M/sec) and no session table (which would be hundreds of millions of hot rows). A central routing endpoint was rejected on latency, load, and stickiness-correctness all at once.
- Swap atomically via consensus, do not edit piecemeal. A change is one totally-ordered, immutable version committed by a Raft quorum and applied by a per-proxy stage-then-atomic-swap, so the fleet never disagrees about what a version means, concurrent changes are serialized instead of racing, and no request is ever routed by a half-applied config. Per-node config edits and best-effort pub/sub were rejected because they allow torn reads, split-brain on weights, and silent permanent drift - the exact failures the problem is about.
- Fixed bucket, moving band for sticky monotonic ramps. Stickiness is a deterministic bucket and a moving band boundary, so ramping the canary up only adds users and never flips a canary user back, a weight change re-slots the minimum set of sessions, and consistency across regions is free - with an optional hard cookie-pin for sessions that must be immune to any change, needing no server-side session store.
- Soft dependency over hard. Routing always runs from last-known-good config (persisted to disk) and sends only to health-filtered pools with cross-version failover, so a config-plane outage freezes rollouts but never stops traffic and a collapsing canary sheds its own load. The engineering goes into never blocking traffic on config, not into strong consistency the data plane does not need.
One-line summary: a traffic splitting service that routes a configurable percentage of live traffic across ~2,000 stateless edge proxies by a local, zero-network hash of a header stickiness key into fixed buckets with moving weight bands (sticky per session, monotonic on ramp-up, consistent across regions for free), and propagates every weight change as a single totally-ordered immutable version committed by a consensus quorum and applied fleet-wide by a per-proxy stage-then-atomic-swap - so routing is free, no user flips mid-session, and no request is ever routed by a partially-applied config during the ~1-second update window, with rollback and blue-green as the same atomic mechanism.
Comments