Feature Flag Delivery and Live Experiment Metrics at Scale
System DesignModel answerLast updated
Design a system that ships versioned feature flags to 10M devices with fast global rollback, plus a streaming pipeline that computes per-version click-through rates in near real time.
Problem
A large consumer streaming app controls its behavior with thousands of remotely managed feature flags. Teams use them for staged launches and A/B experiments. Design the two cooperating subsystems below.
1. Flag delivery service
Publishes flag changes to millions of devices. It must:
- version every change,
- support gradual exposure (for example 5%, then 25%, then 100%),
- support a global rollback that takes effect almost immediately.
2. Engagement telemetry pipeline
Ingests impression and click events from devices and computes near-real-time click-through rate (CTR) for each flag version, so a bad rollout can be detected quickly.
Requirements
- Scale: 10 million devices online at once, each either polling or being pushed config. About 500,000 telemetry events per second worldwide.
- Consistency: Devices must converge on a consistent config within a bounded window. A rollback must reach all devices in under 30 seconds.
- Storage: Config payloads are small JSON documents. Telemetry must feed real-time dashboards and be retained for 30 days.
What to cover
- API design: the calls a device uses to fetch config and to upload events, plus the admin-side calls.
- Data model: how config versions are stored, and how each event is tied to the config version that produced it.
- Architecture: the full path from an admin change to a device, and from a device event to an aggregated CTR number.
- Trade-offs: how you prevent a thundering herd when a config changes, and how you balance freshness against correctness in the telemetry aggregates.
State your assumptions and back-of-the-envelope numbers, and mention failure modes.
Hints
Hint 1
Do the arithmetic first: 10M devices polling every ~15s is hundreds of thousands of requests per second. What kind of serving tier makes that cheap, and what property must the response have?
Hint 2
Consider shipping the rollout rule (percentage plus salt) rather than per-device decisions, so every device downloads identical bytes and a ramp from 5% to 25% keeps earlier users in treatment.
Hint 3
Make snapshot IDs monotonic and treat rollback as a new snapshot with old content. Then think about how events carry the flag version and variant, and how to avoid hot keys and double counting in the stream job.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size
Config side
- 10M devices. A full snapshot is roughly 50-200 KB compressed; a single flag change is a few hundred bytes.
- Rollback in under 30s rules out slow polling. If each device polls every 15s, that is about 10M / 15 ≈ 670K requests/s. That is trivial for a CDN serving tiny cached objects and dangerous for a database-backed service.
Telemetry side
- 500K events/s x ~500 B ≈ 250 MB/s ≈ 21 TB/day raw, so about 650 TB over 30 days raw, or roughly 130 TB with columnar compression.
- Freshness target: dashboards about 1 minute; automated canary decisions can wait 2-5 minutes but must be accurate.
Non-goals: the authoring UI and rich targeting beyond percentage, region and device type.
2. APIs
Device-facing (CDN edge)
GET /config/manifest?env=®ion=returns{snapshot_id, url, poll_interval_s}with a short TTL (about 5s).GET /config/snap/{id}-{hash}.jsonreturns the full snapshot. It is immutable and content-addressed, so it can be cached for a year.POST /events/batchtakes gzip batches (up to 100 events or 5s) and returns202.
Admin-facing
PUT /flags/{key}creates a new flag version.POST /flags/{key}/rollout {bp}changes the exposure.POST /rollback {to_snapshot}reverts globally.- All calls are authenticated, audited and require a reason.
Key decision: ship the rule, not the outcome. The snapshot carries rollout_bp (basis points) and a salt. Each device computes bucket = hash(device_id + salt) % 10000 and is in treatment if bucket < rollout_bp. Benefits:
- Every device gets the same bytes, so the CDN hit rate is near 100%.
- Assignment is monotonic: growing from 5% to 25% keeps the original 5% in treatment.
- Assignment is deterministic and reproducible offline.
3. Data model
Config store (strongly consistent: Postgres, Spanner or CockroachDB)
flags(flag_key, owner, schema)flag_versions(flag_key, version, rules_json, rollout_bp, salt, status, author, created_at), immutable rowssnapshots(snapshot_id, flag_version_map, content_hash)current_pointer(env, region) -> snapshot_id
Snapshot IDs only increase. A rollback is a new snapshot whose content equals an older one, never a decrement. Devices ignore any manifest with an ID lower than what they hold, so a stale CDN node cannot push them backward.
Event
{event_id, device_id, type, item_id, row_id, client_ts, snapshot_id,
exposures:[{flag, v, variant}]}
exposures lists only flags in an active experiment (treatment and control). snapshot_id alone is insufficient because many experiments share a snapshot and the per-device variant is what matters.
4. Architecture
Admin to device
- The console validates (schema, lint, blast-radius check), then writes the flag version and snapshot in one transaction.
- A publisher renders the snapshot to object storage at a content-addressed URL, flips
current_pointer, and regenerates the manifest. - The CDN serves the manifest with a 5s TTL and request collapsing at an origin shield, so origin sees roughly one request per PoP per 5s.
- Devices poll every 15s with jitter. On a new ID they fetch the immutable snapshot, apply it atomically, and keep the last-known-good copy on disk.
- Fast path: devices holding a persistent connection (WebSocket/SSE, about 50K per gateway node, so roughly 200 nodes) get a tiny "invalidate, latest=N" message. Polling stays the correctness backstop.
Worst-case rollback latency without push: 5s manifest TTL + 15s poll + ~3s fetch/apply ≈ 23s, inside the 30s budget. Push makes the typical case much faster.
Device to CTR
- Stateless regional collectors validate events, stamp
server_ts, and write to Kafka (about 500 partitions keyed bydevice_id, RF=3, 3-day retention), mirrored to a central cluster. - A Flink job using event time:
- Dedupe by
event_idwith keyed state and a ~10-minute TTL to absorb client retries. - Explode each event into one record per exposure.
- Aggregate in two stages to avoid hot keys, since control and 100% variants dominate traffic. Stage 1 pre-aggregates locally every few seconds. Stage 2 keys by
(flag, version, variant, region, device_type)in 1-minute tumbling windows, producing impressions, clicks and distinct devices (HLL).
- Dedupe by
- Sinks: Pinot or Druid for sub-second dashboards, and raw events to Iceberg on S3 (hourly partitions, 30-day retention) for reprocessing.
- Exactly-once is achieved with about 30s checkpoints and idempotent upserts keyed by
(window, dims).
5. Trade-offs
Thundering herd
- Immutable snapshots give near-total cache hits; only the small manifest is short-lived, and collapsing protects origin.
- Jitter both regular polls and post-invalidation fetches (0-5s) so 10M fetches spread over a window.
- Rate-limit push fan-out per gateway.
- Devices back off exponentially on 5xx and keep serving the cached config. A config outage must never become an app outage.
- Delta snapshots reduce bytes if snapshots grow.
Freshness vs. correctness in telemetry
- Dashboards show provisional early window values that are revised as late data arrives.
- Automated rollback or ramp decisions use only windows closed past the watermark.
- Event-time windows add about 1-2 minutes of delay but give deterministic, replayable results.
- Hourly batch jobs over Iceberg reconcile the streaming numbers and act as the source of truth.
Statistical care: compare treatment to control with a guardrail on CTR drop, require a minimum sample size, and watch for sample-ratio mismatch, which signals assignment or logging bugs.
6. Failure modes and common mistakes
- Per-device server-side evaluation: destroys cacheability and puts a database in the hot path.
- Rollback as a lower version number: stale caches can reapply the bad config. Use a new, higher snapshot.
- Logging only
snapshot_id: you cannot attribute clicks to a specific variant. - Ignoring duplicates: client retries inflate counts without dedupe.
- Hot keys in aggregation: one huge key stalls a Flink task without two-stage aggregation.
- Polling only: simple, but with long intervals it misses the 30s rollback target.
- Collector or config outage: collectors buffer to Kafka and devices buffer events locally; both degrade gracefully.
- Monitoring: alert on manifest propagation lag (fraction of devices on the latest snapshot over time), Kafka consumer lag, and watermark delay.