Everyone sketches federated learning the same way the first time: a server holds a global model, it ships the weights to a bunch of phones, each phone trains on its own local data, sends the updated weights back, and the server averages them. Repeat for a few rounds. It works in a notebook with three simulated clients that all finish instantly and all behave. Then the interviewer makes it the real problem: you have a hundred million devices in the fleet, only a fraction are online and eligible at any moment, a third of the ones you select will drop out mid-round because the phone got unplugged or left wifi, the raw training data must never leave the device (that is the entire point of doing this instead of centralizing the data), the individual updates you receive can leak the private data they were trained on if you look at them wrong, and somewhere in that crowd are clients sending deliberately poisoned updates trying to wreck or backdoor the global model. And it still has to converge to an accurate model within a bounded number of rounds, because each round costs real client battery and bandwidth and takes minutes.
The average-everything server cannot do any of that. If you wait for every selected client, one straggler stalls the round forever. If you plain-average the updates, one poisoned client with a huge malicious update drags the global model wherever it wants. If you treat the received updates as safe, a gradient-inversion attack reconstructs a user’s photos from them. So the central move of a federated coordinator is a robust, privacy-preserving aggregation protocol - federated averaging that fires on a deadline instead of waiting for everyone, down-weights or discards contributions that look like stragglers or attacks, and never sees any individual update in the clear. That one mechanism - how you select the cohort, bound the round, combine the updates safely, and still march toward convergence - is the whole game. Get it right and you train an accurate model on data you never touched. Get it wrong and you either never finish a round, or you ship a model one attacker steered, or you leak the very data you were trying to protect.
Let me do it properly.
Functional Requirements (FR)
In scope:
- Round orchestration. The coordinator runs training in rounds: select a cohort of clients, distribute the current global model, collect their local updates, aggregate them into a new global model, checkpoint it, repeat. This is the core loop and everything else serves it.
- Client selection (cohort formation). Each round picks a subset of eligible clients from a huge, intermittently-available fleet, by eligibility rules (online, idle, charging, on unmetered network) and sampling policy. We deliberately over-select to survive dropout.
- Federated averaging. Combine client updates into one global update, weighted by each client’s local sample count (the FedAvg rule), with server-side optimization (learning rate, momentum) applied on top.
- Robust aggregation. Down-weight or reject updates from stragglers (too slow, partial, stale) and poisoned / malicious clients (updates crafted to corrupt or backdoor the model) while still converging.
- Straggler tolerance. A round completes on a deadline with a sufficient quorum of updates, not by waiting for all selected clients. Late updates are dropped or folded in asynchronously.
- Privacy preservation. Raw data never leaves the client. Individual updates are protected via secure aggregation (the server sees only the sum, never a single update) and optional differential privacy (clipped, noised updates with a tracked privacy budget).
- Model versioning and convergence tracking. Every round produces an immutable, versioned global checkpoint; the coordinator evaluates it and tracks convergence to decide when to stop.
Explicitly out of scope (say this to control scope):
- The on-device training loop. The device SDK runs local SGD on local data; we define the contract (model in, update out, deadline, sample count) but do not implement the trainer or the mobile runtime.
- Raw data storage or movement. There is none on our side by design - the data stays on the device forever. We store models and transient updates, never training examples.
- Model architecture and hyperparameter search. We train a given architecture; choosing it and tuning local epochs / learning rate is upstream ML work.
- Serving the trained model. Once converged, the global model goes to a separate inference / serving platform. We are the training coordinator, not the predictor.
- Device fleet management / OTA delivery. Pushing the SDK and app to devices is a mobile-infra concern; we assume devices can reach us and run the SDK.
The one decision that drives everything: a federated coordinator is a trust-minimizing, deadline-bounded aggregation engine where the clients are untrusted, unreliable, and private, and the scarce resource is a successful round. You cannot see the data, cannot wait for every client, and cannot trust any single update - so the design is dominated by the aggregation protocol: how it forms a cohort, bounds the round on a deadline, combines updates robustly and privately, and still converges within a budget of rounds.
Non-Functional Requirements (NFR)
- Scale (two very different regimes). Cross-device: a fleet of ~100M mobile devices, ~1M online and eligible at any moment, 1k-10k selected per round, updates a few MB each. Cross-silo: tens to a few hundred organizations (hospitals, banks, on-prem data centers), each a reliable high-capacity participant with large local datasets. The protocol must cover both; cross-device is the harder, more unreliable regime and drives most decisions here.
- Round and campaign timing. A round is minutes (client local compute + upload + aggregation), not milliseconds. A training campaign is thousands of rounds over days to weeks. The hard timing target is the round deadline - the maximum we wait for updates before aggregating what we have.
- Convergence (the quality target). Reach a target validation accuracy within a bounded number of rounds (say, under a few thousand) despite non-IID client data, partial participation, and adversaries. Divergence or needing 10x the rounds is a failure.
- Availability. The coordinator must be highly available across a multi-week campaign; a crash mid-round must not corrupt the global model. Rounds are resumable and idempotent - a failed round is retried from the last durable checkpoint.
- Consistency. The global model version and round state are strongly consistent - there is exactly one current global model and one authoritative round state machine. A client must never train against a half-aggregated or ambiguous model.
- Durability. Global model checkpoints are durable and immutable (object storage, versioned). Transient per-round updates are disposable - a lost update just means that client sits out the round.
- Privacy and security (first-class, not an afterthought). Raw data never transmitted. Individual updates never visible to the server in the clear (secure aggregation). A tracked differential-privacy budget bounds what the final model can leak about any one client. No single client (or small colluding group) can dominate the global model - poisoning influence is bounded by design.
Back-of-the-Envelope Estimation (BoE)
Let me ground the design in numbers before drawing boxes.
Fleet, cohort, and participation:
Fleet: 100,000,000 devices total
Online + eligible now: 1,000,000 (idle, charging, on wifi)
Selected per round: 5,000 target participants
Over-selection: ~7,500 invited (expect ~30% dropout)
Completed per round: ~5,000 updates actually aggregated
So per round we touch ~7.5k devices to land ~5k updates. The fleet
is huge but each round is small - the scale is in the NUMBER of
rounds and devices over a campaign, not concurrent QPS.
Model and update size (the bandwidth driver):
On-device model: 2.5M params * 4 bytes (fp32) = 10 MB.
Download per client (global model): 10 MB.
Upload per client (the update): ~3 MB (quantized/compressed
from 10 MB; updates compress
well - 8-bit or sparse).
Per round:
Egress (model distribution): 7,500 * 10 MB = 75 GB (served via CDN)
Ingress (updates): 5,000 * 3 MB = 15 GB
Per round egress 75 GB over a ~3 min distribution window
= ~75 GB / 180 s = ~420 MB/s. One origin cannot do this for long;
model distribution MUST go through a CDN / object store, not the
coordinator. Ingress 15 GB is modest and lands on stateless
ingestion nodes.
Round and campaign timing:
Round budget:
model download ~15 s (10 MB on a phone)
local training 2-4 min (a few local epochs on local data)
update upload ~15 s
deadline / aggregation ~30 s
=> round wall-clock ~5 min
Campaign: converge in ~2,000 rounds.
Serial: 2,000 * 5 min = ~7 days.
Rounds can PIPELINE (round N+1's cohort downloads while round N
aggregates), shaving wall-clock, but convergence is inherently
sequential in the model version - you cannot parallelize away the
dependency, only overlap the edges.
Aggregation compute and memory (the aggregator sizing):
Aggregate 5,000 updates, each 2.5M params.
Naive: hold all in RAM = 5,000 * 10 MB = 50 GB per round. Big but
fits on one fat box - OR stream them:
Streaming sum: keep ONE running weighted accumulator (10 MB) and
add each update as it arrives, then divide. O(model size) memory,
not O(cohort * model size). This is the key to not needing 50 GB.
Compute: 5,000 vector adds of 2.5M floats = ~12.5 GFLOP. Trivial -
aggregation is bandwidth/robustness-bound, not compute-bound.
Checkpoint storage:
One checkpoint per round: 10 MB * 2,000 rounds = ~20 GB per campaign
in object storage. We keep every checkpoint (cheap) for rollback
and reproducibility; only the latest is "current." Trivial storage;
the value is immutability and versioning, not volume.
The takeaway: this is a round-oriented, deadline-bounded, trust-minimizing system, not a high-QPS one. The scarce resource is a completed, trustworthy round. Model distribution is a CDN problem (75 GB/round egress), update ingestion is light and stateless, aggregation is cheap if streamed, and the whole design pressure is on finishing rounds despite dropout, combining updates despite adversaries, and never seeing the data or the individual updates - while still converging inside a few thousand rounds.
High-Level Design (HLD)
A federated coordinator is a loop driven by a strongly-consistent control plane (the round state machine and the one current global model), fed by a huge, flaky, untrusted client fleet. The intelligence sits in four places: a selector (form the cohort), a CDN/model store (distribute the global model cheaply), a stateless ingestion tier (receive and validate updates at scale), and an aggregator (combine updates robustly and privately into the next global model).
┌──────────────────────────────────────┐
│ CONTROL PLANE (Raft-backed, strong) │
│ - campaign config + policy │
│ - ROUND STATE MACHINE (one per round)│
│ - current global model version │
│ - DP budget accounting │
└───────┬───────────────────▲───────────┘
│ drives round │ commits new
▼ │ model version
┌───────────────┐ ┌───────────────┐ ┌─────┴──────────┐
│ SELECTOR │ │ MODEL STORE │ │ AGGREGATOR │
│ eligibility + │ │ + CDN (reads │ │ robust FedAvg + │
│ over-selection │ │ global model)│ │ secure-agg sum │
└──────┬────────┘ └──────▲────────┘ └─────▲──────────┘
│ invite │ pull model │ masked updates
│ (round config, │ (signed URL) │ (streamed sum)
│ deadline) │ │
┌──────▼─────────────────────────────────────────┴──────────┐
│ UPDATE INGESTION TIER (stateless, scaled) │
│ - authenticate client, validate update shape/size │
│ - run secure-aggregation protocol (masked inputs) │
│ - buffer into per-round accumulator (streaming sum) │
│ - enforce round DEADLINE; drop late/straggler updates │
└──────▲──────────────────────────────────────────▲──────────┘
│ 1. check-in 4. upload masked update
│ │
┌───────────┴───────────────────────────────────────────┴─────────┐
│ CLIENT FLEET (100M devices / N on-prem silos) - UNTRUSTED │
│ on-device SDK: download model -> train on LOCAL data (never │
│ leaves) -> compute update -> clip + noise (DP) -> mask -> upload │
└──────────────────────────────────────────────────────────────────┘
Object storage: immutable versioned global-model checkpoints + eval metrics.
Round path - one training round, end to end:
- The control plane starts round
Rfor a campaign: it fixes the current global model versionv, the target cohort size, the deadline, and the aggregation/privacy policy, and writes the round into its state machine (state =SELECTING). - Eligible devices check in to the ingestion tier (“I am online, idle, charging, on wifi, running SDK version X”). The selector accepts a cohort by policy and over-selects (invite ~1.5x target to absorb dropout). Rejected devices are told to come back later. Accepted devices get the round config, a signed URL to download model
v, and the deadline by which their update must arrive. - Each accepted client downloads global model
vfrom the CDN/model store (not from the coordinator - the CDN absorbs the 75 GB egress), then runs local training on its on-device data: a few epochs of SGD producing a local update (the delta fromv). The data never leaves the device. - The client clips its update to a norm bound and adds differential-privacy noise (if the policy requires it), then masks it for secure aggregation (pairwise random masks that cancel only in the sum), and uploads the masked update plus metadata (sample count, local loss, compute time) to the ingestion tier before the deadline.
- The ingestion tier authenticates the client, validates the update’s shape and norm, participates in the secure-aggregation protocol, and folds the masked update into a per-round streaming accumulator. It tracks how many of the cohort have reported.
- At the deadline (or once a sufficient quorum has reported), the round stops accepting updates (state =
AGGREGATING). Late / straggler updates are dropped. The aggregator unmasks the sum (never any individual update), applies robust federated averaging (weighted by sample count, with outlier updates down-weighted or trimmed), and applies server-side optimization to produce the new global modelv+1. - The control plane commits
v+1as a new immutable checkpoint in object storage, charges the DP budget, runs evaluation on a held-out set, and advances the round state machine. If the stopping criterion is met (target accuracy or round cap), the campaign ends; otherwise roundR+1begins againstv+1.
Failure handling: a client that drops out after being invited simply never uploads - the deadline and over-selection absorb it. An ingestion node that dies loses only the partial masked updates buffered on it (those clients sit out the round); the streaming accumulator is checkpointed so aggregation survives. The control plane is Raft-backed, so the round state machine and current model version survive node loss; a round that crashes mid-aggregation is retried from the last committed checkpoint - rounds are idempotent because they are pure functions of (model v, the set of updates received).
The architectural insight: the control plane owns the one strongly-consistent truth (current model version + round state), model distribution is offloaded to a CDN so the coordinator never serves the heavy egress, update ingestion is a stateless horizontally-scaled tier that speaks the secure-aggregation protocol and enforces the deadline, and the aggregator only ever sees the masked sum - so selection, distribution, ingestion, and aggregation are four decoupled concerns, and the server is structurally incapable of seeing a single client’s data or update.
Component Deep Dive
Three hard parts: (1) the robust aggregation protocol - federated averaging that down-weights stragglers and resists poisoning while converging, (2) privacy-preserving aggregation - secure aggregation plus differential privacy so the server never sees an individual update and the final model leaks little, and (3) round orchestration and fault tolerance - selecting cohorts and running resumable, deadline-bounded rounds at fleet scale. I walk each from naive to scalable.
1. Robust Federated Averaging: the aggregation protocol
This is the whole reason the coordinator exists. It decides how thousands of untrusted, uneven updates become one good global model.
Approach A: Plain mean of all updates (the naive instinct)
Wait for every selected client, average their updates with equal weight, apply to the global model.
for client in selected: # blocks on the SLOWEST client
collect update_i
global_v+1 = global_v + mean(update_1 ... update_n)
Where it breaks - on two independent axes, immediately.
- Stragglers stall the round. Waiting for every selected client means the slowest phone (backgrounded, throttled, on a weak radio) sets the round time. In a cross-device fleet, ~30% simply never report - so “wait for all” means the round never completes. The whole round is held hostage by the worst participant.
- Equal weight ignores data size. A client that trained on 5 examples counts as much as one that trained on 5,000. The global model should reflect clients proportional to how much data backs their update, not one-device-one-vote. This is exactly the FedAvg correction.
- One poisoned client owns the mean. The arithmetic mean is unbounded in any single input. An attacker who sends an update 1000x the normal norm shifts the mean by that client alone - a single malicious participant can arbitrarily steer, degrade, or backdoor the global model (train it to misclassify a chosen trigger). The mean has zero robustness; it assumes every input is honest, which is false by assumption in a federated setting.
Approach B: Deadline-bounded, sample-weighted federated averaging (FedAvg proper)
Stop waiting for everyone - aggregate on a deadline with whatever quorum reported, and weight by local sample count.
At deadline, with received set S (|S| >= quorum):
total_n = sum(n_i for i in S) # n_i = client i's sample count
global_v+1 = global_v + sum( (n_i/total_n) * clipped_update_i
for i in S )
# then apply server-side optimizer (learning rate, momentum)
- Deadline + over-selection solves stragglers: invite ~1.5x the target, aggregate the first quorum that reports by the deadline, drop the rest. The round time is now bounded by the deadline, not the slowest client. A client that would have straggled simply does not count this round and may be picked again later.
- Sample weighting (
n_i / total_n) is the FedAvg correction: clients with more local data count proportionally more, which is the statistically right thing when combining locally-trained updates. - Where it still breaks: poisoning. Weighting by
n_iis honest-client-correct but adversary-exploitable - a malicious client can lie aboutn_ito buy weight, or send a large-norm update. We clip each update’s norm first (bounds magnitude), but a clever attacker sends many small, aligned poisoned updates (a sybil swarm) that a weighted mean still happily averages in. Norm-clipping bounds one client’s magnitude but not a coordinated direction. We need the aggregation itself to be robust to a fraction of adversaries.
Approach C: Robust aggregation - trim, median, and distance-based down-weighting
Replace (or guard) the mean with an estimator that tolerates a bounded fraction of arbitrary (Byzantine) inputs.
PER-COORDINATE TRIMMED MEAN:
for each parameter j:
take the n values update_i[j] across clients
drop the top beta% and bottom beta% (the outliers)
average the middle (1 - 2*beta)%
-> a single extreme client cannot move any coordinate; it is trimmed.
COORDINATE-WISE MEDIAN:
global update[j] = median over clients of update_i[j]
-> breakdown point ~50%: up to half the clients can be arbitrary
and the median still tracks the honest majority. Cheap, robust,
slightly noisier than trimmed mean.
KRUM / MULTI-KRUM (distance-based selection):
for each client, sum the distances to its k nearest neighbor updates.
pick the client(s) with the SMALLEST such sum (most "central",
best agreeing with the crowd); average those, discard the rest.
-> a poisoned update that points far from the honest cluster has a
large neighbor-distance and is never selected. Resists updates
that are far from the consensus direction, not just large in norm.
- Why this works: honest clients, even with non-IID data, cluster loosely in update space; a poisoning attack must push away from that cluster to do damage, which is exactly what trimming, median, and distance-based selection detect and discard. You bound the adversary’s influence to at most a
betafraction regardless of how large or clever each malicious update is. - The cost / trade-off: robustness throws away information. Trimming honest tail clients (especially legitimately-unusual non-IID clients) slows convergence slightly; median is noisier than mean. You tune
betato the assumed adversary fraction - too low and an attacker slips through, too high and you discard honest signal and converge slower. Krum/Multi-Krum is O(n^2) in distance computation per round, fine at 5k but something to note.
Refinements that make robust aggregation production-grade
NORM CLIPPING FIRST (always): clip every update to ||update|| <= C
before aggregation. Bounds any single client's magnitude, caps the
damage of a large-norm attack, and is the enabling step for
differential privacy (bounded sensitivity). Cheap, do it always.
ADAPTIVE DOWN-WEIGHTING (reputation): instead of hard trim/keep,
weight each client by how well its update agrees with the robust
aggregate (e.g. cosine similarity to the median direction) AND by a
persistent per-client reputation score across rounds. A client that
repeatedly submits outlier updates earns a low weight and fades out
without being hard-banned - softer than Krum, robust to the
occasional honest outlier.
STALENESS DOWN-WEIGHTING: in semi-async rounds (below), an update
trained against an OLD model version v-k is stale. Weight it by a
decay factor f(k) so a late/stale update contributes less, bounding
the error it injects. A very stale update (k too large) is dropped.
SERVER-SIDE MOMENTUM / FedProx: the server runs its own optimizer on
the aggregate (momentum, adaptive LR) to speed convergence; FedProx
adds a proximal term so local training does not drift too far from
the global model on non-IID clients, which both speeds convergence
and reduces the spread that robust aggregation has to tolerate.
So aggregation is not one average: deadline-bounded, sample-weighted FedAvg handles stragglers and data imbalance; norm clipping plus robust estimators (trimmed mean / median / Multi-Krum) plus adaptive reputation down-weighting bound the influence of poisoned and straggling clients - all tuned so the global model still converges within the round budget despite never trusting any single contribution.
2. Privacy-Preserving Aggregation: secure aggregation + differential privacy
Keeping raw data on the device is necessary but not sufficient. The updates themselves leak. This deep dive is why the server is structurally blind.
Approach A: Trust the server with plaintext updates (naive)
Clients send their raw updates; the server averages them. “The data stayed on the device, so we are private.”
Where it breaks - the update is not safe. A model update (gradient / weight delta) is a function of the client’s private data, and gradient-inversion attacks can reconstruct the original training examples - pixels of a photo, tokens of a message - from a single client’s update, especially for small local batches. Even without full reconstruction, the server (or anyone who compromises it) can infer membership (“was this specific record in client X’s data?”) and attributes. “Data never left the device” is a lie if a faithful copy of the information in that data left inside the update. We need the server to be unable to see any individual update, only the aggregate.
Approach B: Secure aggregation - the server sees only the sum
Clients cryptographically mask their updates with pairwise random values that cancel out only when summed, so the server can compute the sum of all updates without seeing any single one.
SETUP (per round): every pair of clients (i, j) agrees on a shared
random mask m_ij (via Diffie-Hellman key exchange, coordinated by
the server who only relays public keys - it never learns the masks).
MASK: client i sends masked_i = update_i + sum_j(+/- m_ij)
where the sign is +1 if i<j, -1 if i>j, so m_ij and m_ji are
opposite.
SUM: server adds all masked updates:
sum_i(masked_i) = sum_i(update_i) + sum_of_all_pairwise_masks
= sum_i(update_i) + 0 # masks cancel pairwise!
The server gets the true SUM, and each masked_i on its own looks
like uniform random noise - it reveals nothing about update_i.
- Why it works: each individual
masked_iis indistinguishable from random to the server; only the complete sum collapses the masks to zero. The server learnssum(update_i)(which is all FedAvg needs) and provably nothing about any single client’s update. - The hard problem: dropout. If client
idrops out after exchanging masks but before uploading, its masksm_ijno longer cancel - the sum is garbage. In a cross-device fleet where 30% drop, naive pairwise masking collapses every round. The fix is threshold secret sharing of the masks: each client secret-shares its mask seeds across the cohort so that if a client drops, a threshold of the others can reconstruct and remove the dangling masks of the dropped client (and nothing else). This tolerates dropout up to a threshold while still hiding every present client’s update. It costs extra rounds of communication and O(n^2) pairwise work, so we partition the cohort into smaller secure-aggregation groups (say, groups of a few hundred) and sum the group results, keeping the pairwise cost bounded.
Approach C: Add differential privacy - bound what even the sum reveals
Secure aggregation hides individual updates during aggregation, but the final model can still memorize and leak a specific client’s contribution. Differential privacy bounds that.
PER-CLIENT (local-ish DP): client clips its update to norm C (bounds
one client's sensitivity) and the mechanism adds calibrated Gaussian
noise. With secure aggregation, the noise can be added such that
only the SUM carries enough noise for a (epsilon, delta) guarantee -
distributed DP - so you do not pay the heavy accuracy cost of each
client noising fully on its own.
GUARANTEE: the final model is (epsilon, delta)-differentially private
with respect to any single client's participation: an observer
cannot tell whether any given client was in the training set. We
track a PRIVACY BUDGET (epsilon spent) across rounds via a moments
accountant / RDP accountant; when the budget is exhausted, the
campaign must stop - privacy is a finite, accounted resource.
- Secure aggregation and DP are complementary, not redundant. Secure aggregation hides updates from the server during a round (process privacy); differential privacy bounds what the released model leaks about any client (output privacy). You want both: the server never sees an individual update, and even the model it ships cannot be inverted back to a client.
- The trade-off is accuracy. Clipping discards update magnitude and noise degrades the signal; too tight a clip or too much noise and the model converges worse or not at all. You tune the clip norm
Cand noise multiplier against the DP budget and the accuracy target - the central privacy/utility dial. Larger cohorts help: more clients per sum means the fixed noise is amortized over more real signal, so DP is cheaper per unit accuracy at scale.
So privacy is two layers: secure aggregation (pairwise masking with threshold secret-sharing for dropout) makes the server structurally blind to individual updates, and differential privacy (per-client norm clipping plus calibrated noise under a tracked budget) bounds what the final model can leak about any one participant - together turning “the data stayed on the device” into an actual guarantee rather than a slogan.
3. Round Orchestration and Fault Tolerance at Scale
The aggregation math assumes a clean round with a known cohort and a clean restart on failure. Delivering that against 100M flaky devices and multi-week campaigns is its own hard problem.
Approach A: Synchronous “select-wait-aggregate” loop on one coordinator (naive)
One process selects N clients, blocks until all N report, aggregates, writes the model, loops.
Where it breaks. It inherits the straggler stall (covered above), but worse at the orchestration level: a single coordinator is a SPOF - if it crashes mid-round, the round state (who was selected, which updates arrived, the partial accumulator) is lost and you restart the round from scratch, wasting every client’s completed work. With 5-minute rounds over a week, a crash is near-certain; losing a whole round each time wrecks both wall-clock and client goodwill (wasted battery). And one process cannot run the secure-aggregation handshake and ingest for thousands of concurrent clients.
Approach B: Round state machine on a replicated control plane + resumable rounds
Model each round as an explicit state machine persisted in a Raft-backed control store, and make rounds pure functions of their inputs so they are idempotent and resumable.
ROUND STATE MACHINE (per round, durable in Raft store):
SELECTING -> cohort chosen, invites sent, model version pinned
COLLECTING -> ingestion buffering masked updates; deadline running
AGGREGATING-> deadline hit, quorum met, computing robust sum
COMMITTED -> new model v+1 written to object store, DP budget charged
(FAILED/ABORTED -> quorum not met or error -> retry or re-select)
Transitions are committed through Raft -> survive coordinator crash.
A standby coordinator reads the current state and resumes:
- crash in COLLECTING: resume collecting; the accumulator is
checkpointed periodically, so already-received updates are kept.
- crash in AGGREGATING: re-run aggregation from the checkpointed set
(pure function of model v + received updates -> deterministic).
- crash before COMMITTED: v+1 was never published, so no client ever
saw a half-baked model; retry is safe and invisible.
- Idempotent, resumable rounds mean a crash costs a resume, not a lost round. The new global model is only published (version incremented) at the atomic
COMMITTEDtransition, so clients never train against a partial model - the strong-consistency requirement on the model version is satisfied by committing it exactly once through Raft. - Separation of planes: the Raft control plane holds only small, slow-changing truth (round state, current version, DP budget) - a handful of writes per round, not per client. The heavy per-client work (secure-agg handshake, update ingestion, streaming accumulation) runs on the stateless, horizontally-scaled ingestion tier, which checkpoints its accumulator to durable storage. This keeps Raft out of the hot path.
Client selection at fleet scale, and pipelining rounds
SELECTION without scanning 100M devices every round:
Devices CHECK IN when they become eligible (idle/charging/wifi) and
sit in a short-lived eligibility pool (a queue / sampled stream).
The selector draws the cohort from whoever is checked-in RIGHT NOW -
it never enumerates the fleet. Over-select ~1.5x. Apply:
- eligibility filters (SDK version, OS, locale if targeted)
- pacing: cap how often any single device participates (fairness +
privacy budget per device + battery)
- unbiased sampling: avoid always picking the same always-on
devices, which would bias the model toward their data.
PIPELINING: round R+1 can SELECT and DISTRIBUTE its model while round
R is still AGGREGATING, overlapping the idle edges. But the model
version is sequential (R+1 trains on v produced by R), so you cannot
run two rounds' AGGREGATION concurrently on the same lineage - you
overlap I/O, not the dependency. For throughput you can also run
MULTIPLE INDEPENDENT CAMPAIGNS concurrently, each its own lineage.
- Semi-asynchronous option (FedBuff-style): instead of strict rounds, keep a rolling buffer - aggregate as soon as
Kupdates have arrived (regardless of round boundary), apply with staleness down-weighting for updates trained on an older version, and immediately re-distribute. This removes the deadline-stall entirely and raises device utilization, at the cost of handling stale updates carefully. It is the right choice when the fleet is very large and dropout-heavy; strict synchronous rounds are simpler to reason about and to apply DP accounting to. A real system often runs synchronous rounds with a generous deadline and over-selection as the default and reaches for async only when straggler tails dominate.
So orchestration is an explicit, Raft-persisted round state machine with idempotent resumable rounds (crash costs a resume, not a lost round), cohort selection from a live check-in pool with pacing and unbiased sampling (never scanning the fleet), and pipelined or semi-async rounds to keep the huge flaky fleet productive - all keeping the one strongly-consistent truth (current model version) clean while the heavy per-client work scales out statelessly.
API Design & Data Schema
The coordinator exposes a client protocol (check-in, download, upload - the hot path spoken by the device SDK) and a control/admin API (manage campaigns). The durable state is small and relational (campaigns, rounds, checkpoints metadata); the heavy state is model blobs and transient masked updates.
Client protocol (device SDK <-> coordinator)
POST /v1/campaigns/{campaign_id}/checkin # "I am eligible"
{ "client_token": "...", # pseudonymous, attested
"sdk_version": "...", "os": "...",
"net": "wifi", "charging": true, "idle": true }
-> 200 ACCEPTED {
"round_id": "r_8842",
"model_version": "v8841",
"model_url": "https://cdn/.../v8841", # signed, time-boxed
"deadline_ts": 1764300000, # upload by this time
"train_config": { "local_epochs": 2, "lr": 0.01,
"clip_norm_C": 4.0, "dp_noise": 0.6 },
"secure_agg": { "group_id": "g_17", "peers_pubkeys_url": "..." } }
-> 200 REJECTED { "retry_after_s": 300 } # not selected; back off
POST /v1/rounds/{round_id}/updates # upload MASKED update
Headers: Authorization (attested client token), X-Client-Id
{ "group_id": "g_17",
"masked_update": <bytes>, # update + secure-agg mask
"sample_count": 312, # n_i for FedAvg weight
"metrics": { "local_loss": 0.44, "compute_ms": 143000 },
"trained_on_version": "v8841" } # staleness check
-> 202 ACCEPTED # before deadline + passes shape/norm checks
-> 409 ROUND_CLOSED # deadline passed -> client's work is dropped
POST /v1/rounds/{round_id}/secure-agg/recover # dropout recovery
{ "group_id": "g_17", "dropped_client_id": "...",
"mask_share": <bytes> } # threshold secret share
-> 200 OK # lets the server cancel a dropped client's dangling masks
Control / admin API
POST /v1/campaigns # start a campaign
{ "model_arch_ref": "...", "init_model_url": "s3://.../v0",
"cohort_size": 5000, "over_select": 1.5, "round_deadline_s": 300,
"aggregation": { "rule": "multi_krum|trimmed_mean|median",
"trim_beta": 0.1, "server_momentum": 0.9 },
"privacy": { "secure_agg": true, "dp": { "epsilon": 8.0,
"delta": 1e-9, "clip_norm_C": 4.0 } },
"stopping": { "target_accuracy": 0.92, "max_rounds": 3000 } }
-> { "campaign_id": "c_42", "status": "running" }
GET /v1/campaigns/{id} # status, current round, convergence curve,
# DP budget spent, accuracy history
POST /v1/campaigns/{id}/stop # halt; latest committed model is final
GET /v1/campaigns/{id}/model # signed URL to the latest global checkpoint
GET /v1/fleet/eligibility # live check-in pool size, participation stats
Data model - a small consistent control store + blobs + transient buffer
SQL vs NoSQL: the control-plane state (campaigns, rounds, checkpoint metadata, DP budget) is small, relational, and must be strongly consistent - the current model version and round state cannot diverge, so it lives in a Raft-backed / strongly-consistent SQL-style store, not an eventually-consistent NoSQL store (a split current-version would have clients training against two different models). Model checkpoints are large immutable blobs in object storage, referenced by URI. The per-round masked updates are high-volume, transient, and disposable - they live in a fast KV/in-memory buffer with a streaming accumulator, never a durable relational table (a lost update just drops that client from the round).
1. Campaign (durable, strongly consistent):
campaign
campaign_id STRING PRIMARY KEY
model_arch_ref STRING
cohort_size INT over_select FLOAT round_deadline_s INT
aggregation_cfg JSON # rule, trim_beta, server optimizer
privacy_cfg JSON # secure_agg flag, DP epsilon/delta/clip
dp_epsilon_spent FLOAT # running privacy budget consumed
stopping_cfg JSON # target_accuracy, max_rounds
current_version STRING # the one authoritative global model version
status ENUM # running | converged | stopped | failed
created_at TIMESTAMP
- current_version is the single source of truth clients train against;
updated atomically only at a round's COMMITTED transition.
2. Round (durable, the state machine):
round
round_id STRING PRIMARY KEY
campaign_id STRING INDEX
round_number INT
model_version STRING # the version this round trains against
state ENUM # SELECTING|COLLECTING|AGGREGATING|COMMITTED|FAILED
deadline_ts TIMESTAMP
selected_count INT received_count INT quorum INT
result_version STRING # the v+1 produced (null until COMMITTED)
accumulator_ref STRING # pointer to checkpointed streaming sum
PRIMARY KEY (round_id)
INDEX (campaign_id, round_number)
- transitions committed through Raft; a round is a pure function of
(model_version, received update set) so re-running is deterministic.
3. Model checkpoint (durable, immutable - control store metadata + blob):
model_checkpoint
version STRING PRIMARY KEY # "v8841"
campaign_id STRING round_number INT
artifact_uri STRING # s3://models/c_42/v8841 (immutable weights)
eval_metrics JSON # accuracy, loss on held-out set
created_at TIMESTAMP
- immutable; a new round always writes a NEW version, never overwrites
-> clean rollback, reproducibility, and safe concurrent reads by
the next cohort downloading the model.
4. Client participation / pacing (soft, for fairness + privacy):
client_participation (KV store, keyed by client pseudonym)
client_id STRING # pseudonymous, per-campaign, not a user id
campaign_id STRING
last_round INT # for pacing (don't pick too often)
rounds_joined INT # per-device privacy/battery budget
reputation FLOAT # rolling agreement-with-aggregate score
- soft state; drives selection pacing and adaptive down-weighting.
Keyed by a pseudonym, never by a user identity - we store no PII.
5. Per-round update buffer (transient, in-memory / fast KV, NEVER durable relational):
round_accumulator (RAM + periodic checkpoint to object store)
round_id
weighted_sum BYTES # streaming sum( n_i * masked_update_i )
total_n INT64 # sum of sample counts, for the FedAvg divide
received_set SET<client_id> # who has reported (dedupe, quorum)
mask_shares MAP # threshold secret shares for dropout recovery
- O(model size) memory via streaming, not O(cohort * model size).
Individual masked updates are folded in and DISCARDED immediately;
the server retains only the running sum - it cannot reconstruct any
single update even if it wanted to.
Why these choices: the current model version and round state must be globally agreed (clients across the planet must all train against exactly one model), so they sit in a Raft-backed store written once per round, not per client. Checkpoints are immutable versioned blobs, which is what makes rollback and reproducibility trivial and lets the next cohort read a frozen model safely. The update buffer is a transient streaming accumulator that discards individual updates on arrival - that is not just an efficiency choice, it is a privacy property: the server structurally retains only the sum. And client participation is keyed by a per-campaign pseudonym, never a user identity, because storing who-trained-on-what would reintroduce exactly the privacy risk the whole system exists to remove.
Bottlenecks & Scaling
Where it breaks first, in order, and the fix for each:
1. Waiting for every selected client (breaks before anything else). One straggler or dropout stalls or kills the round; ~30% of a cross-device cohort never reports. Fix: over-select ~1.5x and aggregate on a deadline with whatever quorum reported. The round time is bounded by the deadline, not the slowest device. Late updates are dropped (or folded in async with staleness down-weighting). This is the foundational fix.
2. The mean has zero robustness (poisoning). A single large-norm or coordinated update steers, degrades, or backdoors the global model.
Fix: norm-clip every update, then use a robust estimator - per-coordinate trimmed mean / median or Multi-Krum - plus adaptive reputation down-weighting across rounds. Bounds any adversary’s influence to a beta fraction regardless of how extreme the update, at the cost of discarding some honest tail signal.
3. Model distribution egress. 7.5k clients pulling a 10 MB model is ~75 GB/round from the origin - one coordinator cannot serve it. Fix: distribute the global model via a CDN / object store with signed, time-boxed URLs; the coordinator hands out URLs, not bytes. Compress checkpoints and, where possible, ship deltas from the version a client already has.
4. Secure-aggregation dropout blowup. Pairwise masks do not cancel if a masked client drops, corrupting the whole sum; naive secure-agg collapses under 30% dropout. Fix: threshold secret-sharing of mask seeds so a quorum of survivors can cancel a dropped client’s dangling masks, and partition the cohort into secure-agg groups of a few hundred to keep the O(n^2) pairwise cost bounded. Sum the group results.
5. Sybil / coordinated poisoning at scale. An attacker spins up many fake clients to outvote the honest majority of a robust estimator. Fix: client attestation (device integrity / app attestation so a client is a real attested device, not a script), per-device participation pacing (one device cannot flood many slots), and robust aggregation tuned to the assumed adversary fraction. Authentication caps how many slots the adversary can buy; robust aggregation caps how much each slot moves the model.
6. Non-IID divergence / slow convergence. Client data distributions differ wildly; naive FedAvg drifts and needs far more rounds, and robust trimming of honest outliers makes it worse. Fix: FedProx (a proximal term keeping local training near the global model), server-side momentum / adaptive optimization on the aggregate, and unbiased cohort sampling so the model is not biased toward always-online devices. Larger cohorts reduce variance and let robust estimators keep more honest signal.
7. Coordinator single point of failure. A crash mid-round loses selection + partial accumulator, wasting every client’s completed work over a multi-week campaign. Fix: Raft-backed round state machine with idempotent, resumable rounds - transitions are durable, the accumulator is checkpointed, and a round re-runs deterministically from (model version + received set). The new model version is published exactly once at the atomic COMMITTED transition, so clients never see a half-aggregated model.
8. Per-client communication cost. Uploading a full 10 MB update from a metered, battery-limited phone every round is expensive and caps participation. Fix: compress updates (8-bit or lower quantization, top-k sparsification, random sketching / count-sketch) to a few MB or less, participate less frequently per device (pacing), and only invite clients on unmetered, charging conditions. Communication, not compute, is the client-side bottleneck.
9. Aggregator memory under a large cohort. Holding 5k x 10 MB = 50 GB of updates to average is wasteful and caps cohort size. Fix: streaming weighted-sum accumulation - fold each masked update into one running accumulator (O(model size) memory) and discard it immediately; for robust estimators that need the distribution (median/trim), use hierarchical / tree aggregation across partial aggregators so no single node holds the full cohort, combining partial robust statistics.
10. Privacy budget exhaustion and privacy/utility tension. Each round with DP spends epsilon; too much noise or too tight a clip and the model will not converge, too little and the guarantee is meaningless.
Fix: track the DP budget with an RDP / moments accountant and stop the campaign when it is spent; amortize noise over large cohorts (bigger sums dilute fixed noise) and tune clip norm C and noise multiplier against the accuracy target. Privacy is a finite, accounted, first-class resource, budgeted up front like any other.
Wrap-Up
The trade-offs that define this design:
- Finish on a deadline, not on everyone. The core move against an unreliable fleet is to over-select and aggregate whatever quorum reports by a deadline, dropping stragglers - we trade a little per-round data loss for rounds that actually complete, because waiting for the slowest of thousands of phones means waiting forever.
- Never trust a single update. We assume adversaries are present, so we norm-clip every update and combine with a robust estimator (trimmed mean / median / Multi-Krum) plus reputation down-weighting - bounding any one client’s or small group’s influence to a fixed fraction, at the cost of discarding some honest outlier signal and tuning
betato the assumed adversary rate. - The server is structurally blind. Secure aggregation (pairwise masking with threshold secret-sharing for dropout) means the coordinator only ever sees the sum, never an individual update, and the streaming accumulator discards each update on arrival - so gradient-inversion has nothing to invert. We pay extra crypto handshakes and O(n^2) pairwise work (bounded by grouping) for a hard privacy guarantee rather than a promise.
- Bound what the model itself leaks. Differential privacy (per-client clipping plus calibrated noise under a tracked epsilon budget) caps what the released model can reveal about any participant, complementing secure aggregation’s process privacy with output privacy - trading some accuracy and a finite privacy budget for a provable guarantee, amortized cheaper at large cohort sizes.
- One consistent truth, everything else scales out. The current model version and round state live in a Raft-backed control plane written once per round; model distribution offloads to a CDN; update ingestion and secure-aggregation run on a stateless horizontally-scaled tier; rounds are idempotent and resumable so a crash costs a resume, not a lost round - keeping strong consistency exactly where correctness needs it and nowhere it would bottleneck.
- Communication and rounds are the scarce resources, not compute. Aggregation is cheap arithmetic; the cost is client bandwidth/battery and the sequential dependency between model versions - so we compress updates, pace participation, pipeline the idle edges of rounds, and converge in a bounded round budget rather than chasing per-request throughput.
One-line summary: a federated coordinator is a trust-minimizing, deadline-bounded round engine where a Raft-backed control plane owns the one current model version, a CDN distributes it, a stateless tier ingests masked updates under secure aggregation so the server never sees a single one, and robust federated averaging (norm-clip + trimmed-mean/Krum + reputation and staleness down-weighting, with differential-privacy noise under a tracked budget) turns thousands of unreliable, private, partly-adversarial client updates into an accurate global model that converges within a bounded number of rounds - all without a single raw training example ever leaving the device that owns it.
Comments