Service Discovery and Configuration Management Questions
Letting services find and configure each other at runtime: service registries, client-side versus server-side discovery, DNS-based discovery, dynamic configuration, feature flags, and secrets distribution. Covers how services stay wired together as instances come and go, how config changes propagate safely, and how to monitor and diagnose the outages that stale endpoints or bad config pushes cause. The connective plumbing of a microservices deployment.
Design a feature-flag service that supports per-user and per-segment targeting, deterministic percentage rollouts, and a global kill-switch, serving roughly a million evaluations per second at low latency across multiple regions. Cover the runtime evaluation model, how a flag change propagates to evaluators, storage and caching, and how you'd keep a full audit trail and roll back a bad flag fast.
Sample Answer
Direct answer
The key decision is to evaluate flags inside the application process, not over the network. Each service embeds an SDK (software development kit, the client library) that holds the full rule set in memory and evaluates a flag with a hash and a few comparisons, so a million evaluations per second is a million local function calls with no network hop and no central bottleneck. A central control plane stores flags as versioned, immutable documents with an append-only change log, and pushes each new version to regional relays that stream it to every SDK within seconds. Percentage rollouts use a deterministic hash of flag and user, so a user's answer never flickers. Rollback is "publish the previous version", and the kill switch is a rule evaluated before all others.
Terms first
- Feature flag: a named switch whose value is decided at runtime per request, so behaviour changes without a deploy.
- Targeting: rules like "users in segment
beta-testersgeton", "country = DE getsoff". - Segment: a reusable named group of users, defined either by a rule (
plan = enterprise) or an explicit list of IDs. - Deterministic percentage rollout: "25% of users" chosen by hashing, so the same user always lands in the same group without storing anything.
- Kill switch: a way to force a flag (or all flags of a feature) to its safe value instantly.
- SSE (server-sent events): a long-lived HTTP response over which a server pushes messages to a client; simpler than WebSockets for one-way updates.
- Control plane: the central service that owns the source of truth for every flag and pushes changes out; it never evaluates a flag for live traffic itself, it only distributes the rules.
- Relay: a regional fleet of servers between the control plane and the SDKs. It holds a cached copy of the current rules and streams changes to every SDK connected to it, so the control plane itself is never in the request-serving path.
- Exposure event: a small record ("user U-482 saw flag new-checkout as on") sampled and logged when a flag is evaluated, used afterwards to measure the flag's effect. It plays no part in serving the flag.
Requirements I am designing to
- 1,000,000 evaluations per second in total, low latency (target: microseconds per evaluation, so it can sit on every request path).
- Several regions; a region losing contact with the control plane must keep evaluating correctly on last-known rules.
- Flag change visible everywhere in seconds; rollback in seconds; every change attributable and reversible.
Architecture
flowchart LR
UI[Admin UI and API] --> CP[Control plane: validation, approvals]
CP --> DB[(Primary DB: flag versions and change log)]
CP --> BUS[Change stream]
BUS --> R1[Region A relay fleet]
BUS --> R2[Region B relay fleet]
CP --> SNAP[Versioned snapshots in object storage]
R1 -->|SSE stream| S1[Service SDKs, in-process eval]
R2 -->|SSE stream| S2[Service SDKs, in-process eval]
SNAP -.->|bootstrap and fallback| S1
SNAP -.->|bootstrap and fallback| S2
S1 --> EXP[Sampled exposure events]
Runtime evaluation model
Each flag is a small document: variations (on/off, or variants like A/B), an ordered rule list, a default, and a version number. The SDK evaluates in a fixed order:
- Kill switch / flag off → return the off variation. Checked first so nothing else can override it.
- Individual targets (explicit user IDs).
- Segment rules in order ("in segment
beta-testers" →on). - Percentage rollout on the fallthrough (reached only if none of the rules above matched): hash bucket below the threshold →
on. - Default.
Traced example: user user-000004 requests the new-checkout flag at a live 25% rollout. Step 1, the kill switch: not tripped. Step 2, individual targets: user-000004 is not on the explicit list. Step 3, segments: not a member of any targeted segment. Step 4, percentage rollout: bucket("new-checkout", "s1", "user-000004") comes out to 1,531, and 1,531 is below the 25% threshold of 2,500, so the flag resolves to on right here. Step 5, the default, is never reached for this user.
A global kill switch is a special entry in the rule set ("emergency: all flags tagged checkout return their off variation") that the SDK checks before any flag, so one change disables a whole feature area.
Browsers and mobile apps should not receive the full rule set (it exposes targeting logic and user lists), so they call a thin server-side evaluation endpoint on the relay that returns only their evaluated values.
Deterministic percentage rollouts
Hash flag_key : salt : user_id into 10,000 buckets (the salt is an arbitrary fixed string with no meaning of its own beyond changing the hash's output); the user is in a 25% rollout when their bucket is below 2,500. Including the flag key means different flags pick independent user groups; the salt lets you deliberately reshuffle a flag.
import hashlib
def bucket(flag_key, salt, user_id):
"""Map (flag, user) to a stable bucket in [0, 10000)."""
h = hashlib.sha256(f"{flag_key}:{salt}:{user_id}".encode()).digest()
return int.from_bytes(h[:8], "big") % 10_000
def in_rollout(flag_key, salt, user_id, percent):
return bucket(flag_key, salt, user_id) < percent * 100 # 25% -> buckets 0..2499
users = [f"user-{i}" for i in range(100_000)]
at10 = {u for u in users if in_rollout("new-checkout", "s1", u, 10)}
at25 = {u for u in users if in_rollout("new-checkout", "s1", u, 25)}
other = {u for u in users if in_rollout("new-search", "s1", u, 10)}
print("10% cohort:", len(at10), " 25% cohort:", len(at25))
print("everyone in 10% still in 25%:", at10 <= at25)
print("overlap with a different flag's 10%:", len(at10 & other))
Output (Python 3, run as shown):
10% cohort: 9997 25% cohort: 25083
everyone in 10% still in 25%: True
overlap with a different flag's 10%: 986
Raising a rollout from 10% to 25% only adds users (nobody who had the feature loses it), and a second flag's 10% overlaps this one's at about 10% of 10% (986 of 100,000), which is what independent selection looks like. Every SDK in every language must implement the identical hash, so the algorithm is part of the service's contract and is covered by cross-language test vectors (the same fixed set of (flag, salt, user) inputs and their expected bucket numbers, run against every language's SDK, so a Python evaluation and a Java evaluation of the same user never disagree).
How a change propagates
- Admin saves a change. The control plane validates it (schema, no dangling segment references, approval if the flag is tagged production-critical), writes flag version N+1 and a change-log entry in one transaction, then publishes to the change stream.
- It also writes a full versioned snapshot to object storage (fronted by a CDN, content delivery network), used for SDK bootstrap and as a fallback.
- Regional relays consume the stream and push the delta (only what changed since the SDK's last known version, not the whole rule set) to every connected SDK over SSE. Each message carries the version, and the SDK ignores anything older than what it has, so reordering or replays are harmless.
- If the stream drops, the SDK keeps evaluating on its current rules, reconnects with backoff, and falls back to polling the snapshot. It never goes blank: an SDK that has not loaded rules yet returns the code-level default for every flag, which must be the safe value.
Worked example: capacity arithmetic
Inputs (assumptions to state in the interview): 20,000 application instances running the SDK, 2,000 flags, about 2 KiB per flag document, exposure events sampled at 1%.
evals_per_s = 1_000_000
sdk_instances = 20_000 # app processes running the evaluator (assumption)
flags, bytes_per_flag = 2_000, 2_048
ruleset = flags * bytes_per_flag
print(f"per-instance eval rate: {evals_per_s / sdk_instances:.0f}/s")
print(f"full ruleset: {ruleset / 2**20:.1f} MiB held in memory per instance")
print(f"one flag change fanned out to all instances: {sdk_instances * bytes_per_flag / 2**20:.1f} MiB")
print(f"full resync of every instance (e.g. after a relay restart): {sdk_instances * ruleset / 2**30:.1f} GiB")
exposure_sample = 0.01
print(f"exposure events at 1% sampling: {evals_per_s * exposure_sample:,.0f}/s")
changed_since_reconnect = 5 # flags changed while an SDK was briefly disconnected (assumption)
delta_bytes = changed_since_reconnect * bytes_per_flag
print(f"delta resume after missing {changed_since_reconnect} changes: {delta_bytes / 2**10:.1f} KiB per instance, "
f"vs the {ruleset / 2**20:.1f} MiB full ruleset ({ruleset / delta_bytes:.0f}x less)")
print(f"same delta, fleet-wide: {sdk_instances * delta_bytes / 2**20:.1f} MiB vs the {sdk_instances * ruleset / 2**30:.1f} GiB full resync")
Output (Python 3, run as shown):
per-instance eval rate: 50/s
full ruleset: 3.9 MiB held in memory per instance
one flag change fanned out to all instances: 39.1 MiB
full resync of every instance (e.g. after a relay restart): 76.3 GiB
exposure events at 1% sampling: 10,000/s
delta resume after missing 5 changes: 10.0 KiB per instance, vs the 3.9 MiB full ruleset (400x less)
same delta, fleet-wide: 195.3 MiB vs the 76.3 GiB full resync
What this tells you: evaluation load is trivial (50 per second per instance), memory is small (about 4 MiB), and a normal change is cheap (about 39 MiB of fan-out). The dangerous number is the 76.3 GiB full resync: if every SDK reconnects at once and downloads everything from the relays, that is a thundering herd (a mass of clients all retrying the same operation at the same moment, turning ordinary load into a spike large enough to overwhelm whatever they are hitting). Mitigations: SDKs reconnect with jittered backoff (waiting a random, growing interval before retrying, so reconnects do not all land on the same instant), resume with "I have version N, send deltas" (5 changed flags costs 10.0 KiB per instance against the 3.9 MiB full ruleset, about 400x less, and 195.3 MiB fleet-wide against the 76.3 GiB full resync), and bootstrap full snapshots from the CDN rather than the relays.
Storage and caching
- Source of truth: one relational database in a primary region (flag documents keyed by
(flag_key, version), never updated in place). Writes are rare (humans making changes), so single-region writes are fine; reads never touch it on the evaluation path. - Regional caches: relays hold the current rule set in memory, rebuilt from the latest snapshot on start. The SDK's in-memory copy is the cache that serves all traffic.
- Multi-region: if the primary region is down, evaluation continues everywhere on last-known rules; only editing is unavailable. That is the right trade: editing flags during a regional outage is rare and can use a documented break-glass path in a standby region.
Audit trail and fast rollback
- The change log is append-only: actor, time, flag, old and new version, diff, reason or ticket link, approvals. Nobody, including admins, can edit or delete an entry; it is streamed to the company's audit store as well.
- Rollback = publish the previous version as N+2. Because versions are immutable, "restore version 41" is one click and propagates at the same speed as any change (seconds), and the rollback itself appears in the audit log.
- Kill switch for emergencies needs no approval and flips the flag to off; everything else can require review.
Trade-offs and pitfalls
- Local evaluation vs central evaluation. Central evaluation (every check is an RPC, remote procedure call) makes the flag service a dependency of every request: 1M requests per second of load, a network hop on every call, and an outage takes down every product. Local evaluation costs rule distribution and a multi-language SDK effort. At this scale local wins; with only a few services and low volume, a central endpoint would be simpler.
- Large list segments (millions of user IDs) do not fit in every SDK. Keep those as server-side segment lookups or push them only to services that need them.
- Stale flags accumulate as debt: track last-evaluated time from exposure events and nag owners of flags that have been 100% on for 30 days.
- Consistency across a request: two services may briefly see different versions during a push. For flows where that matters, evaluate once at the edge and pass the result downstream in a header.
Explain the difference between general configuration values and feature flags. When should a capability be implemented as a feature flag versus a normal configuration parameter? Discuss lifecycle considerations: rollout, rollback, targeting, observability for flags, and operational responsibilities for stale flags.
Sample Answer
Direct answer
A configuration value tells the system how to run (a timeout, a pool size, a database hostname) and is usually the same for every user in an environment. A feature flag (also called a feature toggle) decides whether a piece of behaviour is active, can differ per user or customer, is changed at runtime without a deploy, and is usually meant to be temporary. Use a flag when you need to separate deploying code from releasing it to users: gradual rollout, instant switch-off, targeting a subset, or an experiment. Use plain configuration for operational tuning that applies to everyone. Every flag needs an owner and a removal date, because a flag left in place becomes permanent hidden complexity.
How to tell them apart
| Question | Configuration | Feature flag |
|---|---|---|
| What does it control? | How something runs: db_pool_size = 20, payment_timeout_ms = 3000 | Whether a capability is on: new_checkout_flow |
| Who sees which value? | Everyone in an environment | Can vary per user, account, region, percentage |
| How often does it change? | Rarely, alongside operational changes | Often during a rollout, then removed |
| Who changes it? | Engineers or SREs (site reliability engineers), through a reviewed change | Engineers, product managers or release managers, through a flag service's controls |
| Expected lifetime | As long as the service | Days to weeks for a release flag; long-lived only for specific kinds (below) |
| Change mechanism | Deploy, or config push with validation | Runtime toggle, evaluated per request |
A quick test: if the value would ever be different for two users at the same moment, or if you want to switch it off in seconds without a deploy because it is risky, it is a flag. If it is a tuning knob with one right answer per environment, it is configuration.
Kinds of flags (they have different lifecycles)
- Release flags: hide unfinished or newly shipped work; removed once fully rolled out. Short-lived.
- Experiment flags: split users into variants for an A/B test (comparing two versions on randomly assigned users); removed when the experiment concludes.
- Operational flags ("kill switches"): turn off an expensive or risky feature under load, such as disabling recommendations during a traffic spike. Can be long-lived, and are the closest to configuration.
- Permission or entitlement flags: enable a feature for paying plans or beta customers. Long-lived; many teams eventually move these into the product's own entitlement model instead of the flag system.
Lifecycle
Rollout. Ship the code with the flag off. Turn it on for internal users, then a small percentage (1%, 5%, 25%, 50%, 100%), watching metrics at each step. The percentage must be sticky: the same user must get the same answer on every request, or they see the old and new checkout alternately.
Rollback. Turning the flag off is the rollback, and it takes seconds instead of a redeploy. This only works if the old code path still works: do not delete it until the flag is at 100% and stable.
Targeting. Rules such as "on for accounts in the beta list", "on for users in Canada", "on for 10% of everyone else". Keep rules simple and evaluate them in the application (the SDK, the flag vendor's client library, downloads the rules and evaluates them locally), so a flag-service outage does not block requests. Always have a coded default for when the flag service is unreachable.
Observability. Record which variant each request got (in logs, traces, meaning the recorded path a single request took through the system and how long each step took, and metrics), so you can compare error rate and latency between flag-on and flag-off traffic. Also track evaluation counts per flag: a flag evaluated zero times for a month is dead code (code that still exists but no execution path reaches it any more).
Stale flags and operational responsibility. Each flag gets an owner and an expiry date at creation. After full rollout, a ticket removes the flag and the dead code path. Stale flags are dangerous: code has branches nobody tests, and a forgotten flag can be flipped years later by mistake, reviving old behaviour.
Worked example: why percentage rollouts must be deterministic
A flag system typically hashes the flag name plus the user ID into a bucket from 0 to 9,999 and turns the feature on when the bucket is below the rollout percentage. Hashing means running the input through a function that always produces the same fixed, effectively-random-looking output for the same input, and a very different output for almost any different input, with nothing stored in between. Because hashing the same flag name and user ID always produces the same bucket, a given user's answer never flips between two requests on its own, even though nothing about that user was ever saved anywhere.
In plain terms, the program below does two things: bucket() turns a flag name plus a user ID into a number from 0 to 9,999, and is_enabled() turns a rollout percentage like 25% into a cutoff of 2,500 and switches the feature on for a user whose bucket falls below that cutoff. This small program checks the two properties that matter:
import hashlib
def bucket(flag_key, user_id):
"""Stable number 0-9999 for this user and this flag."""
h = hashlib.sha256(f"{flag_key}:{user_id}".encode()).digest()
return int.from_bytes(h[:8], "big") % 10000
def is_enabled(flag_key, user_id, percent):
return bucket(flag_key, user_id) < percent * 100
users = [f"user-{i}" for i in range(100_000)]
on_10 = {u for u in users if is_enabled("new-checkout", u, 10)}
on_25 = {u for u in users if is_enabled("new-checkout", u, 25)}
print("enabled at 10%:", len(on_10))
print("enabled at 25%:", len(on_25))
print("everyone from 10% still on at 25%:", on_10 <= on_25)
other = {u for u in users if is_enabled("new-search", u, 10)}
print("overlap with a different flag at 10%:", len(on_10 & other))
Output (Python 3.14):
enabled at 10%: 9937
enabled at 25%: 25212
everyone from 10% still on at 25%: True
overlap with a different flag at 10%: 1024
What the numbers show:
- About 10% and 25% of 100,000 users are enabled at those settings (9,937 and 25,212: hashing gives a close, not exact, split).
- Every user who had the feature at 10% still has it at 25%, so raising the percentage never takes the feature away from someone mid-rollout.
- Mixing the flag name into the hash keeps flags independent: the 10% for
new-searchoverlaps the 10% fornew-checkoutin 1,024 users, close to the 10% of 9,937 (about 994) you expect by chance. Without it, the same unlucky 10% of users would receive every risky feature first.
Trade-offs and pitfalls
- Putting everything in flags. Flags for tuning knobs lose the review and validation that configuration changes get. A timeout is not a feature.
- Flag debt. Ten flags in one code path is up to 210=1024 combinations, and you have tested a handful. Cap the number of active flags per service and enforce removal dates.
- Flags that change data shape. If the new path writes data the old path cannot read, turning the flag off is no longer a safe rollback. Plan the migration so both paths can read both formats.
- Evaluating flags remotely on every request adds a network call to the hot path (the code that runs on every single request, where added latency is felt by every user) and makes the flag service a single point of failure. Evaluate locally instead, from rules the SDK already downloaded and cached, the same approach described under Targeting above.
- No audit trail. Record who flipped which flag when, the same way you would for a config change, because "someone turned it off" is a frequent root cause.
Design a dynamic configuration service that supports versioned configurations, atomic rollouts, and quick rollback. Requirements: services can query a specific version or subscribe to change notifications, audit history is preserved, and rollbacks across many instances complete within minutes. Sketch the APIs, storage approach, and how you'd coordinate rollout and rollback safely.
Sample Answer
Direct answer
Make every configuration version an immutable, content-addressed document, and make "what is live" a separate, tiny release pointer per config and per rollout stage. Publishing never edits a live document: it creates a new version. Rolling out means moving the pointer for a growing slice of instances; rolling back means moving the pointer back to a version every instance has already run, which is one small write plus a notification, not a new edit. Instances learn about changes through a watch stream and also poll on a fixed interval, so the rollback time has a hard upper bound even when the push path is broken.
Requirements I am designing to
- Scale assumption: about 20,000 instances across 300 services; configs are typically under 50 KiB; tens of publishes per hour, not thousands.
- Clients can fetch a specific version and subscribe to changes.
- Atomic rollout: an instance sees all of version N or all of version N+1, never a mix of keys from both.
- Audit history: who changed what, when, why, and what was live at any past moment.
- Rollback across all instances within minutes; I will target under 2 minutes worst case.
Terms
- Content-addressed: a version's ID is a hash of its bytes (for example SHA-256). Same bytes, same ID; a client can verify it got exactly what was published.
- Watch / subscription: a long-lived connection (a gRPC stream, using gRPC, a binary remote-procedure-call protocol; SSE which is server-sent events over HTTP; or long polling where the server holds a request open until something changes) over which the server tells clients "the version you should run is now X".
- Bake (bake time): the period you hold a change at a given stage, watching it, before trusting it enough to widen to the next stage.
- CAS (compare-and-swap): "update the pointer to X only if it is currently W". It stops two operators from overwriting each other's rollout.
- Canary: a small first slice of instances that gets a change before everyone else.
Architecture
flowchart LR
Op[Operator or deploy pipeline] -->|publish, release, rollback| API[Config API]
API -->|validate schema| API
API --> DB[(Postgres: versions, releases, audit log)]
API -->|pointer change event| Bus[Change notifier]
Bus --> Edge[Distribution nodes]
Edge -->|watch stream: version id| Agent[Client library in each instance]
Agent -->|GET blob by hash| Edge
Agent -->|health and applied version| Mon[Rollout controller]
Mon -->|advance or roll back| API
Storage
config_versions(config_name, version_id, content_hash, body, schema_version, author, message, created_at): append-only. Nothing is ever updated or deleted in this table (retention aside), which is what makes audit and rollback trivial.releases(config_name, stage, version_id, updated_by, updated_at, revision): one small row per config and rollout stage (for examplecanary,stage-10pct,all). Therevisioncolumn makes CAS a singleUPDATE ... WHERE revision = ?.audit_log: one row per publish, release move and rollback, including the ticket or reason.- Postgres is enough at this write rate. The read load does not go to Postgres: distribution nodes (a small fleet of cache servers placed close to the instances, the same role a CDN edge plays for web assets) cache version blobs by hash (they are immutable, so the cache never needs invalidating) and hold the current pointers in memory.
APIs
| Call | Purpose |
|---|---|
POST /configs/{name}/versions (body, message) | Validate against the schema, store immutable version, return version_id. Does not change what is live. |
GET /configs/{name}/versions/{version_id} | Fetch an exact version (the "query a specific version" requirement). |
POST /configs/{name}/releases (version_id, plan, expected revision) | Start a staged rollout; CAS on the release row. |
POST /configs/{name}/rollback (to_version_id, reason) | Point every stage at a previous version in one transaction. |
WATCH /configs?names=a,b&known=a:v12,b:v4 | Stream "you should now run version X" events. Carries IDs, not bodies. |
GET /configs/{name}/history | Audit trail: versions, releases, rollbacks with who and why. |
How an instance applies a version atomically
- The watch stream says "for your stage,
payments-limitsshould bev13". - The client library downloads the blob by hash (or reads it from its local cache), verifies the hash, and parses and validates it completely before touching live state.
- It swaps one in-memory reference from the old parsed object to the new one. Application code always reads through that reference, so a request sees either v12 or v13 in full.
- It reports
applied=v13(orrejected=v13, reason) to the rollout controller. - It writes the version to local disk as last known good, so a restart while the service is unreachable still boots with valid config.
Coordinating rollout safely
sequenceDiagram
participant Op as Operator
participant API as Config API
participant C as Canary instances
participant R as Rollout controller
participant A as All instances
Op->>API: release v13 (plan 1% then 10% then 100%)
API->>C: watch event: run v13
C->>R: applied v13, error rate, latency
R->>R: bake 10 min, compare with instances still on v12
R->>API: advance to 10%, then 100%
API->>A: watch event: run v13
Note over R,API: on regression, controller calls rollback to v12
- Stage membership is deterministic:
hash(instance_id + config_name) mod 100 < stage_percent. For example, hashing"i-04821" + "payments-limits"lands at bucket 48 out of 100: that instance stays out at the 1% and 10% stages (48 is not below either threshold), and first receives the new version once the rollout reaches 50% (48 < 50). The same instances are always in the 1% for a given config, so a rollback cleanly shrinks the set (dropping every instance whose bucket is no longer below the smaller percentage) instead of reshuffling it. - Health gates compare canary instances against the instances still on the old version over the same window (error rate, latency, crash count, and "rejected config" reports). The comparison against a live control group avoids blaming a config for a traffic spike that hit everyone.
- Automatic rollback fires on a gate failure; humans can also trigger it with one call.
- Only one rollout per config at a time, enforced by the CAS on the release row, so two operators cannot interleave.
- Blast-radius limits (blast radius: how much of the system a single bad change can affect): a config that many services depend on can require a longer bake and a smaller first stage.
Worked example: can rollback finish within minutes?
Assumptions: 20,000 instances, a 50 KiB config, watch streams held by distribution nodes, and a fallback poll every 60 seconds for any instance whose stream is broken.
- Push path. Rollback is one row update plus 20,000 small "run v12" messages. Each instance already has v12 cached locally because it ran v12 before this rollout, so it needs no download at all.
- Worst case if a client did need to download: 20,000 instances × 50 KiB = 1,000,000 KiB = 976.6 MiB, about 0.95 GiB of total transfer (binary units used consistently throughout: 1,024 KiB per MiB, 1,024 MiB per GiB). Spread over roughly 30 seconds by distribution nodes serving immutable, cacheable blobs, that is about 976.6 / 30 ≈ 33 MiB per second fleet-wide, trivial for a small cache fleet to absorb.
- Bound when push fails. The 60-second poll means every healthy instance converges within about 60 s plus apply time, even if every watch stream were down. Those polls cost 20,000 / 60 ≈ 333 requests per second fleet-wide, each a tiny "is my version still current?" check answered from memory.
- Result: typical rollback is seconds (push); the guaranteed bound is roughly one poll interval, comfortably inside "a few minutes". If a tighter bound is needed, shorten the poll to 30 s at double the request rate (about 667 per second).
Trade-offs and pitfalls
| Decision | Chosen | Why | What would change it |
|---|---|---|---|
| Push vs pull | Push notification, pull the body, plus periodic poll | Push gives speed, poll gives a guaranteed bound | Very small fleets can poll only |
| Store | Postgres + edge cache | Low write rate, strong audit queries | Needing multi-region writes might push toward etcd or Spanner-style storage (a globally distributed database that can accept correct writes from multiple regions at once, at the cost of extra latency and operational complexity) |
| Rollback | Pointer move to an old version | Old version is already validated and cached | None: "roll back by editing forward" is how outages get extended |
| Atomicity unit | Whole document per config | Easy to reason about | Cross-config atomicity (two configs that must change together) needs a "bundle" version that pins both |
Pitfalls:
- Rolling back by publishing a "fixed" edit. It is a new, untested version under pressure. Roll back to the known-good ID first; fix forward afterwards.
- Config that can crash the parser. Validate at publish time and in the client before swapping; a client that rejects a version must keep running the old one.
- Everyone applies at the same instant. A change that, for example, resets connection pools can cause a synchronized spike. Add a few seconds of random jitter to the apply step.
- Config and code coupling. If v13 needs a code change that only half the fleet has, the rollout controller must know the minimum client version for a config version and skip instances that are too old.
Design a service discovery strategy for a microservices platform operating across multiple datacenters. Compare DNS-based discovery, client-side discovery with a registry like Consul/etcd, and service-mesh-based discovery. Discuss trade-offs in latency, consistency, failover behavior, and operational complexity.
Sample Answer
Direct answer
Run one independent registry per datacenter (never one consensus cluster stretched across datacenters), make every lookup local-first, and fail over to the nearest healthy datacenter through an explicit, per-service failover policy. On top of that, choose the lookup mechanism by client type: DNS as the universal baseline, client-side discovery from the registry for services that need fast, health-aware balancing, and a service mesh where you also need mutual TLS (both sides of a connection proving their identity with certificates, not just the server) and fine-grained traffic control. For a typical platform I would commit to: Consul (or etcd-backed equivalent) per datacenter, federated (each datacenter's registry stays independent but can answer queries about the others through a lightweight cross-datacenter link); its DNS interface for everyone; mesh adopted per service where the security or routing need justifies the extra moving parts.
Terms first
- Service registry: the live list of healthy instances per service (Consul, etcd, ZooKeeper, or Kubernetes' own API).
- Client-side discovery: the calling service queries the registry itself (usually through a library) and picks an instance.
- Server-side / DNS discovery: the caller just resolves a name; something else (DNS server, load balancer) decides.
- Service mesh: a proxy sidecar next to every instance does discovery, load balancing, retries and encryption, fed by a control plane.
- Raft quorum: registries like Consul and etcd agree on writes using the Raft protocol, a consensus algorithm in which one elected leader orders every write and a majority of servers must acknowledge it before it is durable.
- Failover: sending traffic elsewhere when the preferred instances are unhealthy.
- Watch: a long-held request a client keeps open against the registry; instead of the client re-asking on a timer, the registry pushes each change down that open connection the moment it happens.
- Outlier detection (ejection): a proxy watches the real responses a backend returns and temporarily stops sending it traffic after enough of them look like failures, without waiting for a separate health check to catch up.
- Locality / locality-aware failover: preferring an endpoint in the caller's own datacenter first, and reaching into another one only when nothing local is healthy; "locality-weighted" means splitting traffic across localities by a configured ratio rather than all-or-nothing.
Why not one global registry
A Raft cluster commits a write only after a majority acknowledges it. Spread 5 servers across 3 datacenters that are 70 ms apart, a typical 2-2-1 split, and no single datacenter holds the 3-of-5 majority a write needs on its own, so every registration, deregistration and health update pays at least one cross-datacenter round trip (about 70 ms) before it commits, and a network partition can leave the minority side (whichever datacenters are left with fewer than 3 reachable servers) unable to register anything at all. Keeping each datacenter's registry local means local writes commit in about a millisecond and a partition leaves every datacenter fully functional on its own. Consul's design follows this: servers form a Raft cluster per datacenter, and datacenters are joined by a lighter WAN (wide area network) gossip layer (nodes periodically exchange state with a few random peers instead of every node talking to every other one, so it stays cheap even at scale) used for cross-datacenter queries, not for shared consensus.
Comparison
| DNS-based | Client-side with registry | Service mesh | |
|---|---|---|---|
| Lookup latency | one DNS query, then cached for the TTL (time-to-live); near zero on cache hits | in-memory lookup in the library, kept fresh by a watch; near zero | proxy already has endpoints; adds one local proxy hop per request (sub-millisecond to low milliseconds) |
| Consistency / freshness | stale up to the TTL plus any client caching that ignores TTL | seconds: watch pushes changes as they commit | seconds: control plane pushes endpoint updates to every proxy |
| Failover behaviour | coarse: slow (TTL-bound) and per name, no per-request retry | fast and per request, but only as good as each language's library | fastest and uniform: retries, outlier ejection and locality failover in the proxy |
| Cross-DC failover | needs a geo-aware DNS answer or registry-generated records | library applies a failover list | locality-aware load balancing built in |
| Operational complexity | lowest | medium: registry cluster plus a client library per language to maintain | highest: control plane, sidecar on every pod, certificate authority (the component that issues and signs the certificates every proxy uses to prove its identity for mTLS), upgrades of both |
| Language coverage | every client | only languages with a maintained library | every client (it is out of process) |
Worked example: failover time after an instance dies
Assume health checks every 10 s, marked critical after 3 failures, DNS TTL of 30 s.
- DNS: detection 3 x 10 = 30 s, then clients may keep the old answer for up to 30 s more: worst case about 60 s of some traffic still going to the dead instance (longer if a client caches past the TTL).
- Client-side with watch: detection 30 s, then the watch delivers the change in well under a second: about 30 s, and a library that retries on connection failure hides most of that window.
- Mesh: same 30 s for the registry path, but the proxy also does outlier detection on live traffic (Envoy, a widely used sidecar proxy, ejects a host by default after 5 consecutive 5xx errors, the HTTP status codes that signal a server-side failure), so a hard-down instance stops receiving requests after a handful of failed requests, often before the health check notices.
The recommended design
flowchart TB
subgraph DC1[Datacenter 1]
R1[Registry cluster, 5 servers] --- A1[Services: DNS or library or sidecar]
end
subgraph DC2[Datacenter 2]
R2[Registry cluster, 5 servers] --- A2[Services: DNS or library or sidecar]
end
R1 <-->|WAN federation: cross-DC queries only| R2
A1 -->|failover only when local instances unhealthy| A2
- Local-first resolution.
payments.service.consul(or the mesh equivalent) returns only instances in the caller's datacenter by default. - Explicit failover per service. In Consul this is a prepared query with a failover list ("nearest 2 datacenters if no local healthy instances"); in a mesh it is locality-weighted load balancing. Opt-in per service, because failing over a service whose database is local can make things worse (cross-DC latency on every query, or writes against a read-only replica).
- Mechanism by client type. Legacy and third-party software uses DNS. Latency-sensitive internal services use the client library or the mesh. Services needing zero-trust networking (verifying every call cryptographically instead of trusting it just because it came from inside the network perimeter; in practice, mTLS between every pair) use the mesh.
- Configuration stays per datacenter too. Consul's key/value store is not replicated across datacenters by default; replicate deliberately (a tool that copies a prefix from a primary datacenter) and treat the primary as the only writer.
Trade-offs and pitfalls
- Cross-DC failover can cause a cascade. If DC1 fails over its 10,000 requests per second onto DC2, DC2 needs that headroom. Cap failover traffic or pre-provision for it.
- DNS cache ignorance is the classic outage: some runtimes pin an answer far longer than the TTL. Test every major language's behaviour, do not assume.
- A mesh doubles your upgrade surface (every sidecar plus the control plane), and a control-plane outage must leave proxies serving their last-known endpoints, not empty ones.
- What would change the recommendation: a single datacenter makes most of the federation machinery unnecessary; a hard requirement for mTLS everywhere makes the mesh the default rather than the exception; an all-Kubernetes estate can use Kubernetes' native discovery per cluster plus a multi-cluster layer instead of Consul.
Implement a configuration validator in Python that reads a JSON configuration file, validates required keys and types against a provided JSON Schema (you may assume use of the jsonschema package), and writes an atomic validated output file for services to consume. Discuss handling of defaults, deprecated keys, and helpful validation errors for operators.
Sample Answer
Direct answer
Load the file, check the schema itself is valid, migrate any deprecated keys, then validate while filling in defaults. Collect every error rather than stopping at the first, and report each with the exact path to the bad value. Only if there are zero errors, write the validated result to a temp file in the same directory and os.replace it over the output, so services never read a half-written or invalid file.
Approach
- Parse the input. A JSON syntax error gets its own message with line and column, because schema errors make no sense on a file that is not JSON.
- Check the schema with
check_schema. A broken schema is a bug in the service, not the operator's fault, so it should crash loudly instead of rejecting good configs. - Migrate deprecated keys before validation, so a renamed key's value is validated under its new name. Emit a warning telling the operator what to rename.
- Validate and fill defaults in one pass. JSON Schema's
defaultkeyword is only an annotation (metadata attached to a value for tools to read, unlike a validation keyword such astype, which changes whether the data passes): thejsonschemapackage does not insert defaults by itself. The package's documented extension point,validators.extend, lets us wrap thepropertiescheck so it fills a missing property from itsdefaultbefore validating it. - Report all errors, sorted by path, as
path: message (rule, got value). - Write atomically, or not at all.
Code
# validate_config.py (pip install jsonschema)
import copy, json, os, sys, tempfile
from jsonschema import Draft202012Validator, validators
def with_defaults(base):
"""Validator class that also fills in `default` values for missing properties."""
check_props = base.VALIDATORS["properties"]
def properties(validator, props, instance, schema):
if isinstance(instance, dict):
for name, sub in props.items():
if "default" in sub and name not in instance:
instance[name] = copy.deepcopy(sub["default"])
yield from check_props(validator, props, instance, schema)
return validators.extend(base, {"properties": properties})
DefaultingValidator = with_defaults(Draft202012Validator)
def migrate_deprecated(config, schema):
"""Rename deprecated keys (schema: "deprecated": true, "x-replaced-by": "<new key>")."""
warnings = []
for name, sub in schema.get("properties", {}).items():
if sub.get("deprecated") and name in config:
new = sub.get("x-replaced-by")
if new and new in config:
warnings.append(f"'{name}' is deprecated and ignored because '{new}' is also set")
del config[name]
elif new:
config[new] = config.pop(name)
warnings.append(f"'{name}' is deprecated; value moved to '{new}'. Rename it in the source file")
else:
warnings.append(f"'{name}' is deprecated and has no replacement")
return warnings
def explain(err):
where = err.json_path # e.g. $.database.pool_size
if err.validator == "required":
return f"{where}: {err.message}"
if err.validator == "additionalProperties":
return f"{where}: {err.message} (typo, or a key this version does not know?)"
return f"{where}: {err.message} (rule: {err.validator}={err.validator_value!r}, got {err.instance!r})"
def atomic_write_json(path, obj):
d = os.path.dirname(os.path.abspath(path))
fd, tmp = tempfile.mkstemp(dir=d, prefix=".validated-", suffix=".tmp")
try:
with os.fdopen(fd, "w") as f:
json.dump(obj, f, indent=2, sort_keys=True); f.write("\n")
f.flush(); os.fsync(f.fileno()) # fsync: push the write out of the OS's buffer onto disk, not just out of Python's
os.replace(tmp, path)
except BaseException:
if os.path.exists(tmp): os.unlink(tmp)
raise
def validate_file(config_path, schema_path, out_path):
with open(schema_path) as f: schema = json.load(f)
Draft202012Validator.check_schema(schema) # a broken schema is a bug, not an operator error
try:
with open(config_path) as f: config = json.load(f)
except json.JSONDecodeError as e:
return [f"{config_path}:{e.lineno}:{e.colno}: not valid JSON: {e.msg}"], []
warnings = migrate_deprecated(config, schema)
errors = sorted(DefaultingValidator(schema).iter_errors(config), key=lambda e: list(e.absolute_path))
if errors:
return [explain(e) for e in errors], warnings # report EVERY problem, write NOTHING
atomic_write_json(out_path, config)
return [], warnings
if __name__ == "__main__":
errs, warns = validate_file(*sys.argv[1:4])
for w in warns: print("WARNING", w, file=sys.stderr)
for e in errs: print("ERROR ", e, file=sys.stderr)
sys.exit(1 if errs else 0)
How with_defaults works
validators.extend is the jsonschema package's documented way to build a modified validator class: give
it a base class and a dict of {keyword: replacement_check_function}, and it returns a new class that runs
your function for that one keyword and the base class's own logic for everything else.
Here the keyword being replaced is properties, the check that walks an object's known properties.
check_props = base.VALIDATORS["properties"] grabs the original function before it is replaced, so the
new version can still call it. The new properties function then does two things in order: first, for
every property that has a default in the schema and is missing from the instance, it writes that default
straight into the instance dict (mutating it in place); then yield from check_props(...) hands off to the
original check to actually validate the now-filled-in instance.
yield from matters because check_props is a generator: the jsonschema package walks the whole schema
tree and yields one error at a time as it finds them, rather than building and returning a list. yield from check_props(...) re-yields every error the original check produces, one by one, without collecting
them into a list first. So the wrapper adds no errors of its own, it only inserts defaults before the real
check runs, and every genuine error still comes through unchanged.
Worked example (executed)
# demo.py
import json, os, pathlib
from validate_config import validate_file
d = pathlib.Path("/tmp/config-demo"); d.mkdir(exist_ok=True)
schema = {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["service_name", "database"],
"additionalProperties": False,
"properties": {
"service_name": {"type": "string", "minLength": 1},
"log_level": {"enum": ["debug", "info", "warn", "error"], "default": "info"},
"timeout_ms": {"type": "integer", "minimum": 1, "maximum": 60000, "default": 2000},
"timeout": {"deprecated": True, "x-replaced-by": "timeout_ms"},
"database": {
"type": "object", "required": ["host"], "additionalProperties": False,
"properties": {"host": {"type": "string"},
"port": {"type": "integer", "default": 5432},
"pool_size": {"type": "integer", "minimum": 1, "maximum": 200, "default": 10}}}
}
}
(d / "schema.json").write_text(json.dumps(schema))
out = d / "validated.json"
if out.exists(): out.unlink()
good = {"service_name": "checkout", "timeout": 1500, "database": {"host": "db.internal"}}
(d / "good.json").write_text(json.dumps(good))
errs, warns = validate_file(d / "good.json", d / "schema.json", out)
print("good ->", errs, warns)
print(out.read_text())
bad = {"service_name": "", "log_level": "verbose", "timeout_ms": "3000",
"databse": {}, "database": {"host": "db.internal", "pool_size": 500}}
(d / "bad.json").write_text(json.dumps(bad))
before = out.read_text()
errs, warns = validate_file(d / "bad.json", d / "schema.json", out)
for e in errs: print("ERROR", e)
print("output unchanged after bad input:", out.read_text() == before)
Output (jsonschema 4.26.0, Python 3.14):
good -> [] ["'timeout' is deprecated; value moved to 'timeout_ms'. Rename it in the source file"]
{
"database": {
"host": "db.internal",
"pool_size": 10,
"port": 5432
},
"log_level": "info",
"service_name": "checkout",
"timeout_ms": 1500
}
ERROR $: Additional properties are not allowed ('databse' was unexpected) (typo, or a key this version does not know?)
ERROR $.database.pool_size: 500 is greater than the maximum of 200 (rule: maximum=200, got 500)
ERROR $.log_level: 'verbose' is not one of ['debug', 'info', 'warn', 'error'] (rule: enum=['debug', 'info', 'warn', 'error'], got 'verbose')
ERROR $.service_name: '' should be non-empty (rule: minLength=1, got '')
ERROR $.timeout_ms: '3000' is not of type 'integer' (rule: type='integer', got '3000')
output unchanged after bad input: True
What this shows:
- The good file used the old key
timeout; it was moved totimeout_ms, and the operator got a warning to fix the source. log_level,database.portanddatabase.pool_sizewere missing and were filled from the schema's defaults, so services read one complete file and do not each hard-code their own fallback.- The bad file produced five errors in one run. An operator fixing them one at a time with a stop-at-first-error validator would need five deploy attempts.
databse(a typo) is caught only becauseadditionalProperties: falseis set. Without it, the typo passes validation and the realdatabaseblock would silently fall back to defaults.- The previously validated output is untouched after the bad input, so a running service keeps reading the last good config.
Key points
json_path(for example$.database.pool_size) tells the operator exactly where to look, which is the difference between a helpful error and "validation failed".- Defaults in the schema, not in code. One place defines them, and the validated output shows the effective value, which makes "what is this service actually running with?" answerable by reading one file.
- Deprecation metadata.
deprecated: trueis a real JSON Schema annotation (2019-09 and later), but validators do not act on it, so the migration step reads it.x-replaced-byis my own extension keyword; JSON Schema ignores unknown keywords, so it is safe to add. - Atomic write. Temp file in the same directory (so the rename stays on one filesystem),
fsync(force the write from the OS's memory buffer onto physical disk before continuing), thenos.replace, which is atomic on POSIX (the standard Linux and macOS both follow for how the filesystem behaves): a reader sees the old file or the new one, never a mix.
Complexity
Validation is linear in the size of the config times the schema rules that apply to each value, O(n) for ordinary configs. The atomic write is O(n) in output size. Memory holds the config and the list of errors, both small.
Edge cases and pitfalls
- Defaults are inserted before their own validation, so a bad default in the schema (say
pool_sizedefault 0 withminimum: 1) fails every config. That is correct behaviour: it is a schema bug and should surface in CI. - Defaults inside
oneOf/anyOfbranches (JSON Schema keywords for "exactly one of these sub-schemas must match" / "at least one must match") are unsafe to fill this way, because the filler writes into the instance while trying branches that may not match. Keep defaults on plainproperties. - Mutating the input. The filler changes the parsed dict in place. That is fine here because we parse fresh each run; in a library, validate a
deepcopy. - Both old and new key set. The new key wins and the old one is dropped with a warning, rather than guessing.
- Types that look right.
"3000"is a string, not an integer. Resist coercing it: silent coercion hides the fact that some tool is writing the wrong type. - Exit codes. The CLI exits 1 on any error so a deploy pipeline or init container (a Kubernetes container that runs to completion before the main application container starts, often used to validate or prepare its config) can block the rollout instead of shipping a bad file.
Unlock Full Question Bank
Get access to all 21 Service Discovery and Configuration Management interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.