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.
You need to roll out a new feature with feature flags to 10% of users and automatically rollback if SLOs degrade. Outline the flag targeting, bucketing, telemetry to observe impact, detection windows, and an automated rollback mechanism. Include how to avoid cascading rollbacks and how to surface reasons to humans.
Sample Answer
Direct answer
Put the feature behind a flag, assign users to the 10% by a deterministic hash of the user ID salted with the flag's name, and tag every request's metrics with which variant served it. A rollback controller then compares the 10% treatment cohort (users who get the new feature) against the 90% control cohort (users who do not) over two windows: a short one to catch disasters fast and a long one to avoid acting on noise. If the treatment cohort is burning its SLO (service-level objective) error budget and control is not, the controller flips the flag to 0% (no code deploy needed), records exactly why, and pages a human. Comparing against control, rather than against the global SLO, is also what prevents cascading rollbacks: a flag is only blamed for damage its own cohort shows.
Terms used below
- Feature flag: a runtime switch, read from a config service, that decides per request whether new code runs. Turning it off is a config change that propagates in seconds, not a redeploy.
- SLO: the reliability target you promise, such as "99.9% of checkout requests succeed over 30 days". The 0.1% you are allowed to fail is the error budget.
- Burn rate: how fast you are spending the error budget relative to plan. A burn rate of 1 spends exactly the whole budget in 30 days; a burn rate of 14.4 spends 2% of a 30-day budget in one hour.
- p99: the 99th-percentile latency, the time under which 99% of requests finish.
1. Flag targeting and bucketing
Bucketing rule: bucket = hash(flag_key + ":" + user_id) mod 10000, and the user is in treatment when bucket < 1000 (10.00%).
Why each part matters:
- Deterministic, not random per request. The same user must see the same variant on every request and every server, or a checkout started in the new flow finishes in the old one. A hash gives stickiness with no stored assignment table.
- Salted with the flag key. Without the salt, the same users land in the first 10% of every flag. That user group would absorb every experiment at once, and a bug in one flag would contaminate the metrics of all the others.
- 10,000 buckets, not 100. Lets you ramp in 0.01% steps later (0.5%, 1%, 10%, 25%) and, importantly, ramping from 10% to 25% keeps the original 10% in treatment, because
bucket < 1000is a subset ofbucket < 2500. - Bucket by the unit the risk lives in. Per user for a UI change; per tenant/account for a B2B change (half a company on a new permissions model is a support incident); per request only for stateless back-end changes like a new cache.
- Targeting rules evaluate before the percentage: first exclusions (enterprise accounts under a change freeze, users mid-payment), then internal staff forced on, then the 10% hash rule.
- Evaluate locally. The SDK (software development kit, the client library embedded in the application) holds the rule set in memory and receives updates via a streaming connection (a persistent connection the flag service pushes changes over, instead of the client polling for them), so evaluation adds no network hop and still works if the flag service is down (it keeps the last known rules; the safe default for a new feature is "off").
2. Telemetry to observe impact
Every metric and trace carries a flag.<name>=on|off label so the two cohorts can be compared directly:
| Signal | Why | Watch out |
|---|---|---|
| Error rate per cohort (5xx and failed business outcomes, e.g. payment declined by our code) | The SLO signal itself | Count errors in the user's cohort, even when the failing call is downstream |
| p99 latency per cohort | New code paths are often slower before they are wrong | Percentiles cannot be averaged across hosts (a p99 of 100ms on host A and 100ms on host B is not a combined p99 of 100ms); use histograms (buckets that count how many requests fell into each latency range, which combine correctly across hosts before computing the percentile) |
| Business guardrails (checkout conversion, add-to-cart rate) | A feature can be "healthy" and still break the funnel | Needs a longer window, noisy |
| Saturation of shared dependencies (DB CPU, queue depth) | Treatment might hurt everyone via a shared resource | This is the one case where control degrades too, see section 5 |
| Flag evaluation counts per variant | Confirms the split is really 10/90 | A 7/93 split means bucketing or targeting is broken: this is called a sample-ratio mismatch (the actual cohort split differs from the configured one by more than chance would explain), and all comparisons are suspect until it is fixed |
The label cardinality (cardinality: how many distinct values a label can take; a metrics system's storage cost grows with it) is fine: two values per flag. Do not label metrics with the bucket number or the user ID.
3. Detection windows, with the arithmetic
Suppose checkout serves 5,000 requests per second (RPS), so the 10% cohort sees 500 RPS, and the SLO is 99.9% success (baseline error rate 0.1%).
In a 5-minute window the treatment cohort serves 500 × 300 = 150,000 requests. At the baseline 0.1% you expect 150 errors; for rare, independent failures the natural spread of that count (its Poisson standard deviation) is about the square root of the expected count, √150 ≈ 12.2. If the feature doubles the error rate to 0.2% you see about 300 errors, which is (300 − 150) / 12.2 ≈ 12 standard deviations above normal. Five minutes is plenty.
Now a low-traffic service where treatment sees only 5 RPS: 5 minutes is 1,500 requests, 1.5 expected errors, and a doubling gives 3 errors, only about 1.2 standard deviations away. That is indistinguishable from luck. To expect even 30 baseline errors, first find the requests needed: 30 / 0.001 = 30,000 requests. At 5 RPS that takes 30,000 / 5 = 6,000 seconds, which is 100 minutes. The detection window is set by traffic, not by preference, and a low-traffic flag must either ramp more slowly or accept that automation only catches large regressions.
So use two rules, both evaluated on the treatment cohort against control:
- Fast rule (catch disasters): 5-minute window AND 1-hour window both show treatment burning budget at 14.4x or more (error rate at or above 14.4 × 0.1% = 1.44%) while control is below 1x. The short window makes it fire fast; requiring the long window too stops a single 5-minute blip from rolling back.
- Slow rule (catch degradations): over 6 hours, treatment's error rate or p99 is significantly worse than control's (a two-proportion test, i.e. a standard statistical check of whether two error rates differ by more than chance, or a fixed threshold such as "treatment p99 exceeds control p99 by more than 20%") with at least a minimum request count.
Add a minimum sample gate (no decision before N requests in the cohort) and a bake time (a minimum duration to sit at 10% and watch, even if the numbers already look fine) at 10% before any further ramp.
4. The automated rollback mechanism
flowchart LR
A[Metrics tagged by flag cohort] --> B[Rollback controller]
B -->|treatment bad, control fine| C[Set flag to 0 percent]
C --> D[Flag service streams update to SDKs]
B -->|both cohorts bad| E[Hold ramp, page human]
C --> F[Audit record plus page with reason]
- The controller evaluates the rules every minute. On a trip it writes
rollout=0%to the flag service with a compare-and-set (a write that only succeeds if the stored value still matches what was last read, so two writers racing to change it cannot silently clobber each other) on the flag's version (so it cannot overwrite a human who changed the flag a second earlier), and freezes the flag so no automation re-ramps it. - Rollback must be fast and verified: the flag change reaches SDKs by streaming in seconds; the controller then confirms that the variant evaluation counts actually went to 0% on, and that treatment errors decay. If they do not, the problem is not the flag, and it escalates.
- Rollback goes to a known state (0%), never "the previous percentage" chains, and it is idempotent: running it twice is harmless.
- Automation only ever makes the flag more conservative. Re-enabling is always a human decision.
5. Avoiding cascading rollbacks
A cascading rollback is when one real problem triggers a chain of automated reversions of innocent changes, each of which may itself disrupt users.
- Attribute by cohort, not by global health. If both treatment and control degrade, the flag is not the cause (a database or a deploy is), so the controller does not roll back; it pauses ramps and pages. This single rule stops a platform outage from reverting every flag in flight.
- One ramping change per blast radius (blast radius: everything that one bad change can affect, here the service or shared dependency a flag touches). Serialize ramps: one flag ramping per service (or per shared dependency) at a time, so attribution stays unambiguous.
- Cooldown and rate limit. After any automated rollback, block other automated rollbacks in that service for, say, 15 minutes and cap the number per hour; beyond the cap, a human decides.
- Do not chase dependencies. If service A's flag breaks service B, roll back A's flag; B's own flags stay put unless B's own treatment/control comparison says otherwise.
- The shared-resource exception. If treatment saturates a shared database, control degrades too and cohort comparison hides it. Cover this with a separate guard on the dependency's saturation that correlates with the ramp time and pages rather than auto-reverting.
6. Surfacing reasons to humans
Every automated action produces a structured record, posted to the owning team's channel, the flag's audit log, and as an annotation on dashboards:
Flag
new-checkout-flowrolled back 10% -> 0% at 14:32 UTC by rollback-controller. Rule: fast burn. Treatment error rate 2.1% (5m) / 1.6% (1h) vs control 0.09% / 0.10%. Treatment requests in window: 148,200. Flag version 41 -> 42. Owner: @payments-oncall. Re-enable requires a human.
The reason must name the rule, both windows, both cohorts, the sample size and a link to the dashboard pre-filtered to the incident window, so the on-call can judge a false positive in one read.
Trade-offs and pitfalls
- Global SLO as the trigger is the most common wrong answer: at 10% exposure a feature that fails 1% of its own requests adds only 0.1 percentage points to the global error rate (0.1 × 1%), so it can hide inside normal variation, while an unrelated outage that pushes the global rate up gets blamed on whatever flag happens to be ramping.
- Per-request random bucketing breaks stickiness and inflates noise.
- Too-short windows on low-traffic flags produce flapping rollbacks; too-long windows let a disaster run for hours. Size them from traffic, as above.
- Flags that change data shape (new schema writes) cannot be rolled back by flipping a flag alone: the old code must be able to read what the new code wrote. Make the new write path backward compatible before ramping.
- Stale flags: once at 100%, remove the flag and the dead branch, or the codebase fills with untested combinations.
Config or discovery changes are a common trigger for production incidents, but by the time an alert fires it's often not obvious that a recent change was the cause. Design an observability approach that would let you quickly confirm or rule out a recent config or discovery change as the source of a regression, and that would catch this failure mode reliably without drowning on-call in noise from routine changes.
Sample Answer
Direct answer
Treat every configuration and discovery change as a first-class telemetry event (who, what, where, which version, when), stamp the active config version onto the service's own health signals, and join the two at alert time. Do not alert on changes themselves: alert on user-facing symptoms (SLO burn), and have the alert arrive already annotated with "these N changes touched this service or its dependencies in the last 30 minutes, and here is the error rate split by old vs new version". For changes that are rolled out progressively, add an automated canary comparison that halts the rollout on its own, so many change-induced regressions never page anyone.
Terms first
- SLO (service-level objective): the reliability target, for example "99.9% of checkout requests succeed over 30 days". The 0.1% allowed failure is the error budget.
- Burn rate: how fast you are spending that budget. A burn rate of 1 spends it exactly over the 30 days; 14.4 spends 2% of it in one hour (30 days is 30 x 24 = 720 hours, so spending 2% of the whole budget inside one hour is 0.02 x 720 = 14.4 times the sustainable pace).
- Discovery change: anything that alters where traffic goes: an instance registering or deregistering, a health check flipping, a load-balancer weight, a DNS record, a service-mesh routing rule.
- Blast radius: the set of services a change can affect.
- Canary: sending a change to a small slice first and comparing that slice with the untouched remainder.
Why this failure mode is hard
The regression and its cause are separated in time (a TTL, cache or rolling restart delays the effect by minutes), in space (a change to the payments routing rule surfaces as checkout errors), and in tooling (the change lives in Git, Consul, a flag console, the UI where operators toggle feature flags, or a CI log; the alert lives in the metrics system). The design closes all three gaps.
The design
flowchart LR
A[Config store / flag service / registry / mesh control plane] -->|change event| B[Change event bus]
B --> C[Change index: searchable by service and time]
D[Services emit metrics tagged with config_version] --> E[SLO burn-rate alert]
E --> F[Alert enricher]
C --> F
G[Dependency graph from traces] --> F
F --> H[Page with ranked suspect changes]
B --> I[Progressive rollout controller]
D --> I
I -->|auto-halt and revert| A
1. Capture every change as a structured event
Each writer (the config service, the feature-flag service, the service registry, the mesh control plane, the component that pushes routing rules out to every service's sidecar proxy, CI/CD) emits one event per change:
| Field | Example |
|---|---|
| change_id, version | cfg-8812, payments/routing@v143 |
| actor and path | alice via GitOps PR #2291 (GitOps: config changes are made by merging a pull request, so the merge is both the audit trail and the deploy trigger) or autoscaler |
| scope | service payments, region eu-west-1, 5% of hosts |
| kind | config value, flag toggle, route weight, instance set |
| diff summary | retry.max: 3 -> 0 |
| rollout state | started, 25%, complete, reverted |
Two sources are easy to miss: automated changes (autoscaler, health-check flips, certificate rotation) and out-of-band writes (someone running a KV put, a direct write to the key-value config store, by hand). Catch the second by having each config store's own audit or watch stream feed the bus, not just the deployment pipeline.
2. Make the version visible in the victim's own signals
Each service reports the config version it has actually applied (not just the one that was published), as a gauge (a metric that reports the current value at each scrape, like a speedometer reading, rather than an ever-growing total) and as a label (a key/value tag attached to a metric, such as config_version=v143, that lets you filter and group by it) on its request metrics and trace spans (the individual timed steps of one request as it passes through services, recorded by distributed tracing). Keep that label's cardinality (the number of distinct values the label can take) low (the current and previous version, plus a hash for anything older), because an unbounded label multiplies your metrics series count (each unique combination of metric name and label values is stored as its own series, so more distinct values means more series to store and query). This is what turns "errors went up" into "errors went up only on hosts running v143", which is close to proof.
Discovery-specific signals that belong on the same dashboard:
- endpoint-set churn per service (instances added or removed per minute),
- name-resolution failures and "served from stale cache" counts from the client library,
- propagation lag and version skew: how many hosts are on each config version, and how long the newest version has taken to reach 100%.
3. Alert on symptoms, enrich with changes
The page fires on a multi-window burn-rate alert (for example burn rate above 14.4 over both the last hour and the last 5 minutes: the longer window shows the burn is statistically real and not a blip, the short window confirms it is still happening right now, so the page clears itself within minutes of a fix instead of continuing to fire on a burn that has already stopped), never on "a change happened". When it fires, the enricher queries the change index for events in a lookback window whose scope intersects the alerting service or its upstream dependencies (taken from the trace-derived dependency graph: which service calls which, inferred by following the trace spans that hop between them), and ranks them: same service beats a dependency, a change whose rollout curve matches the error curve beats one that does not, and a version split in the error metric is shown inline.
4. Catch it before a human needs to
For progressive rollouts, the rollout controller compares canary hosts with baseline hosts on error rate and latency and halts or reverts automatically on a statistically clear regression (for example: the canary's error rate is at least 3x the baseline cohort's, sustained for two consecutive minutes, over at least 200 requests, so a handful of unlucky samples cannot trigger it on their own). This is the most reliable detector because it compares two cohorts at the same moment under the same traffic, so a regression is not confused with an unrelated traffic spike.
Worked example: why scoping is the noise control
Assume 400 changes per day across the company (config, flags, routing, deploys, autoscaler) and a 30-minute lookback.
- Unscoped: 400 / 24 = 16.7 changes per hour, so about 8.3 changes fall in any 30-minute window. Every page would list eight suspects, most irrelevant. On-call learns to ignore the list.
- Scoped to the alerting service plus its direct dependencies, say 3% of all changes: 8.3 x 0.03 = 0.25 changes per window on average. Most pages now show zero or one suspect, so a listed change is meaningful, and "no changes in scope" is itself a useful answer ("rule out config, look elsewhere").
Then the version split confirms it: if hosts on v143 show a 4% error rate and hosts still on v142 show 0.1%, the change is the cause with no further investigation, and the runbook action is a revert of v143.
Trade-offs and pitfalls
- Alerting on changes directly is the noise trap. Changes are routine; only symptoms deserve a page. Changes are context.
- Published is not applied. If you record only the write, a stuck watcher or a long TTL hides the real moment the fleet changed. Record the applied version from each host.
- The lookback window is a tuning knob. Too short misses TTL-delayed effects (a 300-second DNS TTL alone adds 5 minutes); too long reintroduces noise. Set it per change kind from its known propagation delay.
- Cardinality: version labels on metrics are cheap if bounded, ruinous if every host carries a unique hash forever.
- Automation needs a brake too. Auto-revert must itself be rate-limited and logged as a change event, or two controllers can flap a setting back and forth.
You're tasked with selecting and driving adoption of a company-wide service discovery and configuration platform. Multiple teams prefer different tools (DNS, Consul, custom service mesh). How would you evaluate options technically and operationally, build a migration plan, address concerns such as operational burden and vendor lock-in, and gain cross-team buy-in while minimizing disruption?
Sample Answer
Direct answer
I would not run this as a tool bake-off. I would first write down what the company needs discovery to do (the requirements every team can agree on), score the options against those with weights the teams help set, and then commit to a layered standard: one authoritative service registry as the source of truth, DNS as the universal read interface so every language and legacy system works on day one, and a service mesh as an opt-in layer for teams that need mutual TLS and traffic shaping. Migration runs in reversible phases (dual-register, shadow, cut over by tier, decommission) led by a pilot with the most sceptical team, with success measured and published before anything is mandated.
Terms first
- Service discovery: how a caller finds the current network address of a service it wants to talk to.
- Service registry: the database of which instances of each service are alive and where (Consul is a common example; Kubernetes keeps its own).
- Service mesh: a proxy (a sidecar) runs next to every instance and handles discovery, retries, encryption and routing, programmed by a central control plane. Istio and Linkerd are examples.
- mTLS (mutual TLS): both sides of a connection prove their identity with certificates, not just the server.
- Vendor lock-in: when leaving a tool later would cost more than it is worth, usually because application code or data formats depend on it.
1. Evaluate: requirements first, then options
Run short interviews with each camp and turn their preferences into requirements. "We like DNS" usually means "it works with every client and needs no library"; "we want the mesh" usually means "we need mTLS and canary routing". Requirements, not tools, get weights.
| Criterion (weight) | Plain DNS | Consul registry (+ its DNS interface) | Custom service mesh |
|---|---|---|---|
| Works with every language and legacy host (25%) | yes | yes, via DNS; richer via API | needs a sidecar on every host |
| Health-aware, fast failover (20%) | no health, TTL-bound | health checks, seconds | health plus per-request retries |
| Multi-datacenter support (15%) | manual | built-in federation and failover queries (Consul's own mechanism for linking each datacenter's cluster to the others and automatically querying a nearby one when the local cluster has no healthy instances) | depends on the build |
| Security: mTLS, identity (15%) | none | optional (Consul Connect: Consul's built-in service-mesh feature that adds mutual TLS between services) | core feature |
| Operational burden on platform team (15%) | lowest | moderate: a consensus cluster to run | highest: proxies, control plane, certs |
| Exit cost / lock-in (10%) | none | low if apps only use DNS names | high for a custom build: you own it forever |
The operational side matters as much as the technical: who is on call for it, how upgrades happen, what happens when it is down (does traffic keep flowing on cached data, or does everything stop?), and whether the team that built the custom mesh is still staffed to maintain it. A custom mesh scores well on features and badly on bus factor (how many key people could leave or be unavailable before nobody left understands the system).
Turning that into a decision: score each cell 0 (worst) to 10 (best), consistent with the qualitative read above, multiply by its criterion's weight, and sum:
| Criterion (weight) | Plain DNS | Consul registry | Custom service mesh |
|---|---|---|---|
| Works with every language (25%) | 10 | 9 | 5 |
| Health-aware failover (20%) | 2 | 8 | 9 |
| Multi-datacenter support (15%) | 3 | 9 | 6 |
| Security: mTLS, identity (15%) | 1 | 5 | 9 |
| Operational burden, inverted so lower burden scores higher (15%) | 9 | 6 | 2 |
| Exit cost / lock-in, inverted so lower lock-in scores higher (10%) | 10 | 8 | 2 |
| Weighted total | 0.25x10 + 0.20x2 + 0.15x3 + 0.15x1 + 0.15x9 + 0.10x10 = 5.85 | 0.25x9 + 0.20x8 + 0.15x9 + 0.15x5 + 0.15x6 + 0.10x8 = 7.65 | 0.25x5 + 0.20x9 + 0.15x6 + 0.15x9 + 0.15x2 + 0.10x2 = 5.80 |
Consul wins clearly, 7.65 against 5.85 and 5.80, which is why it becomes the source of truth below rather than a coin flip between three close options. DNS and the mesh land near each other for opposite reasons: DNS wins on universal compatibility and zero lock-in but loses hard on security and failover; the mesh wins on security and failover but loses hard on operational burden and lock-in. That is exactly why the recommendation layers them instead of picking one outright: Consul underneath for its lead on health-awareness and multi-datacenter support, DNS names as the interface every client already speaks, and the mesh opt-in only where a team's own security or failover need would flip its individual score.
Recommendation for a typical mixed estate: Consul (or the platform's native registry) as source of truth, DNS names as the contract applications code against, mesh opt-in. What would flip it: if more than roughly 80% of workloads already run on Kubernetes and a regulator requires mTLS everywhere, standardise on a supported mesh as the default instead, and treat DNS as the legacy bridge.
2. Migration plan
(Two terms used below: tier-1 means the most critical, highest-traffic services, where an outage matters most; the long tail means the large number of smaller, lower-priority services that are slow to migrate voluntarily.)
- Contract first. Publish the naming scheme (
<service>.service.<dc>.<domain>), health-check requirements, and the rule that application code references names, never tool-specific APIs. This is the lock-in defence: if apps only know DNS names, the registry behind them can be swapped. - Dual registration. Services register in both old and new systems, automatically from the deploy pipeline, so nobody hand-edits two places. Nothing reads the new system yet.
- Shadow reads and diffing. A job resolves every service through both systems and reports mismatches. Cutover of a service is blocked until its diff has been clean for a week.
- Cut over by tier. Start with internal tools, then non-critical services, then tier-1. Each cutover is a config flag per caller, so rollback is a flag flip, not a redeploy.
- Decommission the old path per service once its traffic on the old path is zero for 30 days, with a published date.
Worked example: sizing the timeline
Say 300 services owned by 40 teams. The pilot (weeks 1 to 6) moves 10 services with the platform team doing the work. After that, a paved-road script means a team can move one service in about half a day, and the platform team can support about 15 cutovers per week without degrading review quality.
- Remaining after pilot: 300 - 10 = 290 services.
- At 15 per week: 290 / 15 = 19.3, so 20 weeks of rollout.
- Total: 6 + 20 = 26 weeks, roughly two quarters, plus the 30-day decommission tail.
State it as a plan with that arithmetic, so leadership can see what adding or removing platform capacity does to the date.
3. Addressing the specific concerns
- Operational burden: the platform team owns the registry cluster, its upgrades and on-call, with a published SLO. Application teams own only their health checks. Quantify it: a 5-server consensus cluster per datacenter, which tolerates the loss of 2 servers (a write only needs a majority, 3 of the 5, to agree before it commits; losing any 2 still leaves 3, a majority, so the cluster keeps accepting writes, while losing 3 would leave only 2, which can no longer form one).
- Vendor lock-in: the primary defence is contractual, not technical: apps depend on DNS names and standard health endpoints, not on a client SDK, so the registry behind those names can be swapped without touching application code. As a secondary, deeper defence inside the mesh itself, it also uses open standards (Envoy's xDS configuration APIs, a standard protocol for pushing routing config to sidecar proxies, so the proxies do not have to change even if the control plane does; and SPIFFE identities, a vendor-neutral standard for verifiable service identity, so certificates are not tied to one mesh vendor) so even the mesh's control plane is replaceable. Write down the exit plan now, with its cost.
- "Our custom mesh works fine": respect the investment. Offer to make it a candidate for the opt-in mesh layer if it passes the same criteria, and ask its owners to lead the mesh working group. Most resistance is about losing ownership, not about technology.
4. Gaining buy-in
- Publish the decision as an RFC (request for comments) with the weighted scoring, and let teams challenge the weights before the scores. Changing a weight is a cheap, visible concession.
- Pilot with the loudest sceptic. If their pain is solved, that is the most credible endorsement you can get.
- Make the paved road (the supported, recommended way of doing something, made deliberately the easiest path) cheaper than the old road: generated configs, dashboards and alerts for free on the new platform; the old one gets security fixes only.
- Measure and publish: services migrated, lookup failure rate, time to failover, incidents attributable to discovery, before and after.
- Escalate last. Executive mandate is for the long tail after the default is clearly better, not for the opening move.
Pitfalls
- Choosing by committee vote instead of weighted requirements: the loudest team wins, and the others disengage.
- Big-bang cutover: no rollback, and one bad week kills trust in the platform for years.
- Letting apps import the registry's client library "just for one feature": that is how lock-in re-enters.
- Forgetting non-Kubernetes workloads (VMs, databases, batch jobs): DNS is what keeps them in the plan.
Explain DNS-based service discovery and how DNS caching and TTLs affect failover and load distribution. If you had to choose between a 60-second and a 300-second TTL for a service record, which would you pick and why, and what else would you need to account for to make that choice actually hold up in practice?
Sample Answer
Direct answer
DNS-based service discovery means clients find a service by resolving a name such as orders.internal.example.com to the IP addresses of its healthy instances. Because every resolver and client caches the answer for the record's TTL (time-to-live), the TTL sets how long clients may keep sending traffic to an address you have already removed: it is a floor on failover time and a limit on how quickly load shifts. For a service record that must fail over, I would pick 60 seconds. The extra query load is small and a 300-second TTL means up to five minutes of errors after an instance or region dies. But a 60-second TTL only holds if clients actually honour it, so the rest of the job is making sure they do.
How DNS-based discovery works
- Instances register (directly, or via a health-checking DNS provider such as Consul's DNS interface, Kubernetes' CoreDNS, or a cloud DNS service with health checks).
- A client asks its local stub resolver (the small resolver library in the OS or language runtime), which asks a recursive resolver (the caching server, e.g. the node-local cache or the VPC (Virtual Private Cloud) resolver), which asks the authoritative server (the one that actually owns the zone, meaning the portion of the DNS namespace, such as
internal.example.com, that this server holds the real records for). - The answer, say three A records (address records, each mapping the name to one IPv4 address), is cached at every layer for the TTL. The client picks one address, usually the first, and connects.
Nothing tells a client that an address went bad: it only learns on its next lookup after the cached copy expires.
How caching and TTLs affect failover
Worst-case time for all clients to stop using a dead address is roughly:
failover time ≈ health-check detection time + TTL (+ any extra caching the client adds)
With a health check that marks an instance down after 3 failures at 10-second intervals (30 seconds):
| TTL | Worst-case failover | Lookups per second from 2,000 caching client hosts (one lookup per TTL each) |
|---|---|---|
| 60 s | 30 + 60 = 90 s | 2,000 / 60 ≈ 33 |
| 300 s | 30 + 300 = 330 s | 2,000 / 300 ≈ 6.7 |
The 60-second TTL costs about 26 more queries per second, which any resolver absorbs trivially, and cuts the worst-case failover from 5.5 minutes to 1.5 minutes. Query volume scales linearly with 1/TTL, so going lower (5 seconds) is 400 queries per second for the same fleet and starts to matter for resolvers and for paid public DNS.
How caching affects load distribution
DNS balances resolvers, not requests. If one large recursive resolver (a shared NAT, meaning a network-address-translation gateway that many separate devices sit behind and also route their DNS queries through, or a corporate DNS server) serves 500 clients, all 500 may receive the same cached answer in the same order and pile onto the first IP. Longer TTLs make this worse, because a skewed answer persists longer; round-robin record ordering, returning a random subset per response, or client-side random selection among all returned addresses spreads it out. Adding capacity has the same lag as removing it: new instances receive traffic only as caches expire.
What else must be true for the 60-second choice to hold
- Clients must honour the TTL. Language runtimes add their own caches. The JVM's positive cache (a positive cache remembers successful lookups; the negative cache below remembers failures) is governed by the
networkaddress.cache.ttlsecurity property, whose default is implementation-specific; set it explicitly (for example to 60) instead of trusting it. Some resolvers also enforce a minimum TTL that silently raises yours. - Clients must re-resolve at all. A connection pool or an HTTP/2 keep-alive connection (reusing one already-open connection for many requests instead of reconnecting for each one) opened to an IP will keep using that IP for hours, regardless of DNS TTL. Cap connection lifetime (e.g. recycle connections every few minutes) and re-resolve on reconnect, or failover never happens for long-lived clients.
- DNS must only return healthy addresses. The TTL is pointless if the authoritative server keeps handing out the dead IP; the records must be driven by health checks.
- Negative caching. If a lookup returns "no such name" (for example during a brief deregister-everything incident), resolvers cache that negative answer for a time taken from the zone's SOA (start of authority) record, per RFC 2308, and Java's
networkaddress.cache.negative.ttldefaults to 10 seconds. A long negative TTL turns a 5-second blip into minutes of "host not found". Keep it short for service zones. - Clients must retry on another address. Even with perfect TTLs, requests fail during the detection window. Returning several records and having clients try the next address on connection failure turns an outage into a latency bump.
- Lower TTLs before planned changes. A TTL only shortens after the old one expires, so for a planned migration drop the TTL a full old-TTL period ahead of time.
When I would pick 300 seconds instead
For records that rarely change and front something that fails over by other means (a load balancer's stable virtual IP, an address the load balancer itself keeps fixed while swapping which physical instance answers behind it, or an anycast address, the same IP announced from multiple physical locations so network routing sends each client to the nearest live one and simply stops routing to a failed location, no DNS change needed), 300 seconds or more is fine: the address itself never dies, so failover does not depend on DNS, and a longer TTL cuts query volume and shields you from brief DNS outages.
Trade-offs and pitfalls
- A very low TTL (under 10 seconds) makes DNS itself a hard dependency: if the resolver hiccups, every client fails its lookups at once.
- DNS offers no per-request load awareness and no health-based retries; for east-west traffic (traffic between your own services inside the system, as opposed to north-south traffic coming in from outside clients) between microservices that need fast failover, client-side load balancing (the calling service itself holds the instance list and picks one per request, no DNS or proxy hop involved) or a service mesh (a proxy next to each service that receives endpoint updates by streaming) reacts in seconds instead of a TTL period.
- Assuming "TTL 60 means failover in 60 seconds" ignores detection time, runtime caches and pooled connections, which is where most real incidents come from.
Design a zero-downtime secret rotation process for thousands of running containers that avoids secret leakage and guarantees minimal exposure to old secrets. Explain how you would distribute new secrets, revoke old secrets, coordinate dependent services (databases, third-party APIs), and audit the rotation. Discuss use of short-lived tokens, TLS, key-version headers, and potential race conditions.
Sample Answer
Direct answer
Zero-downtime rotation rests on one rule: there must always be a moment when both the old and the new secret are accepted, and the old one is retired only after you have evidence nobody still uses it. So every rotation runs in four ordered phases: make the new secret acceptable to whoever verifies it, distribute it to every consumer, confirm the consumers have switched, and only then revoke the old one. I would push most of the fleet onto short-lived, per-instance credentials issued by a secrets manager (such as HashiCorp Vault) so that "rotation" becomes routine expiry, and run the four-phase process only for the long-lived secrets that cannot be made dynamic (third-party API keys, signing keys, a certificate authority or CA).
Terms used below
- Secret: anything that grants access: a database password, an API key, a TLS private key, a token-signing key.
- Short-lived (dynamic) credential: a credential minted on request for one workload, with a built-in expiry (its lease or TTL, time-to-live). Vault's database secrets engine, for example, creates a new database user per lease and drops it when the lease ends.
- Dual-valid window: the period when both old and new secrets work. Its length is the core design parameter.
- Key version header: a label sent alongside a signed or encrypted message that says which key produced it, such as the
kid(key ID) header in a JSON Web Token (JWT). It lets a verifier hold several keys at once and pick the right one.
The rotation state machine
stateDiagram-v2
[*] --> Staged: generate v2, store encrypted
Staged --> Accepted: verifier trusts v1 AND v2
Accepted --> Distributed: consumers fetch v2
Distributed --> Verified: telemetry shows no v1 use
Verified --> Revoked: v1 disabled at verifier
Revoked --> [*]
Distributed --> Accepted: rollback (consumers back to v1)
Each arrow is a gate with a check, not a timer alone. Rollback is possible right up to Revoked, and never after it, which is why the evidence gate before revocation matters most.
1. Distributing new secrets
- Pull, never bake. The core idea is that the workload's own platform identity, something the platform already hands it for free, doubles as its credential to the secrets store, so nothing has to be pre-shared. Two common implementations: a Kubernetes service-account token (a signed token the cluster issues to each pod) presented through Vault's Kubernetes auth method (Vault's plugin that verifies that token with the cluster), or a cloud workload identity (the equivalent for a VM or serverless task). Containers authenticate this way and fetch secrets at runtime. Nothing lives in the image or in environment variables baked into a deployment spec.
- A local agent per pod. A sidecar (a second container that runs alongside the application container in the same pod, sharing its network and storage) or init container (a container that runs once before the main container starts, then exits), such as Vault Agent, the Secrets Store CSI Driver (a Kubernetes storage plugin that mounts secrets from an external store as files), or a mesh agent (the local proxy a service mesh, a layer that manages service-to-service networking and certificates for every workload, installs next to each one) for certificates, fetches, renews and writes secrets to an in-memory volume (
tmpfs, so they never touch disk) and re-renders the file when a new version appears. The application watches the file and reloads. - Environment variables are the trap. A process reads its environment once at start. Kubernetes updates Secrets mounted as volumes eventually, but does not update values injected as environment variables or files mounted with
subPath. Those require a restart, which turns every rotation into a fleet-wide rolling restart. - Stagger the fetch. Consumers refresh on their own schedule with jitter (random offset) rather than all at once when a new version lands.
2. Coordinating dependent services
Order matters, and the rule is: the side that verifies changes first, the side that presents changes second.
| Dependency | How to get a dual-valid window | Revocation |
|---|---|---|
| Database you control | Preferred: dynamic per-lease users, so there is nothing shared to rotate. Otherwise two users (app_a, app_b): rotate the password of the one not in use, switch consumers to it, then rotate the other next time. | Drop or lock the old user and terminate its sessions: in PostgreSQL, changing a password does not disconnect sessions already logged in. |
| Third-party API key | Most providers allow two active keys. Create key 2, distribute, watch the provider's usage report or your own egress logs until key 1 is idle, delete key 1. | Delete at the provider. If the provider allows only one key, the window is zero: schedule a short maintenance window or put a proxy in front that holds the key. |
| Token-signing key (JWT) | Publish the new public key in the JSON Web Key Set (JWKS, the published list of keys verifiers trust) first, wait for verifiers' caches to refresh, then start signing with the new kid. | Remove the old key from the set only after the longest token lifetime has passed. |
| TLS certificates | Short-lived certs (hours to days) from an internal certificate authority, issued automatically by a mesh or an agent and hot-reloaded. | Expiry does the revoking. For a CA rotation, distribute a trust bundle (the set of CA, certificate authority, certificates a verifier is configured to trust) holding both CAs first, then reissue leaf certs (the end-entity certificates issued to individual services, as opposed to the CA's own certificate) from the new CA, then remove the old CA from the bundle. |
3. Guaranteeing minimal exposure to old secrets
"Exposure" means the time an old secret remains usable after we decided to replace it. The window must cover the slowest consumer, and nothing more:
Wdual=Trefresh+Tconn+Tmarginwhere T_refresh is the longest time for a consumer to pick up the new version, T_conn is the longest a pooled connection opened with the old secret stays open, and T_margin is a buffer added on top of the other two so the revocation decision does not hinge on borderline telemetry.
Key-version headers in practice
Anything signed or encrypted should say which key produced it, so verifiers and decryptors can hold several keys during a rotation:
- Tokens: the
kidin the JWT header selects the verification key from the key set. - Encrypted data at rest: store the key version next to each ciphertext (for example a
v2:prefix), so records written before the rotation still decrypt with v1 while new writes use v2, and a background job re-encrypts old records before v1 is retired. Vault's transit engine formats its ciphertexts this way. - Webhooks and service-to-service signatures: send a header naming the key version, and let the receiver accept the current and previous version during the window.
Without a version label, a verifier has to try every key it holds, and it cannot tell you from logs who is still using the old one, which removes the evidence the revocation gate depends on.
4. Auditing the rotation
- Store-side audit: every read of every secret version, by which identity, from where. In Vault, audit devices (file, syslog, socket) log every request; Vault refuses to serve requests if it cannot write to at least one enabled audit device, so auditing cannot be silently lost.
- Usage-side evidence: the verifier's logs of which key version was presented (DB login user, API key ID,
kidof verified tokens). This is the gate for revocation: "zero v1 uses in the last N minutes across all verifiers". - Rotation record: who or what triggered it, version numbers, the time each phase gate passed, and whether it rolled back. Alert when a secret passes its maximum age without rotating.
- Never log the value, only version IDs or a short hash.
5. Race conditions and how each is closed
- Consumer ahead of verifier. A pod fetches v2 before the database accepts it and fails to log in. Closed by ordering: the verifier accepts v2 before v2 is readable by consumers (the
StagedtoAcceptedgate). - Two rotators at once. A scheduled rotation and a manual one both generate a "v2", one overwrites the other, and half the fleet holds a secret that no longer exists. Closed by a compare-and-set write (a write that only succeeds if the stored value still matches what was last read, so two writers racing to change it cannot silently clobber each other) on the version number (write v3 only if the current version is still v2) or a lock.
- Revoke before drain. v1 is disabled while pooled connections or cached tokens still use it. Closed by the telemetry gate plus the connection-lifetime term in the window formula.
- Rollback re-enables a revoked secret. Rolling back after revocation would resurrect a secret you may be rotating because it leaked. Closed by making rollback only possible before
Revoked; after it, roll forward to v3. - Restart storm. A new version triggers every pod to restart or re-fetch at once, overloading the secrets store. Closed by jittered refresh and by avoiding restart-based delivery.
Worked example: 5,000 containers on one PostgreSQL cluster
Inputs (illustrative, chosen to show the arithmetic): consumers poll for a new version every 5 minutes; the connection pool recycles connections at most every 30 minutes; margin 10 minutes.
Wdual=5+30+10=45 minutesSo the old password is revoked no earlier than 45 minutes after distribution, and only if the database's login telemetry shows zero v1 logins for the last 10 minutes. If you shortened the pool's maximum connection lifetime to 10 minutes, the window drops to 25 minutes: connection lifetime, not secret distribution, is usually the dominant term.
Load on the secrets store if the fleet moves to dynamic credentials with a 1-hour lease renewed at half-life (a common convention: renew once half the lease's time remains, so one missed renewal still leaves margin before expiry), that is, every 30 minutes, 1,800 s:
1800 s5000≈2.8 requests/sThat is trivial. The risk is the burst: if all 5,000 pods restart within 60 seconds after an outage, that is 5000 / 60 ≈ 83 requests/s of new credential creation, and each creation is also a CREATE ROLE on the database. Plan for the burst: rate-limit creation, jitter start-up, and size the database's connection limits for the extra users briefly alive during overlap.
Trade-offs and pitfalls
- Dynamic credentials vs a shared rotated secret. Dynamic per-instance credentials give the smallest blast radius (how much is exposed when one thing goes wrong) (one leaked credential is one pod for one lease) and make revocation per instance, but they make the secrets store a hard dependency for every start-up. Mitigate with long enough leases to ride out a short store outage and a highly available store. I would still choose them for anything we control.
- Short TTLs are not free. A 5-minute TTL means a 5-minute store outage breaks everyone. Pick TTLs that exceed your store's realistic recovery time.
- In-place rotation (one credential, changed in place) always has a gap, because the change and the consumers' reload cannot be simultaneous. Use two credentials or dynamic ones.
- "Revocation" that only stops new logins is incomplete. Kill existing sessions and invalidate caches, or a leaked credential keeps working through an open connection.
- Emergency rotation is a different mode. When a secret has leaked, you shrink the dual-valid window deliberately and accept some errors, because leaving the old secret alive is worse than a brief outage. Decide that policy before the incident.
Unlock Full Question Bank
Get access to all 39 Service Discovery and Configuration Management interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.