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.
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.
Describe how a service mesh such as Istio or Linkerd integrates with service discovery and dynamic configuration. Explain how sidecars discover backends, how the control plane distributes routing/policy config, and trade-offs around performance, operational complexity, and discoverability when adding a mesh to an existing platform.
Sample Answer
Direct answer
A service mesh moves discovery and traffic configuration out of application code and into proxies. A control plane watches the platform's own source of truth (in Kubernetes: Services, EndpointSlices and pod labels, plus the mesh's routing resources) and translates it into configuration that it pushes to a proxy next to every workload. The application calls a plain hostname; the local proxy already knows the healthy backend IPs, the routing rules, retry and timeout policy, and the certificates for mTLS. You gain uniform routing, security and telemetry for every language; you pay in per-pod CPU and memory, an extra network hop per side, a control plane whose config push can itself become a scaling problem, and a system that is harder to debug because the real routing decision now lives in proxy state you cannot see in your code.
Terms
- Service mesh: a layer of proxies that handle service-to-service traffic, plus a control plane that configures them. Istio and Linkerd are the two most common on Kubernetes.
- Sidecar: a proxy container injected into each application pod. Traffic in and out of the pod is redirected through it (typically using iptables, the Linux kernel's packet-filtering and routing rules, configured at pod start to send traffic through the proxy first).
- Data plane vs control plane: the proxies that carry requests are the data plane; the component that tells them what to do is the control plane (
istiodin Istio; thedestination,identityand proxy-injector components in Linkerd). - mTLS (mutual TLS): both sides of a connection present certificates, so the server knows which workload is calling, not just that the traffic is encrypted.
- xDS: the family of discovery APIs Envoy proxies use to receive configuration. Envoy is the specific proxy Istio injects as the sidecar; xDS covers LDS (listeners), RDS (routes), CDS (clusters, meaning upstream services) and EDS (endpoints, meaning the IPs behind a cluster).
- Kubernetes Service, EndpointSlice, pod labels: the platform's own primitives the mesh builds on. A Service is a stable name for a group of pods; an EndpointSlice is the live, auto-updated list of that group's actual pod IPs and their readiness; pod labels are the key/value tags (
app: reviews) Services and mesh rules select pods by. - gRPC: a binary remote-procedure-call protocol; the control plane uses it as the transport for pushing config and endpoints to every sidecar.
How sidecars discover backends
flowchart LR
K8s[Kubernetes API: Services, EndpointSlices, mesh custom resources] -->|watch| CP[Control plane]
CP -->|push config and endpoints over gRPC| PA[Sidecar in pod A]
CP -->|push| PB[Sidecar in pod B]
AppA[App A] -->|calls reviews:9080| PA
PA -->|mTLS, load balanced| PB
PB --> AppB[App B, a reviews pod]
Istio (Envoy sidecars):
istiodwatches Services and EndpointSlices, so it knows every pod IP behind every Service and which are ready.- It turns that into xDS: a cluster for each service, endpoints (EDS) listing healthy pod IPs, and routes for any VirtualService rules.
- Each Envoy sidecar holds a long-lived gRPC stream to
istiod. When a pod becomes ready or is deleted,istiodpushes an endpoint update and the sidecar's load balancer changes within seconds, without DNS TTLs and without the app doing anything. - The app still resolves
reviewsthrough normal cluster DNS, but the sidecar intercepts the connection and picks the actual backend from its own endpoint list.
Linkerd (its own Rust micro-proxy, linkerd2-proxy):
The proxy asks the control plane's destination service, over gRPC, for the endpoints and policy of each destination the application actually talks to, and keeps a watch open for that destination. That on-demand model means a proxy only holds state for the services its workload uses, which is a real difference from Istio's default behaviour.
How the control plane distributes routing and policy config
The two resources to actually know first are VirtualService and DestinationRule: together they cover almost every day-to-day routing decision. The rest of this list matters once you also need identity-based security policy or aren't yet on Istio's newer routing APIs.
- Routing: in Istio, VirtualService (match rules, weighted splits such as "5% to v2", retries, timeouts, fault injection: deliberately injecting errors or delay into some requests to test how callers handle it) and DestinationRule (load-balancing algorithm, connection pools, outlier detection which ejects endpoints that keep failing, and subsets such as
v1/v2by label). In both meshes, the Kubernetes Gateway API's HTTPRoute can express traffic splits too. - Security policy: PeerAuthentication (require mTLS) and AuthorizationPolicy (which identities may call which paths) in Istio; Server and AuthorizationPolicy resources in Linkerd. Workload certificates are issued and rotated automatically by the control plane.
- Distribution: operators apply these as Kubernetes resources; the control plane validates and translates them and pushes the result. This is dynamic configuration delivery: a traffic shift from 5% to 50% is an API write, effective fleet-wide in seconds, with no redeploy.
Worked example: why config scope matters at scale
A cluster has 500 services and 5,000 pods, and each workload really calls about 10 services with about 10 endpoints each.
- Default Istio behaviour sends each sidecar configuration for the whole mesh. Endpoint entries held across the fleet: 5,000 sidecars × 5,000 endpoints = 25,000,000. Every endpoint change also triggers a push to every sidecar.
- Scoped (Istio's
Sidecarresource restricting each workload to the hosts it uses, ordiscoverySelectorslimiting which namespaces are visible): 5,000 × (10 × 10) = 500,000 entries, 50 times less proxy memory and push work. - Linkerd's on-demand lookups give roughly the scoped behaviour by default.
The lesson: with a push-everything control plane, proxy memory and control-plane CPU grow roughly with (number of proxies) × (size of the mesh). Both of those factors grow with the same underlying number, how many pods are in the cluster, so doubling the fleet does not double the cost, it roughly quadruples it: that is what "quadratic as the platform grows" means here. Scoping is not an optimisation to add later; it belongs in the first rollout.
Trade-offs when adding a mesh to an existing platform
| Dimension | Cost | Mitigation |
|---|---|---|
| Performance | Two extra proxy hops per call (client sidecar and server sidecar), plus TLS handshakes; per-pod CPU and memory for every sidecar | Measure p99 (99th percentile) latency on your own traffic before and after on a pilot namespace; do not trust vendor benchmarks. Consider Istio's ambient mode (generally available since Istio 1.24), which replaces per-pod sidecars with a per-node ztunnel (a shared node-level proxy handling basic encrypted routing for every pod on that node) for L4 (TCP-level mTLS and policy) and optional per-namespace waypoint proxies (added only where a namespace needs HTTP-level routing decisions) only where L7 (HTTP-level routing) is needed |
| Operational complexity | A new critical control plane to upgrade and monitor; injection webhooks (the Kubernetes mechanism that automatically adds the sidecar container to a pod as it is created, so nobody edits every deployment by hand); sidecar start-up ordering (the app starts before its proxy is ready, or the proxy exits before the app finishes draining, meaning finishing in-flight requests and closing connections cleanly) | Pilot one namespace; use native sidecar support (a Kubernetes feature that starts and stops sidecar containers in the right order automatically, instead of relying on timing tricks) in recent Kubernetes versions for start/stop ordering; keep the mesh version upgrade as a rehearsed runbook |
| Discoverability (debugging) | The routing decision is no longer in code or DNS; a request can fail because of a DestinationRule nobody on the app team knows about | Standard tooling: istioctl proxy-config endpoints <pod> and istioctl proxy-status (is this sidecar in sync with istiod?), linkerd viz for per-route metrics; mesh resources owned in the same repo as the service |
| Two discovery systems | During migration, meshed pods use proxy-pushed endpoints while unmeshed callers still use DNS or a client-side library; their views of "healthy" can differ | Migrate by call path (callee first, then callers) and keep outlier detection consistent with existing health checks |
| Control-plane failure | If istiod is down, sidecars keep their last config and traffic keeps flowing, but no new endpoints or policy arrive, so scaling events go unseen | Run the control plane highly available; alert on proxy config staleness |
Recommendation
For an existing platform, adopt a mesh when you need at least two of: uniform mTLS with identity-based policy, traffic shifting for progressive delivery (rolling a change out to a growing slice of traffic while watching for regressions, rather than to everyone at once), and consistent retries, timeouts and telemetry across several languages. If you only need discovery and load balancing, Kubernetes Services plus a good client library are cheaper. If you do adopt: start with one namespace, scope config from day one, and prefer the lighter footprint (Linkerd, or Istio ambient) unless you specifically need Envoy's L7 feature set everywhere.
Compare health check approaches between a registry that uses TTL heartbeats (e.g., Consul TTL checks) and Kubernetes probes (liveness, readiness, startup). For each model describe recommended frequencies, failure thresholds, trade-offs between fast failover and false positives, and how check results should influence registry state and load balancing.
Sample Answer
Direct answer
The two models put responsibility in opposite places. A Consul TTL check (Consul is a widely used service registry: a database of which instances of each service exist and are healthy, that clients query to find them) is push-based: the application itself must call Consul every TTL period to say "still passing", and silence past the TTL marks it critical, which removes it from healthy query results. Kubernetes probes are pull-based: the kubelet (the agent on each node) calls into the container, and the three probes do three different jobs: readiness controls whether the pod (Kubernetes' smallest deployable unit: one or more containers scheduled and networked together) receives traffic, liveness controls whether the container is restarted, and startup holds off the other two until a slow starter is up. The frequency and threshold choices follow from a single trade-off: detect a dead instance fast, without evicting or restarting healthy instances that merely paused.
The two models side by side
| Consul TTL check | Kubernetes probes | |
|---|---|---|
| Who acts | The app pushes a heartbeat (PUT /v1/agent/check/pass/<check_id>) | The kubelet pulls: HTTP GET, TCP connect, a gRPC health-check call, or exec (running a command inside the container and checking its exit code) |
| What failure means | No heartbeat within the TTL: status becomes critical | Consecutive failures reach failureThreshold |
| Initial state | Critical until the first heartbeat (so an unready instance never gets traffic) | Readiness starts not-ready until it succeeds |
| Effect on routing | Health-filtered queries (the ?passing filter on the health API, DNS lookups) stop returning the instance | Readiness failure removes the pod from the Service's endpoints (a Kubernetes Service is the stable name/address in front of a set of pods; its endpoints are the live list of pod IPs currently backing it) |
| Effect on process | None; the registry only reports | Liveness failure kills and restarts the container |
| What it really proves | The app's heartbeat code is running and chose to say "pass" | The kubelet can reach the endpoint and it answers correctly |
A subtle difference: a TTL check can report on things a probe cannot see (the app decides "I am passing only if my queue consumer is keeping up"), but a TTL heartbeat thread can keep running while the request-serving threads are deadlocked, and it says nothing about whether the network path from clients works. A probe exercises the real request path from the node, but only as far as the node.
Recommended frequencies and thresholds
Consul TTL checks
- Heartbeat interval about one third of the TTL, e.g. TTL 30 seconds with a heartbeat every 10 seconds. The app then tolerates two lost heartbeats (a garbage-collection (GC) pause, one dropped request) before going critical. A heartbeat at the same period as the TTL fails on the first delay.
- Note that the consecutive-failure counters Consul offers (
FailuresBeforeCritical,SuccessBeforePassing) apply to active checks such as HTTP and TCP, not to TTL checks, so the TTL-to-interval ratio is your failure threshold. - Use
warnfor degraded-but-serving (so dashboards see it) andfailfor a deliberate eviction, e.g. during graceful shutdown the app calls fail first, then drains. - Set
DeregisterCriticalServiceAfterso dead registrations get cleaned up: the minimum is 1 minute and Consul's reaper (the background process that sweeps up and removes checks that have stayed critical too long) runs every 30 seconds, so removal can take slightly longer than configured. Pick something like 10 minutes, long enough that a brief critical period does not delete the registration and force a re-register.
Kubernetes probes
Defaults are periodSeconds: 10, timeoutSeconds: 1, failureThreshold: 3, successThreshold: 1, initialDelaySeconds: 0.
- Readiness: fast and sensitive, because the action is cheap and reversible. For example period 5 s, failureThreshold 2: removed from traffic within about 10 s. It should check what this pod needs to serve (warm caches loaded, local dependencies up) but not shared downstream dependencies (see pitfalls).
- Liveness: slow and conservative, because the action (restart) is expensive and can cascade. Period 10 s, failureThreshold 3 or more, so about 30 s of consecutive failure, and it should check only "is this process wedged" (an endpoint that returns 200 if the event loop, the single loop many runtimes such as Node.js use to process one task at a time, is still responding), never dependencies.
- Startup: for slow starters, e.g.
failureThreshold: 30,periodSeconds: 10gives up to 30 × 10 = 300 seconds to start; liveness and readiness do not run until it succeeds once, so liveness can stay aggressive without killing a JVM (Java virtual machine) that is still warming up. timeoutSeconds: 1is too tight for many real endpoints under load; 2 to 3 seconds avoids counting a slow response as a failure.
Fast failover versus false positives, with numbers
Detection time is roughly period × failureThreshold for probes and TTL for TTL checks. False positives come from transient pauses shorter than that window.
Take a service whose stop-the-world GC pauses (a garbage-collection pause during which the runtime freezes every application thread, not just the collector, so nothing responds until it finishes) occasionally reach 4 seconds:
- Readiness at period 2 s, threshold 1: a 4-second pause fails at least one probe and the pod is pulled from traffic. With 50 pods pausing independently, pods are constantly flapping in and out of the endpoint list, and each change is an update pushed to every client.
- Readiness at period 5 s, threshold 2: a pod needs about 10 seconds of failure to be removed, so a 4-second pause never evicts it, and a truly dead pod is still gone in about 10 s.
- Liveness with the same aggressive settings would restart pods on every GC pause, which makes the pause problem worse (cold caches, restart storms).
The pattern: be aggressive where the action is reversible (removing from load balancing), conservative where it is destructive (restart, deregistration).
How results should drive registry state and load balancing
- Health state feeds routing, not just dashboards: a failing readiness or a critical TTL check must remove the instance from the endpoint set that clients and proxies consume. Warning states should stay routable but visible.
- Removal is not deletion: an unhealthy instance stays registered (so it can come back when it recovers); deregistration happens only after a long critical period or on shutdown.
- Protect against mass eviction: if a health signal says 90% of instances are unhealthy at once, the more likely explanation is a broken check or a shared dependency, not 90% of processes failing together. Proxies like Envoy (a widely used open-source proxy) have a panic threshold (by default, when fewer than 50% of hosts are healthy, it load-balances across all hosts anyway) precisely so that a bad health signal does not funnel all traffic onto a handful of survivors.
- Combine with passive checks: load balancers should also eject endpoints that return errors on real traffic, a technique called outlier detection: watch each endpoint's live error rate and temporarily pull out whichever ones stand out from their peers, which reacts faster than any periodic check.
- Graceful shutdown order: fail the check or readiness first, wait for the change to propagate to clients (a few seconds), then stop accepting connections.
Trade-offs and pitfalls
- Dependency checks in readiness or TTL logic: if every pod's readiness checks the shared database and the database blips, every pod goes unready at once and the whole service vanishes from discovery, turning a partial degradation into a total outage.
- Liveness equal to readiness: restarting pods because a dependency is slow is the classic restart storm.
- TTL heartbeats from a separate thread can report "passing" while the serving threads are deadlocked; tie the heartbeat to a signal from the real request path.
- Probes prove local health only: a pod can pass every probe while clients cannot reach it, for example a network policy (cluster rules restricting which pods may talk to which, even when both ends are healthy) blocking the path, or a partitioned node. Pair with client-side outlier detection.
You're setting up alerting for a Consul- or etcd-backed service registry that several teams' services depend on for discovery and config. What would you monitor to catch degradation before it causes an outage, and what would make you page someone versus just log it?
Sample Answer
Direct answer
Monitor the registry at three layers: the consensus layer (does the cluster have a leader and enough healthy members to keep it), the storage layer (is the disk fast enough and is the database nowhere near its size limit), and the consumer layer (can client services actually resolve names and read fresh config). Page a human only for conditions that are already hurting consumers or that leave the cluster one failure away from losing quorum; everything that is merely unusual goes to logs, dashboards or a next-business-day ticket.
Terms first
- Service registry: the database (here Consul or etcd) where running instances announce "I am
paymentsat 10.0.3.14:8443", and where other services look those addresses up. Many teams also keep dynamic configuration in the same store. - Raft, leader, quorum: Consul servers and etcd members agree on every write using the Raft consensus protocol. One member is the leader and orders all writes. A write only commits once a quorum (a strict majority,
floor(n/2) + 1members) has stored it. A 3-member cluster needs 2 alive; a 5-member cluster needs 3. - Leader election: when followers stop hearing from the leader they hold an election. While there is no leader, no writes succeed: registrations, deregistrations and config changes all stall.
- fsync: forcing a write to physical disk. Raft cannot acknowledge a write until its log entry is fsynced, so a slow disk makes the whole cluster slow.
- Watch / blocking query: a long-lived request that returns when data changes. Clients use them to learn about new instances without polling hard.
- SLO (service-level objective): the reliability target you promise, for example "99.9% of name lookups succeed".
- Error budget / burn rate: the error budget is the failure a 99.9% SLO allows you, up to 0.1% of requests; the burn rate is how fast you are spending it. "Burning error budget fast" means failures are happening quickly enough to exhaust the whole budget before the SLO's period ends, which is why it pages before the SLO is technically breached.
What to monitor
1. Consensus health (the cluster itself)
| Signal | etcd | Consul |
|---|---|---|
| Is there a leader? | etcd_server_has_leader (0 or 1 per member) | consul.raft.state.leader increments; consul.raft.leader.lastContact shows how long followers go without hearing from the leader |
| Election churn | etcd_server_leader_changes_seen_total | consul.raft.state.candidate (a server started an election) |
| Headroom before quorum loss | count of healthy members vs quorum | consul.autopilot.failure_tolerance (voting servers you can still lose) and consul.autopilot.healthy |
| Failed writes | etcd_server_proposals_failed_total | consul.client.rpc.failed, consul.client.rpc.exceeded (rate-limited) |
Failure tolerance is the single most useful number here. It turns "one member is down" from a vague worry into a precise statement: a 5-server cluster with one down still tolerates one more failure; a 3-server cluster with one down tolerates zero.
2. Storage health (the usual root cause)
- WAL fsync latency (WAL: write-ahead log, the append-only file etcd writes every change to before applying it, so a crash can replay from it; fsync forces that write out to physical disk instead of leaving it buffered) (
etcd_disk_wal_fsync_duration_seconds) and backend commit latency (how long etcd's underlying storage engine takes to durably commit a batch of writes) (etcd_disk_backend_commit_duration_seconds). etcd's own guidance is that the p99 (99th percentile) should stay under 10 ms and 25 ms respectively. When fsync is slow, heartbeats miss their deadline and followers start elections, so a noisy-neighbour disk (a shared disk whose latency spikes because something else on the same physical hardware is hammering it) shows up first as "leader changes", not as "disk slow". Alert on the cause, not just the symptom. - Database size vs quota. etcd has a space quota (2 GB by default). When it is exceeded, etcd raises a NOSPACE alarm and rejects writes with
mvcc: database space exceeded(mvcc, multi-version concurrency control, is etcd's storage engine; the message means the quota is full) until someone compacts (discards old key revisions the quota no longer needs), defragments (reclaims the disk space compaction just freed, since the storage file does not shrink on its own) and disarms the alarm (clears the NOSPACE flag so writes resume). That is a full outage for registrations and config changes, and it is completely predictable from a growth trend. Tracketcd_mvcc_db_total_size_in_bytesagainst the quota. - For Consul, the equivalent is
consul.raft.commitTimerising, plus disk usage on the servers' data directory.
3. Consumer-side health (what users actually feel)
The registry can be "green" while clients are broken (a bad ACL token, meaning the credential a client presents on every request has been revoked or misconfigured against the access control list, or ACL, that Consul or etcd checks it against; a firewall change; a client library that stopped re-watching). So measure from the outside:
- Synthetic lookups: a prober in each zone resolves a few canary service names every 10 seconds through the same path real clients use (DNS interface, HTTP API, or client library) and records success and latency.
- Watch staleness: the prober writes a heartbeat key (for example a timestamp) every 10 seconds, and consumers or a second prober report how old the value they see is. This catches a stuck watch or a partitioned follower serving stale reads.
- Resolution errors in client libraries: expose a counter from the shared discovery library for "lookup failed" and "served from stale cache because the registry was unreachable".
- Catalog churn: registration and deregistration rate. A sudden spike of deregistrations (for example half the instances of one service flapping) is a health-check or network problem that will soon be a traffic problem.
Page vs log: the rule and the table
The rule: page when the condition (a) already breaches the consumer SLO, or (b) removes your last margin before an outage, or (c) will cause an outage on a predictable timeline shorter than a working day. Everything else is a ticket or a log.
| Condition | Action | Why |
|---|---|---|
| No leader for more than 30 s (sustained, not a blip) | Page | All writes are failing now; deploys and failovers cannot register. |
| Failure tolerance = 0 (for example 3-member cluster with 1 member down) | Page | The next failure is total loss of writes. |
| Synthetic lookup success below SLO, burning error budget fast | Page | Consumers are impacted now. |
| DB size above 80% of quota and projected to hit 100% within 24 h | Page | Guaranteed write outage with a known ETA. |
| Watch staleness above 60 s in any zone | Page | Instances are routing on stale endpoints or config. |
| Single leader change | Log / dashboard | Normal during member restarts and upgrades. |
| More than 3 leader changes in 15 min | Ticket (page if combined with failed writes) | Flapping leadership is usually disk or network trouble building up. |
| p99 fsync above 10 ms for 15 min | Ticket, high priority | Leading indicator of elections; fix before it becomes one. |
| One member down in a 5-member cluster (tolerance still 1) | Ticket | Margin reduced but not exhausted. |
| DB size above 60% of quota | Ticket | Schedule compaction/defrag or find the writer that grew it. |
Worked example
A 3-member etcd cluster backs discovery for 40 services. Tuesday 09:00, one member's disk starts showing p99 WAL fsync of 40 ms (four times etcd's 10 ms guidance). What fires:
- Tuesday 09:15: the fsync alert raises a ticket after 15 minutes of sustained breach. Nobody is paged yet: the cluster still has a leader and quorum.
- Tuesday through Wednesday: that member keeps missing heartbeats intermittently;
etcd_server_leader_changes_seen_totalclimbs by a handful of elections a day. Each burst is still a ticket on its own, but the dashboard now correlates it with the open fsync ticket. - Wednesday 09:00 (about 24 hours after the ticket opened): the operator, following the runbook, takes the sick member out of rotation for replacement. The cluster is now 2 of 3: failure tolerance drops to 0 and the page fires, because one more loss means
floor(3/2)+1 = 2members can no longer be met.
Notice that the page came from the margin signal, not from the disk metric. The disk metric's ticket, open since Tuesday 09:15, gave about a day of warning before the operator's Wednesday action tripped the margin signal that actually woke someone.
Trade-offs and pitfalls
- Paging on leader changes is the classic noisy alert. Rolling upgrades cause them by design. Page on "no leader for N seconds" or on elections combined with failed writes.
- Monitoring only the servers misses client failures. The prober and client-library metrics are what tell you consumers are affected.
- Staleness is invisible without a heartbeat key. A follower cut off from the leader can keep serving reads it believes are current (unless clients ask for linearizable, meaning always-up-to-date, reads).
- Alert on trends for capacity. A DB-size alert at 95% gives minutes of warning; a projection alert gives hours.
- Multi-team blast radius. Because several teams depend on the registry, tie the paging alerts to a documented runbook (how to disarm a NOSPACE alarm, how to replace a member without losing quorum) so the on-call engineer is not learning Raft at 3 a.m.
Define service discovery in the context of microservices. Explain the differences between client-side discovery and server-side (proxy) discovery, including who is responsible for load balancing, how health checks are handled, and examples of real-world tools (DNS, Consul, Kubernetes Service). When would you choose each approach and why?
Sample Answer
Direct answer
Service discovery is how one service finds the current network addresses of another when instances come and go all the time (autoscaling, deploys, crashes). A service registry keeps the list of live instances. In client-side discovery, the calling service asks the registry for the list and picks an instance itself, so the client does the load balancing. In server-side (proxy) discovery, the caller sends the request to one stable address (a load balancer or proxy), and that component looks up the instances and picks one. My default is server-side through the platform (a Kubernetes Service or a load balancer) because it keeps clients simple and language-independent; I switch to client-side when the extra hop or the lack of per-request control actually costs something.
Why it is needed
In a static world you would hard-code payments = 10.0.1.5. In a microservice fleet, instances get new IPs on every deploy and the count changes with load, so addresses must be looked up at runtime, and the lookup must only return instances that are healthy (able to serve).
The two approaches
Client-side discovery
- Each
paymentsinstance registers itself (or is registered by the platform) in the registry. - The
checkoutservice queries the registry (or a local cache of it) forpaymentsand gets a list, such as[10.0.1.5, 10.0.1.9, 10.0.2.4]. checkout's own library picks one (round robin: cycle through the list in order; or least outstanding requests: send to whichever instance currently has the fewest in-flight calls) and connects directly.
Server-side (proxy) discovery
- Instances register the same way.
checkoutcalls one stable name, such aspayments.default.svc.cluster.localor a load-balancer address.- The load balancer or proxy (which watches the registry) chooses an instance and forwards the request.
Who does what
| Client-side | Server-side (proxy) | |
|---|---|---|
| Who load-balances | The calling service's library | The load balancer or proxy |
| Who knows which instances are healthy | Registry health checks, plus the client's own view (it sees its own timeouts and errors immediately) | Registry health checks, plus the proxy's own active checks or error tracking |
| Extra network hop | None | One (unless the proxy runs on the same host as the caller) |
| Logic lives in | Every client, in every language you use | One shared component |
| Changing the algorithm | Redeploy every client | Reconfigure the proxy |
On health checks: the registry usually learns health by probing instances (an HTTP call to /health every few seconds) or by requiring heartbeats. The client or proxy adds a second, faster signal: passive health checking, which stops sending to an instance that just returned several errors in a row, without waiting for the next probe.
Real-world tools
- DNS: a service name resolves to several A records (IP addresses) and the client picks one. That is a simple form of client-side discovery, but with weak health handling and caching delays (clients keep an answer until its TTL, time-to-live, expires, and some ignore TTLs).
- Consul: supports both. Clients can query its HTTP API or its DNS interface (
payments.service.consul, returning only healthy instances) and pick an instance themselves: client-side. Or traffic goes through Consul's service mesh, where a sidecar proxy (a helper process running next to each service) does the choosing: server-side, but on the same host. - Kubernetes Service: server-side. A normal Service gets one stable virtual IP (the ClusterIP);
kube-proxy(the Kubernetes component that runs on every node and keeps its routing rules in sync with the cluster) programs rules, either iptables (the Linux kernel's built-in packet-filtering and NAT table) or IPVS (the Linux kernel's built-in load balancer), that spread connections across the pods (a pod is Kubernetes' smallest deployable unit, one or more containers scheduled together) that are passing their readiness probe (a periodic check, such as an HTTP call, that decides whether a pod is currently able to serve traffic; failing it removes the pod from the Service without killing it). A headless Service (no ClusterIP) instead returns the pod IPs through DNS, which is client-side, and is what gRPC (a high-performance RPC framework built on HTTP/2, which multiplexes many concurrent requests over a single long-lived TCP connection instead of opening a new one per call) clients often use to balance per request. - Cloud load balancers (for example, an AWS Application Load Balancer with a target group): server-side, with the cloud provider registering instances.
- Client-side libraries: gRPC's built-in load-balancing policies, Spring Cloud LoadBalancer (which replaced the Netflix Ribbon library that is no longer developed).
Worked example
checkout runs 200 instances and calls payments, which runs 50.
- Client-side: every
checkoutinstance may keep connections to everypaymentsinstance: 200 × 50 = 10,000 connections. Whenpaymentsinstance 17 starts timing out, eachcheckoutinstance notices within its own next few requests and stops using it, without waiting for the registry. But the balancing code has to exist, and be kept correct, in every languagecheckout-like services are written in. - Server-side with a Kubernetes Service:
checkoutknows one address. Connections are spread bykube-proxy, which balances per connection, not per request: it picks a pod once, when a TCP connection is first opened, and every request sent over that connection afterward goes to that same pod. Since gRPC keeps one HTTP/2 connection open and multiplexes many requests over it (see above), acheckoutinstance that opens one long-lived HTTP/2 connection sends all of its requests, forever, to whichever single pod answered first, which is a classic cause of uneven load for gRPC. Fixes: a headless Service plus client-side balancing, or a proxy that balances per request.
When to choose each
- Choose server-side when you have many languages, want one place to change routing, or run on a platform that already provides it (Kubernetes, cloud load balancers). This is the right default for most teams.
- Choose client-side when the extra hop matters (very latency-sensitive internal calls), when you need per-request balancing of long-lived connections (gRPC), or when you want each caller to react to failures instantly.
- A service mesh blends them: the logic lives in a proxy (server-side style, one implementation for all languages), but the proxy sits next to each client (client-side style, no central hop). It costs you operating the mesh.
Pitfalls
- Registering an instance as soon as the process starts, before it can serve (use readiness, not liveness, to decide when it receives traffic: a liveness probe only answers "is this process stuck and needs restarting", it says nothing about whether the process is ready to handle requests right now).
- Clients that cache the instance list with no refresh, so they keep calling instances that were removed.
- Treating the registry as the only health signal: a registry probe every 10 s means up to 10 s of requests to a dead instance unless the caller also reacts to errors.
Unlock Full Question Bank
Get access to all 16 Service Discovery and Configuration Management interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.