← Back to System Design, page 4

system-design-0080 · Easy fresher

Design a feature flag service that lets teams turn features on for a percentage of users or specific groups, with SDKs that evaluate flags locally in microseconds.

Store flag definitions (targeting rules, percentages, allow and deny lists) in a database edited through an admin UI. SDKs inside each service download the full rule set at start-up, keep it in memory, receive changes over a streaming connection, and evaluate flags locally with a stable hash of flag key and user ID, so a user always lands in the same bucket. No network call happens per evaluation; the rule set for 2,000 flags is only about 2 MB.

Full answer

Requirements

Functional:

  • Create flags with rules: on or off, percentage rollout, rules by attribute (country, plan), allow and deny lists.
  • Change a flag and have it take effect in all services within seconds.
  • Audit log of who changed what, and a quick kill switch.

Non-functional:

  • Evaluation adds microseconds, not network round trips.
  • If the flag service is down, applications keep running with the last known rules.
  • A user sees the same variant consistently.

Capacity estimates

Assumptions: 2,000 flags at about 1 KB each, 50,000 application instances running the SDK, 1M flag evaluations per second across all services.

  • Rule set: 2,000 x 1 KB = 2 MB, held in memory by every SDK.
  • Streaming connections: 50,000, one per instance, spread across a few relay servers.
  • Evaluations: 1M per second, but all local, so the service sees zero evaluation traffic.

API

Admin: PUT /v1/flags/new-quiz-ui {"default_percent": 10, "rules": [{"attr": "country", "in": ["IN"], "percent": 50}], "allow": ["u_qa"], "deny": []} SDK: GET /v1/sdk/rules -> full rule set with version GET /v1/sdk/stream (Server-Sent Events: {"version": 812, "changed": {...}}) In code: flags.is_enabled("new-quiz-ui", user)

Data model

  • flags: key, description, owner team, rules (JSON), version, updated_by, updated_at.
  • flag_audit: flag key, old rules, new rules, who, when.
  • SDK cache: version plus the full rule set, also written to local disk so a restart without the service still works.

High-level design

mermaid
flowchart LR
  ADM[Admin UI] --> FS[Flag service]
  FS --> DB[(Flags and audit DB)]
  FS --> PUB[(Change stream)]
  PUB --> RL[Stream relays]
  RL -- "SSE" --> SDK1[SDK in service A]
  RL -- "SSE" --> SDK2[SDK in service B]
  SDK1 -. "start-up fetch" .-> CDN[CDN copy of rule set]

Evaluation

python
import hashlib


def bucket(flag_key, user_id):
    """Stable bucket 0..9999 for a user and flag: same answer on every server."""
    digest = hashlib.sha256(f"{flag_key}:{user_id}".encode()).digest()
    return int.from_bytes(digest[:8], "big") % 10_000


def is_enabled(flag, user):
    if user["id"] in flag.get("deny", ()):
        return False
    if user["id"] in flag.get("allow", ()):
        return True
    for rule in flag.get("rules", ()):                  # first matching rule wins
        if user.get(rule["attr"]) in rule["in"]:
            return bucket(flag["key"], user["id"]) < rule["percent"] * 100
    return bucket(flag["key"], user["id"]) < flag["default_percent"] * 100


if __name__ == "__main__":
    flag = {"key": "new-quiz-ui", "default_percent": 10, "allow": {"u_qa"},
            "rules": [{"attr": "country", "in": {"IN"}, "percent": 50}]}
    users = [{"id": f"u{i}", "country": "IN" if i % 2 else "US"} for i in range(20_000)]
    on_in = sum(is_enabled(flag, u) for u in users if u["country"] == "IN") / 10_000
    on_us = sum(is_enabled(flag, u) for u in users if u["country"] == "US") / 10_000
    assert 0.48 < on_in < 0.52 and 0.08 < on_us < 0.12
    assert is_enabled(flag, {"id": "u_qa", "country": "US"})
    assert all(is_enabled(flag, u) == is_enabled(flag, u) for u in users[:100])   # stable
    print(f"ok: IN {on_in:.3f}, US {on_us:.3f}")

Save as rollout.py and run python3 rollout.py (Python 3.13.5).

Hashing flag_key:user_id keeps each user in the same bucket across servers and restarts; including the flag key means a user who is in the first 10% of one flag is not automatically in the first 10% of every flag. Raising a rollout from 10% to 20% keeps the original 10% enabled, because their buckets are still below the new threshold.

Bottlenecks and trade-offs

  • Local evaluation versus server-side evaluation. Local is fast and resilient but ships all rules to every service; for browser and mobile clients, evaluate on the server and send only the results, so rules and user lists are not exposed.
  • Propagation. Streaming gives updates in seconds; polling every 30 seconds is simpler and also acceptable for many teams.
  • Stale rules during an outage are safe if defaults are safe; every flag needs a sensible fallback value in code.
  • Flag debt. Old flags make code hard to follow; track owners and expiry dates and alert on flags unchanged for months.
  • Experiments reuse the same bucketing but need exposure logging, which is sent asynchronously and sampled if needed.

By level

Fresher: Explain that services download flag rules and check them in memory, and that a hash keeps each user in the same group. A fresher should describe a percentage rollout.

Mid: Design storage, streaming updates, the SDK cache and stable bucketing, and show how rollouts grow without flipping users. Handle outages with defaults.

Senior: Discuss server-side evaluation for clients, experiments and exposure logging, propagation guarantees, flag debt and audit. Expect clear reasoning about failure modes.

Key points

  • SDKs hold the full rule set in memory and evaluate locally
  • Stable hash of flag key and user ID for percentage rollouts
  • Streaming updates with a disk cache for restarts
  • Safe defaults in code for outages
  • Server-side evaluation for browser and mobile clients

Common mistakes

  • Calling the flag service over the network on every evaluation
  • Using random numbers per request, so users flip between variants
  • Hashing only the user ID, so the same users get every early rollout
  • Shipping full rules with user lists to browsers

Follow-ups

  • How would you run an A/B test with this service?
  • How do you make a kill switch take effect within one second?
  • How would you clean up old flags?

Tips

  • Explain why evaluation is local
  • Show the hash bucketing idea
  • Mention fallback values for outages

Evaluation rubric

  • Correct local evaluation architecture
  • Stable bucketing explained
  • Propagation and outage behaviour
  • Client-side security and flag hygiene