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 secrets distribution architecture for containerized workloads that supports key rotation without requiring container restarts. Constraints: thousands of containers, least-privilege access, audit logs, node-level caching, and low-latency retrieval. Consider using Vault, sidecars, node agents, and Kubernetes secrets; explain trade-offs for each.
Sample Answer
Direct answer
Use Vault as the single source of truth, have every pod authenticate as itself using its Kubernetes service account token, and deliver secrets as files on an in-memory volume written by a node-level agent (the Secrets Store CSI Driver with the Vault provider), with rotation enabled. The application re-reads the file when it changes, which is what makes rotation work without a restart. Prefer short-lived dynamic credentials (Vault generates a database user per workload with a lease) over long-lived static secrets. Keep Vault Agent sidecars for the minority of workloads that need templating or per-pod lease renewal, and do not use plain Kubernetes Secrets as the source of truth for sensitive material.
Terms
- Vault: HashiCorp's secrets manager. It stores secrets, issues dynamic secrets (credentials created on demand with an expiry), and writes an audit log of every request.
- Lease / TTL: a dynamic secret comes with a time-to-live. The holder must renew it before expiry or get a new one; Vault revokes it afterwards.
- Least privilege: each workload can read only the secrets it needs, and nothing else.
- Kubernetes auth method: a pod presents its service account token (a signed JWT, JSON Web Token) to Vault; Vault verifies it with the Kubernetes API and maps the service account to a Vault policy.
- CSI (Container Storage Interface) driver: a node-level plugin that mounts volumes into pods. The Secrets Store CSI Driver mounts secrets fetched from an external store as files.
- DaemonSet: a Kubernetes workload type that runs exactly one copy of a pod on every node (or every matching node), unlike a Deployment which runs a chosen number of copies wherever the scheduler likes. It is the standard way to run one node-level agent per machine.
- Audience-bound token: a service account token that is only valid for a declared recipient (Vault, here); even if it leaked, another service could not use it to authenticate as this pod to something else.
- Alpha (Kubernetes feature stage): an early, experimental stage of a feature. It can change behaviour or be removed between versions with no long-term compatibility guarantee, and many production platforms disable alpha features by policy.
- Rotation: replacing a credential with a new one while the old one is still valid for an overlap period, so nothing breaks mid-swap.
The four options, compared
| Option | How it works | Rotation without restart | Least privilege | Cost at thousands of pods |
|---|---|---|---|---|
| Kubernetes Secrets | Stored in etcd; mounted as files or env vars | Volume mounts update eventually (the kubelet sync period, how often the node agent that manages each node reconciles state, plus cache delay); env vars never update (they are set once at container start and never revisited); subPath mounts (mounting a single file out of a volume rather than the whole directory) never update at all, because the file is copied in once rather than kept in sync | Namespace-level RBAC (role-based access control); by default stored unencrypted in etcd unless encryption at rest (encrypting the data as stored on disk, not just in transit) is configured | Cheapest; no extra processes |
| Vault Agent sidecar | Injected container per pod authenticates, renews leases, renders templates (a config file with placeholders like {{ secret "database/creds/payments-ro" }} that the agent fills in with the live value) to a shared in-memory volume | Yes: agent re-renders the file | Per pod, via the pod's own service account | One extra container per pod: memory and CPU scale with pod count |
| Node agent (CSI driver + Vault provider) | One DaemonSet pod per node fetches secrets for pods on that node and mounts them | Yes, with rotation enabled (--enable-secret-rotation=true; the driver re-fetches on --rotation-poll-interval, default 2 minutes). The rotation feature is alpha in the driver | Per pod, if the provider authenticates with the pod's own token | One agent per node: scales with node count |
| Vault Secrets Operator / sync to K8s Secrets (a controller that watches Vault and copies values into ordinary Kubernetes Secrets, so existing apps that only know how to read a K8s Secret keep working unmodified) | Controller copies Vault secrets into Kubernetes Secrets | Inherits K8s Secret behaviour | Weakened: the copy is readable by anything with Secret read in that namespace | Low, but secrets now live in two places |
The design
flowchart LR
Pod[App pod with service account] -->|mounts in-memory volume| CSI[CSI driver on node]
CSI -->|pod's own SA token| Prov[Vault provider on node]
Prov -->|Kubernetes auth login| Vault[Vault cluster]
Vault -->|verify token| K8s[Kubernetes API]
Vault -->|policy per service account| Prov
Vault --> Audit[Audit log sink]
Prov -->|write files, re-fetch on rotation| Pod
- Identity. Every workload gets its own service account. The CSI driver passes the pod's projected service account token (a short-lived, auto-rotated token Kubernetes mounts into the pod for exactly this purpose, restricted to Vault as its audience) to the provider. Vault's Kubernetes auth role maps
namespace=payments, sa=payments-apito a policy that allows onlydatabase/creds/payments-ro(thedatabasesecrets engine, generating a dynamic, read-only credential namedpayments-ro) andkv/data/payments/*(everything under thepaymentsfolder of the plain key-value secrets engine). - Delivery. Secrets land as files in a
tmpfs(memory-backed) volume, never on node disk and never in environment variables (env vars leak into crash dumps and child processes: by default, every process an application spawns inherits a copy of its parent's environment, so a secret sitting in an env var ends up in tools and scripts that have no reason to see it, and cannot change without a restart). - Rotation without restarts. Three things need to work together:
- Delivery side: the CSI driver re-fetches on its poll interval and rewrites the file when Vault returns a new value.
- Application side: the app watches the file (inotify, the Linux file-change notification API, or re-reading on a timer) and swaps its connection pool or client credentials in place. This is the part teams forget: an app that reads a password once at startup will keep using the old one until it is revoked, and then fail. Provide a shared library that does "watch file, rebuild client, drain old connections" so each team does not reimplement it.
- Overlap: rotate with two valid credentials at once (Vault's database engine issues a new user while the old lease is still valid; static secrets should support "current" and "previous"), so a pod that has not yet re-read the file keeps working.
- Node-level caching. Whatever caches on the node (the provider itself, or a node-local Vault Agent used as a caching proxy in front of Vault) must key entries by identity plus path, not by path alone, so two pods with different service accounts on the same node never share an entry. Pods of the same service on the same node can share, which is where the cache saves Vault traffic. A cache keyed only by secret path would let a pod read a secret another pod on the node fetched: a confused-deputy bug, where the agent's own broad access is used on behalf of a caller who should not have it.
- Audit. Vault's audit device (a pluggable log sink Vault writes every request to, typically shipped into your normal log pipeline) logs every login and read with the requesting identity. Because each pod authenticates as its own service account, the log answers "which workload read this secret", not just "the node agent did".
Worked example: load and footprint
Assume 5,000 containers, each using 3 dynamic secrets with a 1-hour TTL, renewed at two-thirds of the TTL (40 minutes = 2,400 s).
- Vault renewal/issue rate: 5,000 × 3 / 2,400 s = 6.25 requests per second in steady state. That is modest; the danger is not the average but a thundering herd (a mass of clients all making the same request at the same instant, turning a trivial average load into a brief spike large enough to overwhelm the target) when a node pool restarts and hundreds of pods log in at once. Add jitter to renewal times and rate-limit logins per node.
- Footprint, using an assumed budget of 64 MiB per Vault Agent sidecar: 5,000 × 64 MiB = 320,000 MiB, about 312.5 GiB of cluster memory just for sidecars. With 200 nodes and an assumed 128 MiB per node agent: 200 × 128 MiB = 25,600 MiB, about 25 GiB. Measure the real figures on your workloads; the point is the scaling shape (per pod vs per node), which is why the node agent is the default here.
- Latency: reads come from a local file, so the hot path never touches the network. Vault is only on the refresh path.
Trade-offs and what would change the choice
- Node agent risk: a larger blast radius per node. A compromised node agent can request secrets for any pod scheduled on that node (it holds their tokens). Mitigate with node isolation for sensitive workloads (dedicated node pools for payments) and short token lifetimes.
- Alpha rotation in the CSI driver. If your platform policy forbids alpha features, use Vault Agent sidecars for workloads that must rotate, and the CSI driver only for secrets that change rarely.
- Vault availability becomes critical. Run it highly available, and make sure a Vault outage only blocks new secrets, not running pods: files already on the volume keep working until their credentials expire, so choose TTLs longer than your realistic Vault recovery time.
- Plain Kubernetes Secrets are acceptable for low-sensitivity, rarely-rotated values if encryption at rest and tight RBAC are configured. They are not acceptable as the only protection for database or payment credentials.
- When sidecars win: workloads needing complex templates (rendering one full config file that weaves together several secrets and static values, not just dropping each secret in its own file), or per-pod lease renewal for dynamic credentials that must be revoked the moment the pod dies.
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.
Compare Consul, etcd, ZooKeeper, and Eureka as backends for service discovery and configuration storage. Which are CP and which are AP, and what does that mean operationally, for example ZooKeeper being unavailable during leader election versus Eureka's self-preservation mode serving stale data during a partition? Discuss watch/notify semantics, performance characteristics, operational complexity, and typical failure modes.
Sample Answer
Direct answer
etcd, ZooKeeper and Consul's server cluster are CP systems: they use a consensus protocol (an algorithm, such as Raft or ZAB, that gets every replica to agree on one ordered history of writes, normally by electing a single leader that orders and replicates each write before it counts as committed, which is why "no leader" means "no writes" in these systems), so during a network partition the side without a majority stops accepting writes rather than risk disagreeing. Eureka is AP: every server accepts registrations and keeps answering during a partition, even if the answer is stale. Operationally, CP means "correct or unavailable" and AP means "always answers, possibly wrong". My default is a CP store for configuration, locks and leader election, and discovery clients that tolerate staleness (cache the last good answer, retry on a different instance), because for routing a slightly old list beats no list.
CP and AP in plain terms
The CAP theorem says that when a network partition splits a cluster (some nodes cannot talk to others), a replicated system must choose between consistency (every read sees the latest write, or fails) and availability (every request gets an answer). CP systems choose consistency, AP systems choose availability. When there is no partition, both behave well; the choice only shows during failures, which is exactly when you are debugging at 3 a.m.
Quorum is the majority needed to make a decision: 3 of 5 nodes, 2 of 3. A 5-node CP cluster survives 2 node failures; a partition that splits it 3 and 2 leaves the 3-node side working and the 2-node side unable to write.
The four systems side by side
The table below is dense; for the CP-versus-AP question itself, the first three rows (Replication, CAP stance, Reads) carry the answer. The remaining rows (health/liveness through operational load) are what you'd use to justify picking one system over another, not to argue CP versus AP.
| etcd | ZooKeeper | Consul | Eureka | |
|---|---|---|---|---|
| Replication | Raft consensus | ZAB (ZooKeeper Atomic Broadcast) consensus | Raft among servers; gossip (Serf) among all agents for membership, where each node regularly swaps "who is alive" news with a few random peers | Peer-to-peer copying between servers, no consensus |
| CAP stance | CP | CP | CP for the catalog and KV (key-value) store; reads can opt into stale mode | AP |
| Reads | Linearizable (always latest) by default; serializable (local, possibly stale) on request | Served by whichever server the client is connected to, so possibly stale; call sync() first to catch up | default (strong except briefly during leader changes), consistent (strong, extra round trip), stale (any server, works even with no leader) | From the local registry copy, refreshed every 30 s by delta (an incremental update, not a full resend) |
| Watch / notify | Streaming watch from a given revision; resumable after disconnect; all events ordered, none skipped | Standard watches are one-time triggers: re-register after each event and you can miss intermediate changes. Persistent and recursive watches (addWatch, since 3.6) fix that | Blocking queries: long-poll (a request the server holds open, without answering, until something changes or a timeout passes, instead of the client asking repeatedly) with ?index= from the last X-Consul-Index (a response header carrying the current index, which the client echoes back to mean "tell me only about changes after this point"); a return does not guarantee a change, and an index that goes backwards must reset to 0 | None: clients poll for deltas (an incremental update containing just what changed, not the whole registry) every 30 s |
| Health / liveness | Leases (a TTL, time-to-live, the client must keep alive) | Ephemeral nodes deleted when the client's session expires | Agent runs health checks (HTTP, TCP, script) locally on each node | Client heartbeats every 30 s; evicted after 90 s without one |
| Built for | Kubernetes state, config, coordination | Coordination for Hadoop-era systems | Service discovery across datacenters, with DNS and health checks built in | Service registry for Spring Cloud / Netflix JVM stacks (a family of Java frameworks for building microservices; Eureka was originally Netflix's own registry) |
| Performance shape | Every write waits for the leader to replicate to a majority and fsync to disk (force the write out to physical disk, not just an in-memory buffer), so disk and network latency set write speed; linearizable reads also check with the leader, serializable reads scale with members | Reads served locally, so adding servers (or non-voting observers, ZooKeeper servers that receive the data stream and serve reads but don't count toward quorum) scales reads; writes all go through the leader; the whole data set must fit in memory | Writes go through the Raft leader; stale reads spread across all servers; many blocking queries on a large service list cost server CPU | Reads come from each client's local copy, so they are nearly free; registrations copy between servers asynchronously, so they are cheap but slow to converge |
| Operational load | Low-moderate: 3 or 5 members, watch disk latency and defragment (reclaim disk space after old data has been compacted away, since the storage file doesn't shrink on its own); 2 GiB default storage quota (8 GiB suggested maximum) | Moderate-high: JVM tuning (adjusting the Java Virtual Machine's memory and garbage-collection settings, since ZooKeeper runs on the JVM and a mistuned JVM causes long pauses), whole data tree held in memory, session timeouts (how long the server waits for a disconnected client to reconnect before treating its ephemeral state as gone) to tune | Moderate: servers plus an agent on every node, ACLs (access control lists), gossip encryption | Low to run, but needs clients that handle staleness |
What CP vs AP means during a partition
ZooKeeper during leader election. When the leader dies or is cut off, the ensemble cannot accept writes until a new leader is elected by a quorum. Clients connected to servers on the minority side get disconnected and, if the session times out, their ephemeral nodes (the entries that represent "this instance is alive") are deleted. A discovery design built on ephemeral nodes can therefore remove healthy instances because of a partition between the instances and ZooKeeper, not because the instances died.
Eureka self-preservation. Eureka expects heartbeats at a steady rate. If renewals fall below a threshold (by default, when more than 15% of registered instances are overdue), the server assumes the problem is the network, not mass instance death, and stops evicting anyone. The registry then serves dead instances until renewals recover. That is the AP trade: during a real mass failure, clients keep receiving addresses that no longer answer.
etcd. The minority side refuses writes and, with default linearizable reads, refuses reads too. A Kubernetes control plane (the components that make scheduling and management decisions, such as the API server and scheduler) on the minority side cannot schedule anything, but the workloads already running keep running, because the data plane (the running workloads themselves and the networking that serves their live traffic) does not depend on etcd for every request.
Consul. Writes to the catalog need the Raft leader. Clients that use stale reads (and Consul's DNS interface allows stale reads by default) keep getting answers from any server, even with no leader, so discovery continues while registration of new instances pauses.
Worked example: when does Eureka stop evicting?
100 instances, heartbeat every 30 s, so the server expects
100×3060=200 renewals per minuteand with the default 85% threshold it enters self-preservation below
0.85×200=170 renewals per minute(Eureka's exact computation of the expected count has more detail, but this is the shape.) If a switch fault cuts off 20 instances, renewals drop to 80 × 2 = 160, below 170, so nothing is evicted. If those 20 instances were genuinely dead, a client choosing uniformly at random hits a dead one 20% of the time until they return or an operator acts. The client-side mitigation is a short connect timeout plus a retry on a different instance: with independent random picks, two failures in a row happen 0.2 × 0.2 = 4% of the time. The same fault on ZooKeeper would have taken the other path: those 20 instances' sessions expire and they vanish from the registry, which is correct if they are dead and a self-inflicted outage if only their link to ZooKeeper failed.
Failure modes to name in an interview
- etcd: slow disk (fsync latency) causes leader elections; storage quota reached puts the cluster into alarm mode where it rejects writes until you compact (discard old key revisions no longer needed) and defragment; large watch fan-out on one prefix loads the leader.
- ZooKeeper: long JVM garbage-collection pauses look like dead servers or expired sessions; a "herd effect" when many clients watch one node and all wake up at once.
- Consul: gossip misconfiguration (encryption keys, ports blocked) causing agents to flap between alive and failed; a lost quorum of servers blocks all registrations; a very large catalog makes blocking queries on the whole service list expensive.
- Eureka: stale entries during self-preservation; up to roughly 90 seconds, three heartbeat intervals at the default 30-second heartbeat, for a change to reach every client (Spring Cloud Netflix's Eureka documentation: "a service is not available for discovery by clients until the instance, the server, and the client all have the same metadata in their local cache (so it could take 3 heartbeats)"), and longer still when an intermediate server's own response-cache refresh cycle adds another hop on top.
Recommendation and what would flip it
- Running on Kubernetes: use the platform's own discovery (Services backed by etcd) and do not add another registry unless you span clusters.
- Many datacenters, VMs and containers mixed, want DNS-based discovery and health checks: Consul.
- New design choosing ZooKeeper: rarely justified now; the main reason is an existing system that depends on it. Kafka, its best-known user, removed ZooKeeper mode in Kafka 4.0 in favour of its own Raft-based controller.
- Eureka: fine inside an existing Spring Cloud estate where clients already retry and tolerate staleness; I would not introduce it into a new, non-JVM system.
Pitfalls
- Putting service discovery on the critical path of every request instead of caching locally, so a registry outage becomes a full outage.
- Treating a ZooKeeper one-time watch as a change stream and silently missing updates.
- Using an even number of consensus nodes: 4 nodes need 3 for quorum and still tolerate only 1 failure, the same as 3 nodes but with more to go wrong.
- Assuming "CP" means "always correct for clients": ZooKeeper reads can still be stale without
sync(), and Consul'sdefaultmode has a brief stale window during leader changes.
Case study: Over a 10-minute window 20% of requests began failing with 502 errors. Application logs show upstream connection refused messages and a discovery component reported that service 'orders' endpoint count dropped from 50 to 2. CPU and network metrics look normal. Walk through how you would analyze this incident: likely root causes, immediate mitigations to restore traffic, and permanent fixes to prevent recurrence.
Sample Answer
Direct answer
The evidence points at the discovery layer, not the orders service: CPU and network are normal, so the orders processes are probably still alive, yet the registry says only 2 of 50 endpoints exist and callers get "connection refused", which means they are dialing addresses where nothing is listening. My working hypothesis is that something removed 48 healthy instances from discovery (a health-check or registration fault, or a change that altered how instances are selected) while some callers are still routing on stale endpoint lists that include dead or re-assigned addresses. First move: find what changed in the last 15 minutes and roll it back; in parallel, stop the bleeding by making callers retry connection-refused errors on another endpoint and by pinning the last good endpoint list if the registry cannot be trusted. Permanent fix: make discovery refuse to drop most of a fleet at once, and alert on endpoint-count cliffs.
Terms used below
- 502 Bad Gateway: the error a proxy or load balancer returns when the upstream it forwarded to fails (here, the connection to an orders instance is refused).
- Connection refused: the target machine actively rejected the TCP connection because nothing listens on that port. It is fast and it happens before any request bytes are sent, which matters for retries.
- Endpoint: one address (IP and port) of a service instance that discovery hands to callers.
Step 1: Read the evidence before guessing
| Signal | What it rules in | What it rules out |
|---|---|---|
| Endpoint count 50 to 2 | Discovery's view changed drastically | Gradual capacity loss |
| CPU and network normal | Most orders instances are not overloaded, and not all dead | A load-induced crash; 2 instances absorbing all traffic would be pegged |
| Connection refused | Callers dial addresses with no listener | Slow or hung servers (those give timeouts), app-level errors (those give 500s) |
| 20% failing, not 100% | A subset of callers or paths is affected | The whole service being unreachable |
The 20% figure is a clue in itself: it suggests some callers (a subset of pods, one zone, one proxy fleet, or clients with a certain cache age) have a bad view while others still route correctly.
Step 2: Likely root causes, and the check that confirms each
- A deploy or config change broke registration. E.g. the Kubernetes Service's label selector (the rule, such as
app: orders, that decides which pods a Service routes to, by matching pod labels) or named target port (the container port a Service forwards to, referenced by name rather than a fixed number, so it can point somewhere different after a change) changed, the pod template (the spec inside a Deployment that stamps out each new pod's containers, labels and ports) lost the label the Service selects on, or a registration sidecar (a small helper container that runs alongside the main one in the same pod, whose only job is registering that pod with the service registry) failed to start in new pods. New pods run fine (normal CPU) but are invisible; old pods were terminated, so callers with stale lists hit their now-dead IPs and get refused.
Check: deploy history for orders and its Service manifest in the window; comparekubectl get pods -l app=orders(count of Running pods) with the Service's EndpointSlices (the Kubernetes objects listing which pod IPs the Service currently routes to). - Mass health-check failure with healthy processes. Readiness or registry checks that depend on a shared dependency (a database, a config server) fail everywhere at once, so 48 instances are marked unhealthy and pulled from discovery even though they could serve.
Check: health-check status and output per instance; do the failures share a message, and did a shared dependency blip at the same moment? - Registry or agent-side fault. Heartbeats not reaching the registry (agents lost contact with the registry servers, an access-control list (ACL) token or a TLS certificate expired, the registry lost quorum (its cluster of servers fell below the minimum number needed to agree on the current, correct view) and is serving a stale or partial view), so TTL (time-to-live) checks expired and instances went critical.
Check: registry server logs and leader status, agent logs on the orders hosts, certificate expiry dates, whether other services also lost endpoints (a registry-wide problem hits everyone). - Network partition between some instances and the registry. A zone or subnet loses connectivity to the registry (not to clients), so its instances time out of discovery.
Check: do the missing 48 share a zone, node pool or subnet?
The "connection refused" part most strongly fits cause 1 (stale addresses after pods were replaced), but causes 2 to 4 also produce it whenever instances restart or IPs are reused. The discriminating checks, not intuition, pick the cause.
Step 3: Immediate mitigations to restore traffic (in order)
- Roll back the most recent change touching orders, its manifests, the registry, or health-check config. It is the cheapest high-probability fix, and you can analyse later.
- Retry connection-refused on a different endpoint. Because a refused connection means the request never reached a server, retrying it elsewhere is always safe, even for non-idempotent operations like creating an order (non-idempotent: doing it twice has a different effect than doing it once, here two orders instead of one; retrying is safe here specifically because we know the first attempt never arrived anywhere to have that effect). Most proxies can be configured to do this in minutes.
- Stop trusting the broken view. If the registry is the problem, enable the proxy's panic mode (route across all known hosts when most are marked unhealthy) or temporarily pin a static list of the last known good 50 endpoints for orders.
- If a health check is the culprit, relax or bypass that check (remove the shared-dependency test from readiness) so instances rejoin, then fix it properly.
- Do not scale up blindly: if registration is broken, new instances also will not register, and restarts churn IPs, making stale-address refusals worse.
Confirm recovery from the same signals: endpoint count back near 50, 502 rate back to baseline, and no remaining refused connections in caller logs.
Step 4: Permanent fixes
- Guard against mass removal. Configure the discovery consumer to refuse an update that drops more than, say, 30% of endpoints in one step, and keep serving the previous list while alerting. Envoy's (a widely used open-source proxy) panic threshold (by default 50% healthy) is one built-in version of this idea.
- Separate liveness of the instance from health of its dependencies in checks, so a shared dependency outage degrades requests rather than deregistering the fleet.
- Alert on the discovery signal itself: endpoint count dropping more than X% within 5 minutes, and divergence between "pods Running" and "endpoints registered".
- Safer rollouts of manifests and registration config: canary the change (roll it out to a small slice of instances first and watch before touching the rest), and include a post-deploy check that the endpoint count stayed within bounds.
- Client resilience: bounded endpoint cache lifetimes, retries on connection errors to another host, and outlier detection (ejecting endpoints that fail real requests).
- Registry robustness: monitor quorum, certificate expiry and agent connectivity, since a registry failure can remove healthy services from discovery.
Trade-offs and pitfalls
- Anchoring on the orders code: CPU and network are normal; debugging the application first wastes the first 20 minutes.
- Restarting everything feels productive but destroys evidence and churns IPs.
- Retrying all 502s: safe only for connection-level failures; retrying a 502 whose request reached the server can duplicate a non-idempotent order.
- Mass-removal guards have a cost: they deliberately keep routing to instances discovery says are dead, which is right when discovery is broken and wrong when 48 instances really did die. Pair the guard with client-side outlier detection so truly dead endpoints still get ejected on real traffic.
An API gateway routes external traffic to internal microservices that use a registry for discovery. Describe how the gateway should discover internal services, handle caching of endpoints, and react to rapid scaling events (for example autoscale from 1 to 100 instances). Discuss cache TTLs, warm-up strategies, and circuit breaker interactions.
Sample Answer
Direct answer
The gateway should subscribe to the registry (a watch or streaming update, not a periodic re-query) and hold the endpoint list for each service in memory, so a new instance becomes routable within about a second of passing its health check. A short cache TTL (time-to-live) is then only the fallback for when the subscription breaks, and on registry failure the gateway keeps serving the last known-good list rather than dropping it. For a 1-to-100 scale-out, the danger is not discovery speed but three interactions: new instances receiving full traffic before they are warm, the one old instance being crushed by slow-start weighting, and circuit breakers sized for the old fleet tripping on healthy traffic.
Terms used below
- Registry: the service holding the current list of instances (Consul, Eureka, etcd, the Kubernetes API).
- Endpoint cache: the gateway's in-memory copy of that list.
- Warm-up: the period after start when an instance is slow (just-in-time compilation, empty caches, cold connection pools).
- Circuit breaker: a limit that fails requests fast instead of queueing them once a threshold is hit. In the Envoy proxy (used by many gateways) this means cluster-level limits on connections, pending requests and active requests, plus outlier detection, which temporarily removes (ejects) an individual instance that keeps failing. Here "cluster" is Envoy's word for the group of instances behind one backend service (an "upstream cluster" or "upstream group"), not a Kubernetes cluster or a database cluster.
1. How the gateway discovers services
flowchart LR
R[Registry] -- watch stream --> CP[Gateway control plane]
CP -- endpoint updates --> G1[Gateway node 1]
CP -- endpoint updates --> G2[Gateway node 2]
G1 --> S[Service instances]
G2 --> S
- Push over poll. One component (a control plane, meaning a management service that holds routing state and pushes it to the proxies, or each gateway node itself) holds a watch on the registry and pushes changes to gateway nodes. Polling costs load that grows with nodes × services: 20 gateway nodes polling 200 services every 30 s is 20 × 200 / 30 ≈ 133 registry requests per second, forever, and still leaves instances up to 30 s late.
- Only ready instances. The gateway must receive only instances that have passed a readiness check, not ones that have merely started.
- Registry outage = keep last good list. If the watch fails, keep routing with the cached list and let the gateway's own passive checks (errors on real traffic) drop dead instances. Emptying the cache because the registry is unreachable turns a registry outage into a full outage.
2. Caching of endpoints and TTLs
With push-based updates, a TTL is not what makes things fresh; it is the safety net. My settings:
- Refresh on push, immediately.
- Full resync every few minutes, in case a push was missed.
- Maximum staleness before alerting (not before discarding): if the list has not been confirmed for, say, 5 minutes, page someone but keep serving.
If you are stuck with polling (DNS-based discovery, for example), the TTL becomes the key number and has to be short, because it bounds two different delays:
| Direction | What a TTL of T means |
|---|---|
| Scale-out | New instances wait up to T to receive traffic (wasted capacity during a spike) |
| Scale-in | Terminated instances keep receiving requests for up to T (errors) |
The scale-in side is the one that hurts. Fix it on the service side, not with a tiny TTL: an instance being removed first deregisters, then keeps serving for a drain delay at least as long as the maximum staleness (T plus propagation time), then exits.
3. Rapid scaling from 1 to 100 instances
Warm-up
Mark an instance ready only after it has warmed: run a few synthetic requests through the hot paths (the request types that carry most of the traffic, so their caches and connection pools are what actually need priming) and prime local caches in the readiness check. That protects new instances regardless of how the gateway balances.
The slow-start trap in a 1-to-100 event
Envoy's slow start gives a new endpoint a reduced weight that grows over a configured window, starting at a minimum (10% of normal weight by default). With 1 old instance at full weight and 99 new ones at 10%:
old instance’s share=1+99×0.11=10.91≈9.2%instead of the fair 1%. At 60,000 requests per second (RPS) arriving across the fleet, that is about 5,505 RPS on the one old instance against a fair share of 600. Slow start protects the 99 newcomers by overloading the one instance that was already struggling, which is presumably why you scaled. Envoy's own documentation notes slow start is meant for a few new endpoints joining an established set. So for a large scale-out, rely on readiness-gated warm-up and turn slow start off or keep its window short; use slow start for the ordinary case of a handful of instances joining.
Circuit breakers sized for yesterday's fleet
Envoy's cluster circuit-breaker thresholds apply to the whole upstream cluster, not per instance, and default to 1024 for maximum connections, pending requests and active requests. By Little's law (concurrent requests = arrival rate × time in system), 4 gateway nodes carrying 60,000 RPS at 80 ms per request each hold
460000×0.08=1200 concurrent requestswhich exceeds 1024. The gateway starts rejecting requests with 503 errors even though 100 healthy instances sit behind it. Size these thresholds from the peak you will scale to, not the size you started at, or make them scale with the instance count.
Outlier detection during warm-up
Cold instances are often slow or return errors in their first seconds. Outlier detection may eject them (by default after 5 consecutive 5xx errors, meaning HTTP server-error responses in the 500-599 range, for 30 s the first time), but Envoy caps ejections at 10% of the cluster by default. That cap is protective in both directions: in a 100-instance cluster at most 10 are ejected, and in a small cluster it stops detection from removing the capacity you have. Do not raise it just to "clean up" a bad scale-out; fix warm-up instead.
Retries amplifying overload
When the old instance is overloaded, gateway retries add load exactly where it hurts. Use a retry budget (retries allowed only up to a fraction of active requests; Envoy's default budget is 20%) rather than a fixed retry count per request.
Worked example: timeline of a scale-out
Assume a flash sale drives traffic from 500 to 60,000 RPS.
- T+0: autoscaler requests 99 new instances.
- Instances start over the next minute or two, warm up behind their readiness check, and register.
- Each registration reaches the gateway within about a second via the watch, rather than up to 30 s later with a 30 s poll.
- With slow start off and warm-up done before readiness, traffic spreads evenly as each instance appears, and the gateway's circuit-breaker limits (sized to the 1,200-concurrent-request peak with headroom) do not trip.
- On scale-in, each instance deregisters, drains for longer than the maximum staleness, then exits. To see why the drain matters, consider the counterfactual without it: with a poll-based cache whose TTL equals the maximum-staleness window, gateway nodes refresh their caches at staggered times spread evenly across that window, so at the instant an instance actually stops, roughly half of them have already refreshed past it and half have not. With independent random picks, a request plus one retry would then hit that still-stale half both times 0.5 × 0.5 = 25% of the time. Drain-then-exit (keeping the instance serving until the whole staleness window has passed) removes this risk entirely, because no cache can still be pointing at a dead instance once it actually exits.
Trade-offs and pitfalls
- Push is more machinery than poll: a watch has to handle disconnects and resync. Worth it at this scale; for a small, stable estate, polling every few seconds is fine.
- Registry-driven routing vs a load balancer per service: pointing the gateway at a per-service load balancer (or a Kubernetes Service virtual IP) hands the scaling problem to the platform, but loses per-request balancing and outlier detection at the gateway.
- Health checks that are too eager remove warming instances and cause flapping (instances bouncing in and out of the list). Separate "ready to receive traffic" from "alive".
- Do not make the gateway's TTL the only defence against dead instances. Pair it with passive health checking and deregister-then-drain on the service side.
Unlock Full Question Bank
Get access to all 19 Service Discovery and Configuration Management interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.