"Design a feature flag system" has a trap built into it. The natural first drawing is a service that answers "is flag X on for user Y?" and every application calls it. That design works in a demo and takes down your company the first time the flag service has a bad day, because now every request of every product waits on it.
The interviewer wants to see you resolve a tension. A flag must change quickly (a kill switch has to take effect in seconds), and flag evaluation must be free and always available (it sits on the hot path of every request, in every service). You can only have both if you separate distributing rules from evaluating them.
The lesson on feature toggles and progressive delivery covers what flags are for and how to manage their lifecycle. This page designs the platform that serves them.
Clarify the requirements
Functional requirements:
- Create a flag with a type (boolean, string, number or JSON) and a default value.
- Targeting rules per environment: turn it on for specific users, for a segment (country, plan), or for a percentage of users.
- SDKs for backend services and for web and mobile clients return a flag's value for a given user context.
- Changes take effect without a deploy, and a flag can be killed instantly.
- An audit log of who changed what and when, with the ability to roll back.
- Record which users were exposed to which variation, so experiments can be analyzed.
Out of scope, said aloud: the experimentation statistics engine, an approval workflow beyond a simple permission check, and billing.
Non-functional requirements:
- Evaluation adds almost no latency and never fails. It is a function call, not a network call. If the flag platform is down, applications keep running with the last known rules.
- Changes propagate fast: within about 5 seconds to servers and 30 seconds to clients.
- Consistent. A given user gets the same value on every request and in every service, and a gradual rollout never flip-flops them.
- Safe defaults. If a flag cannot be read at all, the SDK returns the default compiled into the code.
- Privacy. User attributes used for targeting should not need to leave the application.
Estimate the scale
Assume 20 million daily active users, 5 sessions each a day, and a typical session evaluating about 200 flags (many checks per page or request) and exposing the user to about 10 distinct flags.
Rule fetches: every session loads the flag configuration once: 20M × 5 = 100 million a day ÷ 86,400 s ≈ 1,157 per second, and about 3,500 per second at 3× peak. Only these cross the network.
Evaluations: 100M sessions × 200 = 20 billion a day, or about 231,000 per second. If each were a network call, the platform would need to serve that, and every outage would be an application outage. Evaluated locally, they cost nothing.
Rule size: 5,000 flags in an environment × about 2 KB of rules = 10 MB for a server-side ruleset. A client needs only the values for one user: 200 flags × 50 B = 10 KB.
Exposure events: log each (user, flag) once per session: 20M × 5 sessions × 10 flags = 1 billion a day ÷ 86,400 s ≈ 11,600 per second. At about 100 bytes each, 36.5 TB a year (20M × 50 events × 100 B × 365).
Changes: about 2,000 flag edits a day is 0.02 a second. Writes are almost nothing.
"Read volume is 231,000 evaluations a second, so evaluation must be local. What crosses the network is small: 3,500 config fetches a second, one change every 40 seconds. The biggest data flow is exposure events, 11,600 a second, and that is analytics ingestion, not flag serving."
The capacity estimator reproduces the event volume and the per-session fetch rate.
API and data model
POST /v1/flags { key, type, defaultValue, ... }
PUT /v1/flags/{key}/environments/{env} { enabled, rules[], fallthrough, version }
GET /v1/environments/{env}/ruleset -> full ruleset, ETag: "v1842"
GET /v1/stream?env={env} -> server-sent events: "ruleset v1843"
POST /v1/events { userKey, flagKey, variation, ts }[]flag (flag_key PK, type, owner, created_at, archived)
flag_env (flag_key, env) -> enabled, rules_json, fallthrough, version
ruleset_snapshot (env, version) -> full ruleset blob // immutable, in object storage
audit_log (flag_key, ts) -> actor, before, afterTwo non-obvious choices. First, a rule edit does not update a snapshot in place: it creates a new immutable snapshot with the next version number, which is cheap to cache and trivial to roll back. Second, rules contain a flag's version, so an out-of-order update can never overwrite a newer one.
High-level design
We simulate the distribution path: SDK requests hit a CDN, the CDN falls back to the flag service, and the service reads the rule store.
- The CDN serves the current ruleset snapshot for an environment, so most fetches never reach the origin.
- The flag service reads the rule store's replicas and publishes a new version when an editor saves.
Describe this diagram
Components
- app SDKs (Client)
- rules cdn (Content delivery network)
- flag service (Service)
- rule store (PostgreSQL)
Connections
- app SDKs sends to rules cdn
- rules cdn sends to flag service
- flag service sends to rule store
Run it, then try shortening the CDN's cache lifetime, or add load, and see how much traffic reaches the origin. The CDN is the reason a very read-heavy, very small-write system stays cheap.
The write path: an editor saves a flag. The service validates the rules, writes the new version to Postgres in one transaction together with an audit row, builds a snapshot and publishes "environment X is now at version N" to a stream.
The read path: an SDK fetches the snapshot (GET /ruleset, conditional on its ETag). Evaluation then runs entirely inside the SDK against the in-memory rules.
The interesting problem: evaluate locally, distribute globally
Where a flag is evaluated decides your availability, latency and privacy. Three ways:
Approach A: evaluate on the server, per call
The application sends the user context to the flag service and gets back a value.
Good: rules stay secret, and the service can change logic freely.
Bad: 231,000 network calls a second, with added latency on every request. Worse, the flag service sits on the critical path of everything: its outage is everyone's outage. User attributes also have to be sent out for every check.
Approach B: servers download the ruleset and evaluate locally
Each backend SDK fetches the full ruleset (10 MB) once, keeps it in memory and evaluates with a local rules engine.
Good: evaluation takes microseconds and works when the platform is down. Context never leaves the process.
Bad: you must keep every SDK's copy fresh, and you cannot send a 10 MB ruleset, with other users' targeting rules, to a web browser or phone.
Approach C: local evaluation with CDN-distributed snapshots and push invalidation
Combine the strengths:
- Backend SDKs use B. They fetch the immutable snapshot from the CDN, then hold a streaming connection (server-sent events) that carries only a tiny message: "version 1843 is available". On that message the SDK fetches the new snapshot, which is a CDN cache hit. A slow poll every 30 to 60 seconds is the fallback if the stream drops.
- Client SDKs call a thin evaluation endpoint at the edge that evaluates for one user and returns the 10 KB of values, never the rules. Cache that response briefly in the app.
- The CDN serves snapshots. Because they are immutable and versioned, they can be cached for a long time, and only the small "current version" pointer needs a short lifetime.
Diagram, as text
- Editor saves leads to Flag service
- Flag service leads to Rule store
- Flag service leads to New snapshot v1843
- New snapshot v1843 leads to CDN
- Flag service leads to Backend SDKs (stream: v1843)
- Backend SDKs leads to CDN (fetch v1843)
- Backend SDKs leads to Local evaluation
- Web app leads to Edge evaluator (user context)
- Edge evaluator leads to CDN
This is the answer to aim for. A change reaches servers in a few seconds because the push is a few bytes and the fetch is a cache hit. The platform being down only means no new changes, never a broken application.
The second decision: consistent percentage rollouts
"Turn it on for 10% of users" must mean the same 10% on every request, in every service, and growing the rollout from 10% to 25% must keep the original 10% on. A random coin flip per request fails both.
The standard answer is deterministic bucketing: compute bucket = hash(flagKey + ":" + userKey) mod 10,000, and compare it with the rollout (a 10% rollout includes buckets 0 to 999). Properties that follow:
- Stable: the same user always lands in the same bucket, in any language or service, as long as the hash function and salt are specified exactly.
- Monotonic: raising the percentage only adds buckets, so no one who had the feature loses it.
- Independent across flags: including the flag key in the hash means a user at the bottom of one flag's range is not at the bottom of every flag's range. Without it, the same 5% of users would get every experiment first.
- No state: nothing is stored per user.
Two cautions. Pick the bucketing key deliberately: user id for a logged-in feature, device id for logged-out pages, and an account id when everyone in a company should see the same thing. And for mutually exclusive experiments, hash into a shared layer first, then assign each experiment a range of that layer.
Bottlenecks and failures
The kill switch. The most important flag type is the emergency off. Time it as a requirement: flip, push, SDK refetch, effective in under 5 seconds for servers. Test it regularly in production with a harmless flag, because an untested kill switch is a hope.
Flag platform outage. Applications keep running on cached rules. The editor UI is down, so changes are blocked, and the on-call needs a second route to disable something, such as a break-glass override file the SDK reads.
A bad rule. A typo can turn a feature on for everyone. Validate rules on save, preview the effect on sample users, store every change as a version and offer one-click rollback to the previous snapshot. The audit log answers "who changed it".
Event storm. At 11,600 exposure events a second, SDKs must batch and sample: buffer in memory, flush every few seconds, drop on overflow. Never block a request on sending an event. The ingestion path follows the message queue pattern, so a slow analytics store does not push back on applications.
Stale clients. A mobile app open for three days may hold old rules. Send the ETag on every refresh and refetch on app foreground, and design flags so that an old value is acceptable for a short time.
Flag debt. The system fills with dead flags. Record an owner and expected removal date, and report flags that evaluate to the same value for 30 days so they can be deleted.
Trade-offs to name aloud
- Local evaluation over a central decision API: availability and speed, in return for shipping rules to servers and trusting the SDKs.
- Push plus poll: fast changes with a safe fallback, at the cost of holding open connections.
- Immutable snapshots: easy caching and rollback, but each edit writes a whole new document.
- Evaluated values for clients, not rules: rules stay private, but the edge evaluator becomes a service to run.
- Sampling exposure events: lower cost against less exact experiment counts.
What interviewers listen for
- A working answer: flags in a database, an SDK that fetches the config and evaluates it, a cache in front.
- A strong answer: argues for local evaluation with numbers (231,000 evaluations a second against 3,500 fetches), pushes changes, uses a hash for stable percentage rollouts and returns defaults when the platform is unreachable.
- A standout answer: separates server and client SDK models for secrecy, includes the flag key in the bucket hash, treats the kill switch as a latency requirement, versions snapshots for rollback and plans for flag cleanup.
Check your understanding
Common mistakes
A central "is it on?" API on the hot path. It is the first design most people draw and the one with the worst failure mode. Evaluate locally.
Sending the whole ruleset to browsers. It leaks targeting rules, internal segments and unreleased feature names. Evaluate on the edge and send values only.
Random assignment per request. Users see features flicker between page loads, and an experiment's results are meaningless.
Blocking on analytics. Sending an exposure event inline turns an analytics outage into slow requests. Batch, sample and drop.
No default and no last-known-good. An SDK that throws when the platform is unreachable makes the flag system a dependency of startup.
No lifecycle. Without owners and removal dates, the codebase fills with permanently-on flags and untested branches.
Practice
A new checkout flow ships behind a flag at 5%. Error rates rise. Describe exactly what happens from the moment someone clicks the kill switch until all traffic is safe, and what could make it slower than expected.
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Follow the change through the write, the push, the fetch and the SDK. Look for the slowest hop.
Show a strong answer
The save. The editor writes a new flag version and an audit row in one transaction, and a new snapshot is built. This takes tens of milliseconds.
The push. The service publishes the new version on the stream. Backend SDKs receive a message of a few bytes within about a second.
The fetch. Each SDK requests the new snapshot. The first request fills the CDN cache and the rest hit it, so a 10 MB file is not fetched thousands of times from the origin. Total time to apply: a couple of seconds.
What slows it down. A dropped stream makes an SDK fall back to polling, which may take up to a minute. Client apps refresh on a longer interval. Long-lived requests already in progress finish on the old value. Mitigate by monitoring SDK versions in use (each SDK reports the ruleset version it holds) and alert if more than a few percent lag beyond 10 seconds.
The pattern worth keeping: measure the whole path to "effective", not just the write. A kill switch is only as fast as its slowest consumer.
Product wants two experiments, a new homepage and a new pricing page, to run on the same users without contaminating each other. How should assignment work?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Think about whether the two experiments should be independent or exclusive, and what each choice needs from the hash.
Show a strong answer
Decide the relationship. If effects might interact (a homepage change alters who reaches pricing), make them mutually exclusive: a user is in at most one. If they are independent, let them overlap.
For independence, include each experiment's key in its hash. Assignments are then uncorrelated, so the pricing test sees an even mix of homepage variants and the effects average out.
For exclusivity, define a shared layer. Hash the user into 10,000 buckets using the layer's key, then give the homepage experiment buckets 0 to 4,999 and pricing 5,000 to 9,999. Each experiment uses half the traffic, and no user is in both.
Log both assignments in the exposure event, so analysis can check the overlap and correct for it.
The pattern worth keeping: a hash that includes the salt you choose gives you either independence or exclusion. Pick the salt on purpose.
Key takeaways
- Separate distributing rules from evaluating them. Evaluation is local; only small updates cross the network.
- Do the math on evaluations. 231,000 a second as network calls would be a self-inflicted outage.
- Immutable, versioned snapshots on a CDN make distribution and rollback simple.
- Stable percentage rollouts use a hash of flag key and user key, and only ever add buckets.
- Fail static: keep the last good rules, and carry a default in code.
- Time the kill switch end to end, and keep exposure events off the request path.
Further reading
- Pete Hodgson, "Feature Toggles (aka Feature Flags)" (martinfowler.com, 2017): the categories of toggle and how to manage them.
- OpenFeature project documentation (CNCF), the specification of a vendor-neutral flag evaluation API: how SDK interfaces and evaluation context are standardized.
- WHATWG, HTML Living Standard, "Server-sent events": the streaming mechanism behind a push channel of tiny messages.