Skip to content

Service Discovery: Client-Side vs Server-Side, DNS, Health Checks ​

"When making a request to a service, the client obtains the location of a service instance by querying a Service Registry, which knows the locations of all service instances." — Chris Richardson, Pattern: Client-side service discovery, microservices.io

Summary: Service discovery answers one question, "which addresses can I send this request to right now?", for a world where instances are created, moved and killed all day; the answer always comes from a registry (explicit, or hidden inside DNS or a platform), and it is only as good as the health information and the caches between the registry and the caller. Focus: The registry and its lifecycle (register, heartbeat, lease, deregister), client-side versus server-side discovery, DNS (A, AAAA, SRV, TTL, headless services), liveness versus readiness versus startup probes, graceful drain, registry consistency (AP versus CP), mesh discovery (xDS, EDS), multi-cluster, security, local development, and the failure modes that cause outages. Learning goal: For any request between two services, trace exactly where the address comes from, how long a dead instance stays in the list, and what the deploy does to in-flight requests; then pick client-side, server-side or DNS discovery and set probes, TTLs and drain delays with numbers you can defend.

This chapter is the "how does service A find service B" page of the microservices group. Deciding whether to split services is in Monolith vs Microservices vs Modular Monolith; where the boundaries go is in Service Boundaries; what travels over the wire after the address is known is in Service Communication; the edge and the proxy-per-pod are in API Gateway, BFF and Service Mesh. Load-balancing algorithms are taught once in Load Balancing, DNS itself in IP, DNS, GeoDNS, Kubernetes basics in Containers & Kubernetes, and the CAP trade-off in CAP and PACELC; here they appear only as far as discovery needs them.

Page map ​

If you are looking forGo to
Why a hard-coded address stops workingWhy it exists
The registry, registration styles, leases and TTLsRegistry, Registration, Leases
Client-side vs server-side, with a tableClient-side, Server-side, Comparison
DNS, SRV records, headless services, why DNS caching hurtsDNS discovery
Liveness vs readiness vs startup, deep vs shallow checksProbes, Deep vs shallow, Flapping
Zero-error deploys, drain, lame duckGraceful shutdown
AP vs CP registries, stale entries, split brainConsistency, Failure modes
Envoy, xDS, EDS, IstioMesh discovery
Several clusters or regionsMulti-cluster
Registry ACLs, spoofed registration, mTLSSecurity
Registry metrics, endpoint churnObservability
Docker Compose, static configLocal development
Go: registry, heartbeat client, round robin, gRPC resolverGo
Laravel: health route, SRV, config-driven upstreams, Octane drainLaravel
Monolith to multi-region, step by stepIn architecture
Run it yourself, kill an instanceLab

Everything in one minute ​

The three jobs. Every discovery system, from a hosts file to a service mesh, does the same three things.

JobQuestion it answersTypical ownerWhere it goes wrong
Registration"Which instances exist?"The instance (self-registration), the platform or a sidecar (third-party registration)Instances that die without deregistering; instances registered before they are ready
Health"Which of them can serve right now?"Probes run by the kubelet, the registry agent, the proxy or the instance itselfChecks that are too shallow (traffic to a broken pod) or too deep (one dependency outage empties every pool)
Lookup"Give me an address for this name."The client library, a proxy, DNS, the mesh data planeCaches that outlive the truth (DNS TTL, client lists, keep-alive connections)

The patterns.

PatternWho queries the registryWho balancesExample productsMain cost
Client-side discoveryThe clientThe clientNetflix Eureka + Ribbon, gRPC name resolver, Consul HTTP API, etcd watchA library per language, client logic to upgrade
Server-side discoveryA router or load balancerThe routerKubernetes Service (kube-proxy), AWS ELB, NGINX/HAProxy fed by a registryAn extra hop; the router must be highly available
DNS discoveryThe OS or client resolverRound-robin DNS, or the client over SRVCoreDNS, Consul DNS, AWS Cloud Map, Route 53TTL caching and clients that resolve once
Mesh discoveryThe sidecar proxy, fed by a control planeThe sidecarEnvoy with xDS/EDS, IstioOperating the control plane and proxies

The three probes.

ProbeQuestionOn failureTypical endpointMust not check
Startup"Has it finished starting?"Kill and restart (after the budget)/startupzAnything slow after boot
Liveness"Is the process stuck beyond repair?"Restart the container/livez (Laravel: /up)Databases, other services
Readiness"May it take traffic now?"Remove from endpoints, no restart/readyzOptional dependencies

Three numbers to remember. Eureka's defaults: a heartbeat every 30 s, removal after about 90 s of silence. CoreDNS in Kubernetes answers with a 5 s TTL by default. A pod gets 30 s by default (terminationGracePeriodSeconds) between SIGTERM and SIGKILL. A dead instance stays visible for the sum of detection time and every cache after it.

Why it exists ​

In a monolith, "calling orders" is a function call; the address is a symbol the linker resolves. Split it into services and the address becomes a network location that changes. Richardson lists the forces: the number of instances and their locations change dynamically, "virtual machines and containers are usually assigned dynamic IP addresses", and instance counts vary with load, for example when an EC2 Autoscaling Group adjusts them. Add crashes, rolling deploys, spot-instance reclaims and node drains, and a config file with orders=10.0.3.17:8080 is wrong within hours.

Static addressesDiscovery
Simple, works for three servers that never moveA moving part that must itself be reliable
Failure of a host means an outage until a human edits configFailure of a host is removed from the list automatically
Scaling out means editing every clientScaling out means starting instances; they register themselves
No dependency on a registryThe registry (or DNS, or the platform) becomes critical infrastructure

Everyday picture. A restaurant with a changing staff. Static addresses are a laminated card with "ask Maria for table 4"; Maria goes home and the card is wrong. Discovery is the host stand: staff check in when they start (registration), the host removes anyone who walks out (deregistration) or stops answering for ten minutes (lease expiry), and guests are sent to whoever is on the floor and not in the middle of a break (health). Server-side discovery is the guest asking the host to seat them; client-side is the guest reading the staff board and choosing a table.

Three common misunderstandings, up front ​

  • "Service discovery is DNS." DNS is one transport for a registry. It has no health semantics by itself, caches by design, and returns addresses, not "which instances are ready". Kubernetes uses DNS on top of EndpointSlices that carry readiness.
  • "If the instance is registered, it is healthy." Registered means "someone told the registry it exists". Healthy means "a check said it can serve". Registered-but-not-ready instances are the classic source of 502s during deploys.
  • "Discovery removes the need for retries and timeouts." Discovery narrows the window in which you call dead instances; it never closes it. Every client still needs a timeout, a retry on another instance and a circuit breaker.

Where it comes from ​

  • Before microservices: fixed hosts, hosts files, round-robin DNS and hardware load balancers. DNS SRV records (RFC 2782, February 2000) already allowed "move services from host to host with little fuss" and "designate some hosts as primary servers for a service and others as backups" (read in the RFC text), but ordinary HTTP clients do not use them by default; you must ask for SRV explicitly.
  • The cloud era: servers "come and go" in AWS. Netflix built Eureka for mid-tier load balancing because the AWS ELB was an edge load balancer and, in EC2 Classic, putting mid-tier services behind it exposed them to the outside world (Eureka wiki). Eureka made a deliberate choice: the registry is replicated between peers, clients cache it, and a registry outage must not stop calls.
  • Registries with consensus: Apache ZooKeeper, then etcd and Consul put service registration on top of a consistent store (Raft in etcd and Consul), with leases, watches and health checks.
  • Platforms absorb it: Kubernetes made the Service object plus cluster DNS the default; Richardson's pattern catalogue already notes that "some systems such as Kubernetes, Marathon and AWS ELB have an implicit service registry".
  • Meshes: Envoy's xDS APIs turned discovery into a streaming configuration protocol pushed to proxies next to every instance; Envoy's docs argue that discovery "does not require full consistency" (see Registry consistency).

The concept catalogue ​

Each block has the same order: plain words, the usual misunderstanding, the definition, a timeline, real scenarios, per-product behaviour, and how to use it.

Service registry Must-know ​

In plain words: a registry is a database of "service name → live instances (address, port, metadata)" that clients or proxies read and instances write.

Common misunderstanding: "The registry is a configuration file for addresses." Addresses are the easy part. The hard parts are liveness (who is still there), change notification (watch instead of poll) and availability (it sits on the path of every deploy and often every request).

Definition: Richardson: "a service registry, which is a database of services, their instances and their locations. Service instances are registered with the service registry on startup and deregistered on shutdown. Client of the service and/or routers query the service registry to find the available instances of a service." Its cost: it "is a critical system component" and "must be highly available"; clients "should cache data provided by the service registry".

InstanceRegistryClient (watcher)1 register(id, addr, ttl=6s) lease starts2 renew every ttl/3 = 2s (heartbeat, ready=true)3 renew ... renew ...4 watch event: list = [i1, i2]A SIGTERM: renew(ready=false) drain startsA wait drainDelay, then deregister(id)A watch event: list = [i1] (gap = about 1 heartbeat)B CRASH (kill -9, OOM, node loss): heartbeats just stopB registry still lists it until the lease expires; clients get errorsB lease expires after ttl: reaper removes it, watch eventclients: passive ejection on error, then the new list arrivesRule: ttl short = fast detection but more renewals and false expiry under GC pauses; ttl long = long stale window.
text
     Instance orders-1          Registry                  Client billing
1    PUT register(orders, 10.0.3.17:8080, ttl=6s)  ->  stored, lease starts
2                                                      <-  GET orders?index=0   (list: [orders-1])
3    PUT renew (every 2 s)                          ->  lease extended
4    Instance orders-2 registers                    ->  index 7 -> 8, watchers woken
5                                                      <-  GET orders?index=8   (list: [orders-1, orders-2])

Real scenarios: Netflix Eureka behind Ribbon (client-side); Consul's catalog read through its DNS interface; Kubernetes' EndpointSlices read by kube-proxy and CoreDNS; AWS Cloud Map where instances call RegisterInstance and clients call DiscoverInstances ("if you specified health checking ... AWS Cloud Map returns only healthy instances"); etcd keys with leases for in-house systems.

ProductRegistry storageConsistencyChange notification
EurekaIn-memory registry replicated between peer serversEventually consistent, availability firstClients poll deltas (about every 30 s by default)
ConsulRaft-replicated catalog in the servers, agents on every nodeStrong by default per read mode (default, consistent, stale)Blocking queries (index, wait), DNS
etcdRaft key-value store, leasesReads are linearizable by default; serializable (local, possibly stale) reads are opt-inWatch API
ZooKeeperQuorum-replicated tree; Richardson lists it as a registry (its ephemeral-node details were not re-checked for this page)Strong writesWatches
KubernetesEndpointSlice objects in etcd via the API serverStrong in etcd, eventual to every nodeWatch (kube-proxy, CoreDNS, Envoy-based gateways)
AWS Cloud MapManaged namespaces/services/instancesManaged (AWS does not publish the model)DiscoverInstances, DNS

Fix / how to use it: in Go the whole idea is under 200 lines (registry and heartbeat client); in production use the one your platform already runs. A registry you operate yourself is another stateful, quorum-based cluster.

Registration: self-registration vs third-party registration Must-know ​

In plain words: either each instance announces itself ("I am here"), or someone else watches instances start and stop and does the announcing.

Common misunderstanding: "Self-registration is always the simple choice." Richardson's catalogue lists its cost: it couples the service to the registry, you re-implement it per language, and "a service instance that is running yet unable to handle requests will often lack the self-awareness to unregister itself". Third-party registration has the opposite problem: the registrar "might only have superficial knowledge of the state of the service instance".

Definition: Self-registration: the instance registers on startup, "must typically periodically renew its registration", and unregisters on shutdown. Third-party registration: "a 3rd party registrar is responsible for registering and unregistering a service instance".

text
     Self-registration                                Third-party registration
1    instance starts                                  scheduler starts the container
2    instance -> registry: register                   registrar sees the start event
3    instance -> registry: renew, renew, ...          registrar -> registry: register
4    instance -> registry: deregister (on SIGTERM)    registrar probes /readyz, updates the entry
5    crash: no deregister, the lease expires          registrar sees the container die -> deregister
StyleExamples (from the pattern pages and docs)ProsCons
Self-registrationSpring Cloud with Eureka (@EnableEurekaClient), the Go client in this chapter, Consul PUT /agent/service/register from the appInstance knows its own state (STARTING, AVAILABLE, DRAINING); no extra componentLibrary per language; a stuck instance may keep renewing
Third-party: platformKubernetes (controllers create EndpointSlices from pods and readiness), AWS Auto Scaling groups registering with ELBNo code in the serviceOnly as smart as the probes you define
Third-party: sidecar / agentNetflix Prana (sidecar that registers a non-JVM app with Eureka), Consul agent with service definition files, Registrator for DockerLanguage independent, can run health checksAnother process per host or pod

Real scenarios: a Laravel app never talks to a registry: Kubernetes or a Consul agent registers it. A Go service in a VM fleet self-registers with Consul and sets DeregisterCriticalServiceAfter as a safety net. A legacy PHP service on a VM gets a Consul service-definition file and the agent probes /up.

Fix / how to use it: prefer third-party (platform or agent) for polyglot fleets; use self-registration when the instance has state the platform cannot see (for example "warming a cache" or "draining"), and then publish that state with every heartbeat, as the Go client does with ready=false.

Leases, TTLs, heartbeats and deregistration Must-know ​

In plain words: an entry in the registry is rented, not owned; the instance must keep paying (heartbeat) or the entry disappears.

Common misunderstanding: "Deregistration happens on shutdown, so I do not need TTLs." Only graceful shutdown deregisters. kill -9, an out-of-memory kill, a node loss and a network partition do not, and those are exactly the cases discovery exists for.

Definition: a lease is a time-bounded registration. etcd: "Leases are a mechanism for detecting client liveness. The cluster grants leases with a time-to-live. A lease expires if the etcd cluster does not receive a keepAlive within a given TTL period"; keys attached to the lease are deleted with it. Eureka: "send heartbeats to renew their leases every 30 seconds. If the client cannot renew the lease for a few times, it is taken out of the server registry in about 90 seconds." Consul has TTL checks: "if the check does not receive a status update before the specified duration, the health check enters a critical state."

text
     TTL = 6 s, heartbeat every TTL/3 = 2 s
0 s  register                  expires at 6 s
2 s  renew                     expires at 8 s
4 s  renew                     expires at 10 s
5 s  CRASH (no more renewals)
10 s lease expires, entry removed    -> detection time = TTL - (time since last renew) = 1..6 s
     clients with a watch learn at ~10 s; clients polling every 30 s learn up to 30 s later
KnobToo smallToo largeTypical rule
TTLFalse expiries during GC pauses, CPU starvation, short network blipsDead instances listed for long3x heartbeat interval; 10 to 30 s for most services
Heartbeat intervalRegistry write load grows with instances x frequencySlow detectionTTL/3, with jitter so heartbeats do not synchronise
Deregister-after-critical (Consul DeregisterCriticalServiceAfter)Instances removed during a long deploy or incidentZombie entries foreverMinutes, not seconds
Client refresh interval (poll)Registry read loadStale client listsPrefer a blocking query or watch

Real scenarios: a JVM full GC of 8 s with a 6 s TTL makes a healthy instance flap out and back; a registry restart with in-memory state loses every lease and instances must re-register (the Go client re-registers on 404); Eureka's server "stops expiring instances" during self-preservation (see Consistency).

Fix / how to use it: SQL for the case where your registry is a table (monolith and modular monolith with a few worker processes). Liveness lives in expires_at, so correctness needs no reaper; the delete only keeps the table small.

sql
CREATE TABLE service_instance (
    id          text PRIMARY KEY,
    service     text        NOT NULL,
    addr        text        NOT NULL,            -- host:port
    ready       boolean     NOT NULL DEFAULT false,
    meta        jsonb       NOT NULL DEFAULT '{}',
    expires_at  timestamptz NOT NULL
);
CREATE INDEX service_instance_lookup ON service_instance (service) WHERE ready;

-- register or re-register
INSERT INTO service_instance (id, service, addr, ready, expires_at)
VALUES ($1, $2, $3, $4, now() + interval '6 seconds')
ON CONFLICT (id) DO UPDATE
   SET addr = EXCLUDED.addr, ready = EXCLUDED.ready, expires_at = EXCLUDED.expires_at;

-- heartbeat every 2 seconds: 0 rows updated means the lease is gone, register again
UPDATE service_instance SET expires_at = now() + interval '6 seconds', ready = $2 WHERE id = $1;

-- lookup: the lease check IS the liveness check
SELECT id, addr FROM service_instance
 WHERE service = 'orders' AND ready AND expires_at > now();

-- housekeeping only
DELETE FROM service_instance WHERE expires_at < now() - interval '1 minute';

Go: registry and regclient/keepalive.go do the same with Renew returning ErrUnknown. Laravel: you rarely write this; if you do, DB::table('service_instance')->upsert(...) and a scheduled delete().

Client-side discovery Must-know ​

In plain words: the caller asks the registry for the list and picks an instance itself.

Common misunderstanding: "Client-side means one registry call per request." No: clients cache the list, watch for changes and balance locally. Eureka's wiki says so: the information "is cached on the client", so "your application can be resilient to the outages of the load balancers" and the registry.

Definition: the client holds (a) a name resolver that talks to the registry and (b) a balancer that picks among the instances. Richardson: benefit, "fewer moving parts and network hops compared to server-side discovery"; drawbacks, "couples the client to the Service Registry" and "you need to implement client-side service discovery logic for each programming language/framework". gRPC's load-balancing post gives the table: proxy LB has a simple client and works with untrusted clients but puts the LB in the data path with higher latency; client-side LB gives high performance by eliminating the extra hop but means a complex client, a per-language implementation burden, and "client needs to be trusted, or the trust boundary needs to be handled by a lookaside LB".

text
     Client (billing)                          Registry               orders-1 / orders-2
1    start: Watch("orders")                 ->  GET ?index=0           
2                                            <-  [o1, o2], index 8
3    request #1: pick o1 (round robin)       ----------------------------------------> o1
4    request #2: pick o2                     ----------------------------------------> o2
5    o2 crashes
6    request #3: pick o2 -> connect error; Fail(o2) (eject for 5 s); retry -> o1
7                                            <-  watch event: [o1], index 9 (after TTL)
VariantWho watches the registryExampleNotes
Thick clientEvery client processNetflix Ribbon with Eureka; Go regclient.WatchMaximum control; every language needs the library
gRPC name resolvergRPC channel, plugin per schemedns:///, custom registry:/// resolver (Go)round_robin policy balances across resolved addresses
Lookaside LBA separate balancer server that clients askgRPC "lookaside" / xDS-styleClients stay thin, LB is off the data path
Proxy-based client (sidecar)A local proxy per hostNetflix Prana, Envoy sidecarLooks client-side to the host, server-side to the app

Real scenarios: Netflix services calling each other through Ribbon with Eureka; a Go gateway with a registry:///orders gRPC channel; a batch job that reads Consul GET /v1/health/service/orders?passing once at start.

What provides it: Eureka client (Java), Consul API clients, etcd client watches, gRPC resolvers (Go, Java, C++), HashiCorp's Consul "native app integration". PHP rarely does it because short-lived requests make a per-process watch pointless; PHP apps use DNS or an agent on the host.

Fix / how to use it: Go registry client with a watched list and gRPC resolver.

Server-side discovery Must-know ​

In plain words: the caller sends the request to a fixed address; a router that knows the instances forwards it.

Common misunderstanding: "Server-side means no registry." The registry still exists, inside the router or the platform; you just do not see it. In Kubernetes it is the set of EndpointSlices.

Definition: Richardson: "the client makes a request via a router (a.k.a load balancer) that runs at a well known location. The router queries a service registry, which might be built into the router, and forwards the request to an available service instance." Benefits: "the client code is simpler"; and "some cloud environments provide this functionality". Drawbacks: unless it is part of the cloud environment, the router is another component "replicated for availability and capacity", it must support the protocols you use, and "more network hops are required".

text
     Client (billing)             Service orders (ClusterIP 10.96.4.2)     kube-proxy / node rules        Pods
1    GET http://orders.shop.svc/    ->  DNS: orders.shop.svc.cluster.local = 10.96.4.2
2    connect 10.96.4.2:80           ->  node rules (iptables, IPVS or nftables) pick a ready endpoint
3                                       DNAT to 10.244.1.7:8080                                        -> pod
4    pod fails readiness            ->  EndpointSlice ready=false -> rules updated on every node (lag)
Router typeRegistry sourceLevelExamples
Platform virtual IPEndpointSlices (the Kubernetes Service)L4, per connectionKubernetes ClusterIP with kube-proxy (iptables, ipvs or nftables modes)
Cloud load balancerTarget groups, auto scaling group membershipL4 or L7AWS ELB/ALB, GCP load balancers; ELB "also functions as a Service Registry"
Reverse proxy fed by a registryConsul, etcd, Docker or Kubernetes providerL7Traefik, NGINX + consul-template, HAProxy with DNS service discovery, Envoy
Edge gatewaySame sourcesL7API gateway

Real scenarios: every Kubernetes service-to-service call over a ClusterIP; an internal ALB in front of an ECS service; Traefik routing to Docker containers by label. In all of these the client sees one stable name.

Fix / how to use it: Kubernetes manifests in Mechanics and the Laravel config in Laravel. Watch two costs: long-lived HTTP/2 or gRPC connections defeat per-connection balancing at L4 (all RPCs stay on one pod), so use an L7 proxy, a headless Service with a client-side policy, or a mesh; and the router's own HA.

Client-side vs server-side: the comparison ​

Client+ LB logicRegistryConsul / Eureka / etcdorders-1orders-2orders-3Clientname onlyLB / proxyfixed addressRegistrybuilt in or externalorders-1orders-2orders-3Client-side discoveryServer-side discovery1 query2 list (cached, watched)3 picks one, calls directlyOne hop fewer. Every language needs the client library.Examples: Eureka + Ribbon, gRPC resolver, Consul API.Simple clients. The proxy is in the data path and must be HA.Examples: Kubernetes Service, AWS ELB, Envoy.1 call2 lookup3 forward
QuestionClient-sideServer-side
Extra network hopNoYes (router in the data path)
Client complexityHigh: library, cache, balancer, retriesLow: one name
Polyglot fleetOne implementation per languageLanguage independent
Load-balancing intelligenceCan use request-level signals, zone, latency, weightsWhatever the router supports
Failure of the registryClients keep the cached list (stale but working)Router keeps its last config; new instances do not appear
Failure of the routerNot applicableThe whole path fails unless the router is HA
Trust boundaryClients must be trusted with the full instance listClients see only the router
Upgrade pathRoll out a new library to every serviceUpgrade the router once
ObservabilityEach client emits its own metricsOne place for LB metrics
Typical fitHomogeneous fleet, high performance (Netflix-style, gRPC)Mixed fleet, platform-managed (Kubernetes, cloud)

Mesh discovery (below) is the hybrid: balancing happens in a client-side proxy (the sidecar) fed by a control plane, so applications stay simple while the instance list is known at the caller.

DNS-based discovery: A/AAAA, SRV, TTL, headless services Must-know ​

In plain words: instead of a registry API, publish instances as DNS records so every program that can resolve a name can find them.

Common misunderstanding: "DNS with a short TTL gives instant failover." Kubernetes' own docs explain why they do not rely on DNS round robin for Services: "there is a long history of DNS implementations not respecting record TTLs, and caching the results of name lookups after they should have expired. Some apps do DNS lookups only once and cache the results indefinitely. Even if apps and libraries did proper re-resolution, the low or zero TTLs on the DNS records could impose a high load on DNS."

Definition: an A or AAAA record maps a name to an IP; several records for one name give round-robin DNS. An SRV record (RFC 2782) maps _service._proto.name to priority weight port target: "a client MUST attempt to contact the target host with the lowest-numbered priority it can reach; target hosts with the same priority SHOULD be tried in an order defined by the weight field." SRV is what carries the port and failover order. A headless Service (clusterIP: None) has no virtual IP: "kube-proxy does not handle these Services, and there is no load balancing or proxying done by the platform"; DNS returns the pod IPs directly and, in the Kubernetes DNS docs, "clients are expected to consume the set or else use standard round-robin selection from the set".

text
     Client                          CoreDNS (Kubernetes)                         API server
1    resolve orders.shop.svc.cluster.local A
2                                    ClusterIP Service -> one A record: 10.96.4.2        (kube-proxy balances)
3    resolve orders-hl.shop.svc.cluster.local A        (headless Service)
4                                    -> A 10.244.1.7, A 10.244.2.9, A 10.244.3.4          (one per ready pod, TTL 5 s)
5    resolve _http._tcp.orders-hl.shop.svc.cluster.local SRV
6                                    -> SRV 0 33 8080 pod-a.orders-hl.shop.svc.cluster.local. (one per pod)
7    pod 10.244.2.9 fails readiness  -> EndpointSlice updated -> next DNS answer omits it
8    client that cached the A set for 60 s keeps calling 10.244.2.9 for up to 60 s
RecordCarriesUsed byLimits
A / AAAAIPv4 / IPv6 addressEverythingNo port, no weights, no health, caching
SRVPriority, weight, port, target hostConsul DNS, Kubernetes named ports, Cloud Map, SIP/XMPP, gRPC grpclbMany HTTP clients ignore SRV; Go net.LookupSRV and PHP dns_get_record(..., DNS_SRV) need you to use it explicitly
CNAMEAliasExternalName Services, DNS aliasesRedirection at DNS level, no proxying
TXTMetadataRare for discoveryNo standard schema
ProductWhat DNS returnsTTL / cachingNotes
Kubernetes + CoreDNSClusterIP A record; headless Service: all pod IPs; SRV per named portCoreDNS kubernetes plugin ttl default 5 s, max 3600, 0 disables cachingPod resolv.conf has search domains and options ndots:5, so short names try several suffixes
Consul DNS<name>.service.consul A and SRV; failing instances omitted; results randomisedPer Consul DNS config"Consul randomizes DNS SRV records and ignores weights specified in service configurations", so weights are unreliable over DNS
AWS Cloud MapDNS records in a VPC (or public) namespace, only healthy instances when health checking is onPer record TTL you setAlternative: DiscoverInstances API
Docker ComposeService name resolves to container IPs on the project networkDocker's embedded DNS"Each service registers its name with an internal DNS server"; IPs change when recreated
Route 53 / public DNSRecords you publishResolver and TTL dependentEureka's wiki: traffic "can still be routed to servers which may not be healthy or may not even exist"

Real scenarios: a Laravel app calling http://orders.shop.svc.cluster.local:8080 (ClusterIP, no client logic); a Go gRPC client on dns:///orders-hl.shop.svc.cluster.local:8080 with round_robin (headless Service); a VM fleet using orders.service.consul through dnsmasq forwarding; a job resolving _amqp._tcp.broker.internal SRV to find the broker port.

Fix / how to use it: Go SRV lookup with a refresh loop, PHP SRV resolver with a short application cache. Rules: cap the cache in your own code (gRPC's DNS resolver, for example, limits re-resolution to at most once per 30 s by default, MinResolutionInterval), re-resolve on connection errors, set connection max-age so keep-alive connections do not pin old addresses, and prefer headless-plus-client-balancing or a ClusterIP over bare round-robin A records.

Health checks: liveness, readiness and startup Must-know ​

In plain words: three different questions, three different reactions. Startup: has it finished booting? Liveness: is it hopelessly stuck? Readiness: may it take requests right now?

Common misunderstanding: "One /health endpoint is enough." One endpoint cannot answer all three, because the reaction differs: a failing liveness probe restarts the container, a failing readiness probe only removes it from traffic. If a database outage fails the single endpoint, Kubernetes restarts every pod, which makes recovery slower.

Definition (Kubernetes): "Startup probes verify whether the application within a container is started. If a startup probe is configured, Kubernetes does not execute liveness or readiness probes until the startup probe succeeds." "Liveness probes determine when to restart a container", for example to catch a deadlock. "Readiness probes determine when a container is ready to accept traffic", and "if the readiness probe returns a failed state, the EndpointSlice controller removes the Pod's IP address from the EndpointSlices of all Services that match the Pod." Caution from the docs: "the readiness and liveness probes do not depend on each other to succeed." Readiness probes "run on the container during its whole lifecycle", not only at start.

NEW pod (v2)image pull, startstartup probereceives traffic (readiness passing, in Service endpoints)liveness runs from here; it only restarts on deadlock, not on a dependency outagestartupProbe: failureThreshold x periodSeconds is the warm-up budgetreadiness succeeds: EndpointSlice ready=true, then proxies / DNS / Envoy catch upOLD pod (v1)serving normallypreStopdrain delayin-flightterminating: EndpointSlice ready=false (else you flip it)removal propagates in parallel; late requests: keep servingTERM after preStop; finish in-flight work, then exitWithout a readiness probe the new pod gets traffic before it is warm; without preStop plus drain the old pod drops requests.Order matters: the new pod must be Ready before the old pod starts draining (rolling update maxUnavailable / maxSurge).
text
     Pod lifecycle (probes)                               Effect
1    container starts                                     no traffic (not Ready)
2    startupProbe every 10 s, failureThreshold 30         budget 300 s; success moves on; failure: container killed, restartPolicy applies
3    startup succeeded                                    livenessProbe and readinessProbe begin
4    readinessProbe succeeds                              pod IP appears as ready in EndpointSlices -> receives traffic
5    DB unreachable, readiness fails                      pod IP removed from endpoints; container NOT restarted
6    deadlock, liveness fails failureThreshold times      kubelet restarts the container
7    SIGTERM: readiness already failing (drain)           no new traffic, in-flight work completes
ProbeMechanism optionsDefault behaviour on failureKey fieldsUsed by
Kubernetes startuphttpGet, tcpSocket, exec, grpcContainer killed, then restartPolicyfailureThreshold, periodSeconds (budget = product)kubelet
Kubernetes livenesssameContainer restartedinitialDelaySeconds, periodSeconds, timeoutSeconds, failureThresholdkubelet
Kubernetes readinesssameRemoved from Service endpointssame, plus successThresholdkubelet, EndpointSlice controller
Consul checksHTTP, TCP, UDP, gRPC, script, OS service, TTL, aliasNew checks start critical; critical instances are omitted from DNS and ?passing queriesInterval, Timeout, DeregisterCriticalServiceAfterConsul agent
Envoy active health checkingHTTP, gRPC, L3/L4 byte bufferHost marked unhealthy after N failures, back after M successesinterval, unhealthy/healthy thresholdsEnvoy
AWS Cloud MapRoute 53 health checks or a third-party checkerOnly healthy instances returnedper serviceCloud Map
EurekaClient heartbeat (lease) plus optional health check handlerLease expiry removes the instancerenewal interval, lease durationEureka server

Consul's default is the right instinct for everyone: "When checks are registered against a Consul agent, they are assigned a critical status by default. This prevents services from registering as passing and entering the service pool before their health is verified." Kubernetes readiness works the same way: a new pod is not Ready until the probe passes. The Laravel health route (/up, the health option of withRouting) returns 200 "if the application has booted without exceptions"; Laravel dispatches Illuminate\Foundation\Events\DiagnosingHealth there so you can add checks, and you may "throw an exception from the listener".

Real scenarios: a Rails/Laravel app that needs 40 s to warm its caches gets a startup probe instead of a huge initialDelaySeconds; a service that loses its Redis becomes unready (not restarted) while it reconnects; a deadlocked Go worker pool is restarted by liveness.

Fix / how to use it: Go health package (/livez, /startupz, /readyz), Laravel /up plus /readyz, manifests in Mechanics.

Deep vs shallow checks, and dependency checks Important ​

In plain words: a shallow check asks "is this process answering"; a deep check also asks "can it reach its database, cache and the services it calls".

Common misunderstanding: "Deeper is safer." A deep liveness check turns a shared dependency's outage into a fleet-wide restart storm; a deep readiness check across many dependencies turns one flaky, optional dependency into an empty pool. This is the cascading failure pattern applied to probes (our reading of the Kubernetes probe semantics above; the rule that readiness must reflect only what the pod cannot work without is standard operating practice, not a quoted guarantee).

Definition: shallow = no outbound calls (process, event loop, thread pool). Deep = outbound calls with a timeout. The safe split:

CheckIncludeExcludeWhy
LivenessEvent loop responsive, no deadlock, memory saneAny network dependencyA dependency outage cannot be fixed by restarting this pod
ReadinessStarted, not draining, critical local dependencies (own database, own cache that the request path cannot bypass)Optional services, downstream services you can degrade aroundIf readiness fails everywhere, the Service has zero endpoints and the outage is total
StartupConfig loaded, migrations check, warm-up completeSlow optional workKeep the budget focused
Synthetic deep check (separate endpoint, e.g. /healthz/deep)Everything, with timingsDo not wire to probesFor humans and dashboards
text
     Readiness checks the shared payments API (optional for browsing)
1    payments API slow -> every pod's /readyz times out
2    all pods unready -> Service has 0 endpoints -> 100% of requests fail, including those that never needed payments
     Better: readiness ignores payments; the circuit breaker returns "payments unavailable" only for checkout
Dependency typeReadiness?Cache the result?Timeout
Own primary databaseYes (cheap select 1)1 to 5 sBelow the probe timeout
Own cache (Redis) on the hot pathOnly if there is no fallback1 to 5 sSame
Another microserviceNo (use a circuit breaker)n/an/a
Message brokerOnly for pure consumers that cannot do anything without it5 sSame
Feature-flag service, analytics, emailNevern/an/a

Fix / how to use it: the Go health.Check has Critical, Timeout and MaxAge so probes never hammer the database; the Laravel ReadinessGate caches the database result for 3 s (the array cache only helps under Octane; under PHP-FPM every request re-checks).

Check intervals, thresholds and flapping Important ​

In plain words: probes run on a timer and need several failures or successes in a row, otherwise a single slow response flips an instance in and out of traffic ("flapping").

Common misunderstanding: "Faster probes mean faster recovery." Faster probes mean more load on the app and more false positives; recovery speed is bound by the slowest cache after the check (see the staleness chain).

Definition: detection time = about periodSeconds x failureThreshold plus timeoutSeconds; recovery time = periodSeconds x successThreshold. Envoy's health checking supports "check interval, failures required before marking a host unhealthy, successes required before marking a host healthy", and an HTTP check, "by default, it expects a 200 response if the host is healthy".

SettingEffectTypical start
periodSecondsProbe frequency5 to 10 s readiness, 10 s liveness
timeoutSecondsPer-probe patience1 to 2 s; below the app's slow-query timeouts
failureThresholdFailures in a row before reacting3 readiness, 3 or more liveness, startup large
successThresholdSuccesses in a row to become ready1 (liveness must be 1)
Startup budgetfailureThreshold x periodSecondsWorst-case boot time with margin (the K8s example: 30 x 10 s = 300 s)
JitterSpreads heartbeats and checks10 to 20 %
text
     Flapping readiness (period 2 s, failureThreshold 1, a 2.5 s GC pause every minute)
1    t=0   ready
2    t=60  probe times out -> not ready -> removed from endpoints
3    t=62  probe ok -> ready -> added back
4    every removal re-balances connections and churns EndpointSlices on every node -> use failureThreshold 3

Real scenario: a payments pod set flaps during a traffic spike: each probe hits a saturated pod, fails, removes it, the remaining pods receive more load and also fail, until the Service has no endpoints. Fix: readiness must not depend on request-path capacity; use load shedding instead.

Fix / how to use it: start with 5 s period, 3 failures, 1 s timeout; watch endpoint churn (Observability) and adjust from data.

Graceful shutdown and drain Must-know ​

In plain words: before a pod stops, it must first stop receiving new requests, wait until everyone has noticed, and only then finish what it has and exit.

Common misunderstanding: "On SIGTERM I call server.Shutdown() and I am safe." Removal of the pod from endpoints happens in parallel with the kubelet starting the shutdown (preStop first, then SIGTERM), not before it, and takes time to reach every proxy, DNS cache and client list. Requests still arrive after SIGTERM; if you stop accepting at once they fail with connection refused.

Definition: Kubernetes: "a Pod is granted a term to terminate gracefully, which defaults to 30 seconds"; the kubelet sends TERM, and "once the grace period has expired, the KILL signal is sent to any remaining processes". The Kubernetes pod-termination page adds the ordering: "at the same time as the kubelet is starting graceful shutdown of the Pod, the control plane evaluates whether to remove that shutting-down Pod from EndpointSlice objects"; those endpoints are not removed at once but marked terminating, and "terminating endpoints always have their ready status as false ... so load balancers will not use it for regular traffic". The kubelet runs the preStop hook first, then sends TERM. Google's SRE chapter on load balancing calls the middle state lame duck: the task "is listening on its port and can serve, but is explicitly asking clients to stop sending requests". Its shutdown steps: the scheduler sends SIGTERM; the task enters lame duck state; ongoing requests execute normally; active requests decrease to zero; "after a configured interval, the backend task either exits cleanly or the job scheduler kills it", with a rule of thumb "between 10s and 150s".

text
     Old pod                           Endpoints / proxies / DNS          Clients
1    deletion requested                -> pod marked Terminating; the control plane starts removing it from EndpointSlices AT THE SAME TIME (ready=false, terminating=true)
2    preStop hook (e.g. sleep 8)
3    Kubernetes: ready=false already set by termination; other systems: your readiness / heartbeat flips   proxies update, caches expire (lag)
4    ... late requests still arrive    <------------------------------------ keep serving them
5    SIGTERM -> server.Shutdown(): stop accepting, finish in-flight
6    exit 0 (or SIGKILL when terminationGracePeriodSeconds elapses)
StepDuration to planWhere it lives
Pod marked terminating (Kubernetes) or readiness flipped (other systems); endpoint removedController lag (Kubernetes) or probe/heartbeat periodkubelet, EndpointSlice controller
Propagation to proxies, DNS, client listsThe slowest layer you have (see staleness chain)kube-proxy, CoreDNS, Envoy, client caches
In-flight request completionThe longest legitimate requestYour server's Shutdown timeout
TotalMust be below terminationGracePeriodSecondsPod spec

In EndpointSlices, "service proxies will normally ignore endpoints that are terminating, but they may route traffic to endpoints that are both serving and terminating if all available endpoints are terminating", so a drain can survive a full rollout.

Real scenarios: a rolling deploy returning a burst of 502s because the old pods exited the instant SIGTERM arrived; a long-poll or WebSocket service needing a 60 s grace; a batch consumer finishing its current message before exit (competing consumers).

Fix / how to use it: Go health.Serve (StartDrain, sleep drainDelay, Shutdown), Laravel app:drain command for the preStop hook.

Load-balancing integration Important ​

In plain words: discovery gives you the candidate list; the balancer decides which candidate gets this request.

Common misunderstanding: "Round robin is fair." It is fair in count, not in cost. Google's SRE chapter: the most expensive requests can consume "1000x (or more) CPU than the cheapest requests", so equal counts mean unequal load.

Definition: the algorithms are taught in Load Balancing; here is only what discovery adds.

PolicyNeeds from discoveryGood forWatch out
Round robinThe ready listUniform, cheap requestsHot spots when costs differ; thundering herd to a new instance
Weighted round robinWeights/metadata per instance (Eureka metadata, Consul Weights, EDS weights)Mixed instance sizes, canariesWeights go stale; SRV weights are ignored by Consul DNS
Least connections / least loadedLive per-connection counts (client or proxy side)Variable request costFast-failing sick backends look idle: SRE calls it "sinkholing", fix by counting recent errors as active requests
Consistent hashingStable instance identitiesCaches, sticky shards, consistent hashingRegistry churn reshuffles keys
Zone-aware / localityZone of each endpoint (EDS "zone", Kubernetes topology hints)Latency and cross-zone costZone imbalance; fallbacks
SubsettingLarge instance listsLimit connections per clientUneven subsets if done naively
Random with two choices, panic modeHealth stateResilience when most hosts look unhealthyHides outages if overused

Envoy states why EDS is preferred: "Envoy has explicit knowledge of each upstream host (vs. routing through a DNS resolved load balancer) and can make more intelligent load balancing decisions", and "extra attributes carried in the discovery API response for each host inform Envoy of the host's load balancing weight, canary status, zone, etc." Kubernetes' Topology Aware Routing populates a hints field on EndpointSlices "to allocate it to a zone", so that components such as kube-proxy can keep traffic in the zone it originated.

Real scenario: a gRPC client on a ClusterIP sends every RPC to one pod because HTTP/2 multiplexes all RPCs on one TCP connection chosen once; the fix is round_robin over a headless Service or an L7 proxy (gRPC blog: L3/L4 vs L7).

Fix / how to use it: the Go RoundRobin skips ejected instances (passive health checking) and falls back to "try one anyway" when all are ejected.

Registry consistency: AP vs CP, stale entries Important ​

In plain words: when the registry's own servers cannot agree (a network split), you choose between answering with possibly stale data and refusing to answer.

Common misunderstanding: "A discovery system must be strongly consistent." Envoy's docs argue the opposite: "many existing RPC systems treat service discovery as a fully consistent process. To this end, they use fully consistent leader election backing stores such as Zookeeper, etcd, Consul, etc. Our experience has been that operating these backing stores at scale is painful. Envoy was designed from the beginning with the idea that service discovery does not require full consistency." Combine eventually consistent discovery with active health checking.

Definition: see CAP and PACELC. Registries differ:

SystemLeaningEvidenceBehaviour during a partition
EurekaAvailability first (our reading, "AP-style"; Netflix's wiki does not use the CAP label)Peers replicate; clients cache; "the information is reconciled on the next heartbeat"; self-preservation: if renewals fall "below the percent configured for that value (below 85% within 15 mins), the server stops expiring instances to protect the current instance registry information"Keeps serving possibly stale entries; clients "must make sure they are resilient to eureka server returning an instance that is non-existent or un-responsive"
ConsulCP for the catalog (Raft); read modes tunableQuorum "at least (N/2)+1"; if quorum is lost "the Consul cluster becomes unavailable because no new logs can be committed"; read modes default, consistent, staleWrites (registrations) stop without a leader; stale reads still work on any server
etcdCP (Raft)Linearizable reads by default; serializable local reads optional; leasesMinority side cannot commit; leases cannot be renewed there
KubernetesCP store (etcd) behind an API server; eventual to every node proxyEndpointSlices propagate via watchNodes keep their last programmed rules
Envoy + EDSEventual by design2x2 matrix belowKeeps routing on last known endpoints

Envoy's matrix of discovery status against health-check result: discovered + check OK: route; absent + check OK: route ("very important since the design assumes that the discovery service can fail at any time"); discovered + check failed: don't route ("health check data is assumed to be more accurate than discovery data"); absent + check failed: don't route, and delete.

Consul's read-mode text explains staleness: by default "agents forward catalog read requests to the cluster leader" and use leader leasing, so "Consul may occasionally return a stale result, but it processes reads faster"; consistent verifies with a quorum at extra latency; stale "allows any server to service the read ... more likely to return stale value" but also "allows reads without a leader, meaning that Consul servers can still respond to requests during an outage".

Real scenarios: a Consul server quorum lost during a bad upgrade: existing services keep running with cached lists and local agents, new deploys cannot register; a Eureka cluster in self-preservation during a network blip keeps listing dead hosts for minutes.

Fix / how to use it: pair any registry with (1) client-side last-known-good caching (Watcher.Instances() keeps the previous list on errors), (2) client timeouts and passive ejection, (3) active or passive health checking, (4) registry HA: three or five servers across zones for Raft systems.

Service mesh discovery: xDS and EDS Important ​

In plain words: a control plane watches the platform and pushes the endpoint list to a proxy next to every instance; applications keep calling orders and the local proxy chooses the backend.

Common misunderstanding: "The mesh replaces the registry." It reads one (Kubernetes EndpointSlices, Consul catalog) and distributes it. The registry is still the source of truth.

Definition: Envoy's service discovery types: Static (explicit addresses), Strict DNS (continuous asynchronous resolution; every returned IP is a host; "Envoy never synchronously resolves DNS in the forwarding path"), Logical DNS (uses the first returned IP for new connections; "connections are never drained"; best for large web services behind round-robin DNS), Original destination, and EDS (endpoint discovery service, "the preferred service discovery mechanism"). xDS is the family of "discovery service" APIs (LDS, RDS, CDS, EDS, ...); aggregated xDS (ADS) "carries all resource types in a single gRPC stream". Istio's control plane (istiod) implements xDS servers and feeds sidecars or ambient proxies from Kubernetes.

text
     Kubernetes API              Control plane (istiod)               Envoy sidecar (billing pod)         orders pods
1    EndpointSlice orders: [o1, o2]  ->  watch event
2                                    CDS: cluster "orders";  EDS: endpoints [o1, o2] + zone + weight  ->  load balancer updated
3    o2 fails readiness              ->  watch event -> EDS push: [o1]                                   ->  o2 removed in ~ms-seconds
4    app calls http://orders/        (iptables redirect to local Envoy)                                  ->  Envoy picks o1
MechanismPushed byLatencyNotes
Kubernetes Service + kube-proxyAPI server watchSecondsPer-connection balancing
Envoy strict DNSPeriodic DNS (dns_refresh_rate default 5000 ms, respect_dns_ttl)TTL or 5 sDraining of removed IPs
Envoy EDSControl plane streamPushWeights, zones, canary info
Consul Connect / service meshConsul servers to EnvoyPushRegistry is Consul itself

Mesh internals (mTLS identity, traffic policy) are in API Gateway, BFF and Service Mesh and Service Mesh & the Sidecar Pattern.

Fix / how to use it: if you already run a mesh, do not also run client-side discovery libraries; configure outlier detection and active health checks in the mesh instead.

Multi-cluster and multi-region discovery Good to know ​

In plain words: one registry per cluster or region is normal; calling across them is an explicit design, not an accident.

Common misunderstanding: "One global registry is simplest." A global registry couples every region's availability to the slowest link. Eureka is region-isolated by design: it "does not know about servers in other AWS regions"; its "primary purpose of holding information is for load balancing within a region."

ApproachHowExamplesTrade-off
Local first, remote on failureLocal registry plus failover to remoteConsul prepared queries ("automatically querying remote datacenters for services if no healthy nodes are available in the local datacenter")Failover is automatic but traffic may cross regions
Peering / federationClusters exchange servicesConsul cluster peering ("connect two or more independent Consul clusters"), WAN federationOperational overhead, explicit exports
Global DNS in frontGeoDNS/latency routing to regional entry pointsRoute 53, Cloud Map public namespaces; see GeoDNSDNS TTL limits failover speed
Mesh gatewaysEast-west gateways expose services across clustersIstio multi-cluster, Consul mesh gatewaysCross-cluster mTLS and policy
Application-levelThe app chooses a region and URLConfig per regionSimple, manual

Real scenario: an orders service in two regions, each registering locally; billing calls local orders first; a prepared query fails over to the other region when no healthy local instance exists, with a latency alert because the failover path is slower.

Fix / how to use it: keep a per-region registry, define cross-region calls deliberately, make failover visible (metric and alert), and test it in a game day.

Security: registry access, spoofed registration Important ​

In plain words: whoever can write to the registry can steer other services' traffic; whoever can read it learns your topology.

Common misunderstanding: "The registry is internal, so it needs no auth." A compromised workload that can call register for the name payments receives other services' requests, including credentials in headers.

ThreatExampleControl
Spoofed registrationA rogue pod registers as paymentsRegistry ACLs scoped by service name (Consul ACL tokens with service:write per service); Kubernetes RBAC on EndpointSlices (only controllers write them)
Unauthorised read (topology leak)Any client lists every serviceRead ACLs; Consul results can be filtered by ACL (X-Consul-Results-Filtered-By-ACLs: true)
Man-in-the-middle after discoveryAddress is right, the endpoint is notmTLS with service identity verified against the name, not the IP: see mTLS
Script-check executionRemote agents can be told to run scriptsConsul warns that enabling non-local script checks "may introduce a known remote execution vulnerability"; use enable_local_script_checks, prefer HTTP/TCP checks
Registry takeoverStolen server credentialsSeparate gossip and RPC encryption, TLS between agents and servers, least-privilege tokens
DNS poisoning / cacheSpoofed A answersDNSSEC rarely used internally; network policy; short TTLs; do not trust DNS alone, verify via mTLS

Fix / how to use it: authenticate instances to the registry (tokens, IAM), authorise by service name, and authenticate peers with certificates so that discovery only ever proposes candidates.

Observability: registry metrics and endpoint churn Important ​

In plain words: you cannot debug "why did traffic go to a dead pod" without a record of what the list looked like at that moment.

Common misunderstanding: "If the dashboard shows N pods, clients see N." Clients see their own cached list; compare what the registry says with what each client uses.

SignalWhyWhere from
Instances per service (ready vs registered)Capacity and rollout healthRegistry API, kube_endpoint_address style kube-state-metrics, Consul catalog
Endpoint churn (adds + removes per minute)High churn means flapping probes or crash loops; it also costs CPU on every node and proxyEndpointSlice watch events, Envoy membership_change, membership_healthy
Registration/heartbeat failuresRegistry unreachable, auth brokenClient logs and metrics
Lease expiries vs graceful deregistersCrashes versus clean stopsRegistry logs
DNS error rate and latencyNXDOMAIN storms, ndots search-list amplificationCoreDNS metrics (including per-service-kind duration), resolver logs
Envoy DNS statsupdate_attempt, update_success, update_failureEnvoy cluster stats (documented in the service discovery page)
Per-instance error rate at the callerDetects stale entriesClient metrics tagged with instance id
Registry healthRaft leader, quorum, commit latencyConsul/etcd metrics

Real scenario: a rollout looks fine but p99 spikes: endpoint churn graph shows each pod flapping four times per minute because failureThreshold: 1 on a slow readiness probe.

Fix / how to use it: tag client metrics with the chosen instance id; alert on "instances ready = 0" and on churn above a baseline; see Observability.

Local development: Compose DNS and static configuration Good to know ​

In plain words: locally, the platform already gives you discovery: the Compose network is DNS.

Common misunderstanding: "I should run Consul locally to match production." Match the interface (a name in an environment variable), not the product. Docker's docs: "Each service registers its name with an internal DNS server, so containers can reach each other using the service name directly. No IP addresses or manual configuration is needed", and containers get their IP addresses dynamically each time they start, "so they are not persisted across restarts or recreations. This means you should always reference services by name, not IP address."

EnvironmentDiscoveryConfig the app sees
Laptop, one processStaticORDERS_URL=http://127.0.0.1:8081
Docker ComposeEmbedded DNS, service nameORDERS_URL=http://orders:8080
KubernetesService + CoreDNSORDERS_URL=http://orders.shop.svc.cluster.local:8080
VMs with ConsulConsul DNS or agentORDERS_SRV=orders.service.consul
TestsFake or Http::fake()URL to a stub

When a container is recreated it keeps the name but gets a new IP; "running containers can look up that name and connect to the new address, but the old address stops working", so clients that cache the IP break in local dev too (a cheap way to reproduce DNS-caching bugs: docker compose up -d --force-recreate orders).

Fix / how to use it: one environment variable per upstream, never an IP in code; the Laravel config/services.php in Laravel and the lab show it.

The staleness chain Must-know ​

In plain words: removal is a relay race; each runner adds delay, and your request lands on the dead instance for as long as the whole race takes.

Common misunderstanding: "My TTL is 5 seconds, so failover takes 5 seconds." The 5 s is one layer. Probe period times threshold, controller lag, proxy sync, DNS TTL, client resolver cache and open keep-alive connections all add.

Pod failsreadiness probeperiodSeconds x NEndpointSliceready=falsecontroller lagProxy ruleskube-proxy / xDS pushsync periodDNS answerCoreDNS ttl (5 s default)client resolver cacheConnectionskeep-alive, HTTP/2,gRPC channelsTime during which the removed instance can still get traffic = sum of the layers you actually have.ClusterIP Service: layers 1-3, plus long-lived connections (balancing happens per new TCP connection, not per request).Headless Service or DNS SRV: all five layers; clients that resolve once at start-up never leave the old list.Client-side registry watch: layer 4 is replaced by the watch latency (a push), so it is usually the fastest to converge.Fix on the server side: drain delay at least as long as the slowest layer. Fix on the client side: short TTL, re-resolve on error, cap connection age.

Definition: time-to-stop-traffic equals the sum over every layer between the failing check and the caller's socket. Numbers you can set: probe periodSeconds x failureThreshold, CoreDNS ttl (5 s default), client re-resolution (gRPC: at most every 30 s by default), connection max age. Numbers you cannot set but must allow for: controller and proxy propagation. The drain delay in Graceful shutdown is how the server side compensates.

Fix / how to use it: cap client connection age (HTTP MaxIdleConnsPerHost, gRPC MaxConnectionAge), re-resolve on error, and set the drain delay above the slowest layer.

Per-product behaviour, side by side ​

AspectEurekaConsuletcd (DIY)KubernetesAWS Cloud MapEnvoy / Istio
RegistrationSelf (client)Self or agent service file / sidecarSelf via lease + keyPlatform (pods → EndpointSlices)RegisterInstance API, ECS integrationFrom Kubernetes or Consul
HealthHeartbeat lease; optional health handlerHTTP, TCP, gRPC, UDP, script, TTL, OS serviceLease keepaliveProbes (readiness gates endpoints)Route 53 health checks or third partyActive HC + outlier detection
LookupClient library (REST)HTTP API, DNS, blocking queriesWatchDNS + virtual IP; APIDiscoverInstances or DNSxDS push
Detects crash byMissed renewals (about 90 s default)Failing check (interval based)Lease TTLProbe failure; node-controller for node lossHealth checkActive HC interval
ConsistencyEventual (AP-style)Raft (CP), tunable readsRaft, linearizableetcd store, eventual in nodesManagedEventual by design
Strong pointSurvives registry outagesRich checks, KV, DNS, meshPrimitive for DIY registries and leasesBuilt in, no extra componentNo servers to run on AWSPer-request control
Weak pointStale entries, JVM-centricYou run a Raft clusterYou write everything elseCluster-localAWS-onlyOperating the mesh

Mechanics ​

Kubernetes manifests: probes, Service, headless Service, drain ​

yaml
apiVersion: apps/v1
kind: Deployment
metadata: { name: orders, namespace: shop }
spec:
  replicas: 3
  strategy:
    rollingUpdate: { maxUnavailable: 0, maxSurge: 1 }   # new pod must be Ready before an old one is drained
  selector: { matchLabels: { app: orders } }
  template:
    metadata: { labels: { app: orders } }
    spec:
      terminationGracePeriodSeconds: 45                  # preStop (8) + in-flight work (30) + margin
      containers:
        - name: orders
          image: registry.example/orders:2.4.1
          ports: [{ name: http, containerPort: 8080 }]
          startupProbe:                                    # warm-up budget 30 x 5 = 150 s
            httpGet: { path: /startupz, port: http }
            periodSeconds: 5
            failureThreshold: 30
          livenessProbe:                                   # shallow: process only
            httpGet: { path: /livez, port: http }
            periodSeconds: 10
            timeoutSeconds: 1
            failureThreshold: 3
          readinessProbe:                                  # critical local dependencies, not draining
            httpGet: { path: /readyz, port: http }
            periodSeconds: 5
            timeoutSeconds: 2
            failureThreshold: 3
          lifecycle:
            preStop:
              exec: { command: ["sleep", "8"] }            # keep serving while endpoints update
---
apiVersion: v1
kind: Service            # server-side discovery: ClusterIP + kube-proxy
metadata: { name: orders, namespace: shop }
spec:
  selector: { app: orders }
  ports: [{ name: http, port: 8080, targetPort: http }]
---
apiVersion: v1
kind: Service            # headless: DNS returns pod IPs and SRV, client balances
metadata: { name: orders-hl, namespace: shop }
spec:
  clusterIP: None
  selector: { app: orders }
  ports: [{ name: http, port: 8080, targetPort: http }]

The ClusterIP Service gives orders.shop.svc.cluster.local one stable virtual IP; the headless one gives orders-hl.shop.svc.cluster.local many A records and _http._tcp.orders-hl.shop.svc.cluster.local SRV records. For a Laravel Octane pod the preStop hook can run php artisan app:drain --wait=8 instead of sleep (Laravel).

Consul: service definition with a check ​

hcl
service {
  name = "orders"
  id   = "orders-1"
  port = 8080
  check {
    http     = "http://localhost:8080/readyz"
    interval = "5s"
    timeout  = "2s"
    deregister_critical_service_after = "10m"
  }
}

Queries: dig @127.0.0.1 -p 8600 orders.service.consul SRV (instances that fail their check are omitted), curl 'localhost:8500/v1/health/service/orders?passing=true&index=8&wait=30s' (blocking query, response header X-Consul-Index).

Knobs and error messages you will meet ​

WhereSetting or messageMeaningRemedy
KubernetesReadiness probe failed: HTTP probe failed with statuscode: 503Pod not Ready; removed from endpointsCheck the dependency named in your /readyz output
KubernetesLiveness probe failed ... Container ... failed liveness probe, will be restartedRestart in progressIs liveness too deep or the timeout too short?
KubernetesStartup probe failed and the container is killed after the budgetSlow boot or wrong pathRaise failureThreshold x periodSeconds
Kubernetes DNSNXDOMAIN for data from another namespaceShort names expand only in the pod's namespaceUse data.prod or the FQDN
Kubernetes DNSoptions ndots:5Names with fewer than 5 dots try the search list firstEnd FQDNs with a dot or lower ndots for external names
Godial tcp: lookup orders on 10.96.0.10:53: no such hostName does not exist (yet)Retry with backoff; check Service name and namespace
Goconnect: connection refused to a listed addressStale entry or instance drainingPassive ejection, retry another instance
Consulrpc error: No cluster leaderRaft quorum lostRestore quorum; use stale reads in the interim
ConsulCheck status criticalFailing checkInstance omitted from DNS and ?passing
etcdLease TTL expired; key deletedMissed keepalivesIncrease TTL or fix the stall
RegistryRenew returns 404 / unknown leaseLease gone after restart/partitionRe-register (the Go client does)
HTTP502 / 503 during deployNo readiness gating or no drainProbes plus preStop
Eureka"EMERGENCY! EUREKA MAY BE INCORRECTLY CLAIMING INSTANCES ARE UP WHEN THEY'RE NOT"Self-preservation mode is active (renewals below threshold)Check for a real partition; do not disable blindly

The liveness message comes from the Kubernetes probe tutorial; the readiness, startup, Consul and Eureka message texts are from operational experience and were not in the pages fetched for this chapter.

Go ​

The Go module academy/service-discovery (stdlib plus gRPC only) has the whole story: a tiny registry, a client with heartbeats, a watched round-robin list, probes with drain, an SRV resolver, a gRPC resolver, and compile-only Kubernetes and Consul clients. gofmt and go vet are clean, and the registry/client tests pass with -race.

The registry and the heartbeat client ​

The registry: leases, Renew that reports an unknown lease, a reaper, a blocking Wait (like Consul's index and wait).

go
// Package registry is a tiny in-memory service registry with leases.
// It keeps the three ideas every registry shares: register, renew (heartbeat)
// and expire, plus a blocking query so clients can watch for changes.
package registry

import (
	"context"
	"errors"
	"sort"
	"sync"
	"time"
)

// ErrUnknown is returned when a lease is renewed after it expired or after
// the registry restarted. The caller must register again.
var ErrUnknown = errors.New("registry: unknown instance")

// Instance is one running copy of a service.
type Instance struct {
	ID      string            `json:"id"`
	Service string            `json:"service"`
	Addr    string            `json:"addr"` // host:port
	Meta    map[string]string `json:"meta,omitempty"`
	Ready   bool              `json:"ready"`
}

type entry struct {
	inst    Instance
	ttl     time.Duration
	expires time.Time
}

// Registry stores instances. The zero value is not usable; call New.
type Registry struct {
	mu      sync.Mutex
	entries map[string]*entry
	index   uint64
	changed chan struct{} // closed and replaced on every change
	now     func() time.Time
}

// New returns an empty registry.
func New() *Registry {
	return &Registry{
		entries: map[string]*entry{},
		changed: make(chan struct{}),
		now:     time.Now,
	}
}

func (r *Registry) bump() {
	r.index++
	close(r.changed)
	r.changed = make(chan struct{})
}

// Register adds or replaces an instance and starts its lease.
func (r *Registry) Register(inst Instance, ttl time.Duration) {
	r.mu.Lock()
	defer r.mu.Unlock()
	r.entries[inst.ID] = &entry{inst: inst, ttl: ttl, expires: r.now().Add(ttl)}
	r.bump()
}

// Renew extends the lease and publishes the current readiness.
func (r *Registry) Renew(id string, ready bool) error {
	r.mu.Lock()
	defer r.mu.Unlock()
	e, ok := r.entries[id]
	if !ok {
		return ErrUnknown
	}
	e.expires = r.now().Add(e.ttl)
	if e.inst.Ready != ready {
		e.inst.Ready = ready
		r.bump()
	}
	return nil
}

// Deregister removes an instance immediately (graceful shutdown).
func (r *Registry) Deregister(id string) {
	r.mu.Lock()
	defer r.mu.Unlock()
	if _, ok := r.entries[id]; ok {
		delete(r.entries, id)
		r.bump()
	}
}

// Reap removes every instance whose lease has expired (crash, partition).
func (r *Registry) Reap() int {
	r.mu.Lock()
	defer r.mu.Unlock()
	n := 0
	for id, e := range r.entries {
		if r.now().After(e.expires) {
			delete(r.entries, id)
			n++
		}
	}
	if n > 0 {
		r.bump()
	}
	return n
}

// Run reaps expired leases until ctx is cancelled.
func (r *Registry) Run(ctx context.Context, every time.Duration) {
	t := time.NewTicker(every)
	defer t.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case <-t.C:
			r.Reap()
		}
	}
}

// Snapshot returns the ready instances of a service and the current index.
func (r *Registry) Snapshot(service string) ([]Instance, uint64) {
	r.mu.Lock()
	defer r.mu.Unlock()
	return r.snapshotLocked(service), r.index
}

func (r *Registry) snapshotLocked(service string) []Instance {
	var out []Instance
	for _, e := range r.entries {
		if e.inst.Service == service && e.inst.Ready {
			out = append(out, e.inst)
		}
	}
	sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
	return out
}

// Wait blocks until the index moves past `after` or the context ends, then
// returns the current snapshot. This is a blocking query (long poll).
func (r *Registry) Wait(ctx context.Context, service string, after uint64) ([]Instance, uint64) {
	for {
		r.mu.Lock()
		if after == 0 || r.index > after { // index 0 means "first call, answer now"
			out, idx := r.snapshotLocked(service), r.index
			r.mu.Unlock()
			return out, idx
		}
		ch := r.changed
		r.mu.Unlock()
		select {
		case <-ch:
		case <-ctx.Done():
			return r.Snapshot(service)
		}
	}
}
go
package registry

import (
	"context"
	"encoding/json"
	"net/http"
	"strconv"
	"time"
)

// Handler exposes the registry over HTTP, shaped like Consul's API on purpose:
//
//	PUT /v1/register?ttl=10s          body: Instance
//	PUT /v1/renew/{id}?ready=true
//	PUT /v1/deregister/{id}
//	GET /v1/services/{name}?index=N&wait=10s   (blocking query, X-Index header)
func (r *Registry) Handler() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("PUT /v1/register", func(w http.ResponseWriter, req *http.Request) {
		var inst Instance
		if err := json.NewDecoder(req.Body).Decode(&inst); err != nil || inst.ID == "" {
			http.Error(w, "bad instance", http.StatusBadRequest)
			return
		}
		ttl, err := time.ParseDuration(req.URL.Query().Get("ttl"))
		if err != nil || ttl <= 0 {
			ttl = 10 * time.Second
		}
		r.Register(inst, ttl)
		w.WriteHeader(http.StatusNoContent)
	})
	mux.HandleFunc("PUT /v1/renew/{id}", func(w http.ResponseWriter, req *http.Request) {
		ready := req.URL.Query().Get("ready") != "false"
		if err := r.Renew(req.PathValue("id"), ready); err != nil {
			http.Error(w, err.Error(), http.StatusNotFound) // client must re-register
			return
		}
		w.WriteHeader(http.StatusNoContent)
	})
	mux.HandleFunc("PUT /v1/deregister/{id}", func(w http.ResponseWriter, req *http.Request) {
		r.Deregister(req.PathValue("id"))
		w.WriteHeader(http.StatusNoContent)
	})
	mux.HandleFunc("GET /v1/services/{name}", func(w http.ResponseWriter, req *http.Request) {
		after, _ := strconv.ParseUint(req.URL.Query().Get("index"), 10, 64)
		wait, err := time.ParseDuration(req.URL.Query().Get("wait"))
		if err != nil || wait > time.Minute {
			wait = 5 * time.Second
		}
		ctx, cancel := context.WithTimeout(req.Context(), wait)
		defer cancel()
		list, idx := r.Wait(ctx, req.PathValue("name"), after)
		w.Header().Set("X-Index", strconv.FormatUint(idx, 10))
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(list)
	})
	return mux
}

The client: KeepAlive registers, renews every ttl/3 with the current readiness, re-registers on a lost lease and deregisters on shutdown with a fresh context.

go
// Package regclient is the client side of the tiny registry: register,
// heartbeat, watch and pick. It never talks to the registry on the request path.
package regclient

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"strconv"
	"time"

	"academy/service-discovery/registry"
)

// ErrNotFound means the lease is gone; register again.
var ErrNotFound = errors.New("regclient: lease not found")

// Client talks to the registry HTTP API.
type Client struct {
	Base string // e.g. http://registry:8600
	HTTP *http.Client
}

// New returns a client with a sane default timeout for short calls.
func New(base string) *Client {
	return &Client{Base: base, HTTP: &http.Client{Timeout: 3 * time.Second}}
}

func (c *Client) do(ctx context.Context, method, path string, body any) (*http.Response, error) {
	var rd *bytes.Reader
	if body != nil {
		b, err := json.Marshal(body)
		if err != nil {
			return nil, err
		}
		rd = bytes.NewReader(b)
	} else {
		rd = bytes.NewReader(nil)
	}
	req, err := http.NewRequestWithContext(ctx, method, c.Base+path, rd)
	if err != nil {
		return nil, err
	}
	return c.HTTP.Do(req)
}

// Register creates the lease.
func (c *Client) Register(ctx context.Context, inst registry.Instance, ttl time.Duration) error {
	resp, err := c.do(ctx, http.MethodPut, "/v1/register?ttl="+url.QueryEscape(ttl.String()), inst)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusNoContent {
		return fmt.Errorf("register: status %d", resp.StatusCode)
	}
	return nil
}

// Renew is the heartbeat. It also publishes readiness.
func (c *Client) Renew(ctx context.Context, id string, ready bool) error {
	resp, err := c.do(ctx, http.MethodPut, "/v1/renew/"+url.PathEscape(id)+"?ready="+strconv.FormatBool(ready), nil)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	switch resp.StatusCode {
	case http.StatusNoContent:
		return nil
	case http.StatusNotFound:
		return ErrNotFound
	}
	return fmt.Errorf("renew: status %d", resp.StatusCode)
}

// Deregister removes the lease at once.
func (c *Client) Deregister(ctx context.Context, id string) error {
	resp, err := c.do(ctx, http.MethodPut, "/v1/deregister/"+url.PathEscape(id), nil)
	if err != nil {
		return err
	}
	return resp.Body.Close()
}

// List is one blocking query: it returns when the index moves past `index`
// or after `wait`, whichever comes first.
func (c *Client) List(ctx context.Context, service string, index uint64, wait time.Duration) ([]registry.Instance, uint64, error) {
	q := fmt.Sprintf("/v1/services/%s?index=%d&wait=%s", url.PathEscape(service), index, wait)
	cl := &http.Client{Timeout: wait + 5*time.Second} // longer than the long poll
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.Base+q, nil)
	if err != nil {
		return nil, 0, err
	}
	resp, err := cl.Do(req)
	if err != nil {
		return nil, 0, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, 0, fmt.Errorf("list: status %d", resp.StatusCode)
	}
	var out []registry.Instance
	if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
		return nil, 0, err
	}
	idx, _ := strconv.ParseUint(resp.Header.Get("X-Index"), 10, 64)
	return out, idx, nil
}
go
package regclient

import (
	"context"
	"errors"
	"log/slog"
	"time"

	"academy/service-discovery/registry"
)

// KeepAlive registers inst and renews its lease every ttl/3 until ctx ends,
// then deregisters. ready is asked on every beat, so readiness changes reach
// the registry within one interval. A lost lease (registry restart, network
// partition longer than the TTL) is repaired by registering again.
func (c *Client) KeepAlive(ctx context.Context, inst registry.Instance, ttl time.Duration, ready func() bool) error {
	inst.Ready = ready()
	for {
		err := c.Register(ctx, inst, ttl)
		if err == nil {
			break
		}
		slog.Warn("register failed, retrying", "id", inst.ID, "err", err)
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-time.After(time.Second):
		}
	}
	t := time.NewTicker(ttl / 3)
	defer t.Stop()
	for {
		select {
		case <-ctx.Done():
			// Fresh context: ctx is already cancelled, the goodbye must still go out.
			bye, cancel := context.WithTimeout(context.Background(), 2*time.Second)
			defer cancel()
			return c.Deregister(bye, inst.ID)
		case <-t.C:
			err := c.Renew(ctx, inst.ID, ready())
			if errors.Is(err, ErrNotFound) {
				inst.Ready = ready()
				err = c.Register(ctx, inst, ttl)
			}
			if err != nil {
				slog.Warn("heartbeat failed", "id", inst.ID, "err", err)
			}
		}
	}
}

Watch keeps the last good list on registry errors and backs off; RoundRobin ejects an instance after a failure and falls back to "try one anyway" when all are ejected.

go
package regclient

import (
	"context"
	"log/slog"
	"sync/atomic"
	"time"

	"academy/service-discovery/registry"
)

// Watcher keeps a local copy of a service's ready instances, updated by
// blocking queries. Requests read the copy; they never wait for the registry.
type Watcher struct {
	list atomic.Pointer[[]registry.Instance]
}

// Instances returns the last known list. On registry errors this is the last
// good list (stale-if-error), which is what Eureka clients and Envoy do.
func (w *Watcher) Instances() []registry.Instance {
	if p := w.list.Load(); p != nil {
		return *p
	}
	return nil
}

// Watch starts the background loop and returns at once.
func (c *Client) Watch(ctx context.Context, service string) *Watcher {
	w := &Watcher{}
	go func() {
		var index uint64
		backoff := 200 * time.Millisecond
		for ctx.Err() == nil {
			list, idx, err := c.List(ctx, service, index, 10*time.Second)
			if err != nil {
				slog.Warn("watch failed, keeping last list", "service", service, "err", err)
				select {
				case <-ctx.Done():
					return
				case <-time.After(backoff):
				}
				backoff = min(backoff*2, 5*time.Second)
				continue
			}
			backoff = 200 * time.Millisecond
			index = idx
			w.list.Store(&list)
		}
	}()
	return w
}
go
package regclient

import (
	"errors"
	"sync"
	"sync/atomic"
	"time"

	"academy/service-discovery/registry"
)

// ErrNoInstance means the list is empty or every instance is ejected.
var ErrNoInstance = errors.New("regclient: no healthy instance")

// RoundRobin picks instances from a Watcher in turn and skips ones the caller
// reported as failing (passive health checking) for a cool-down period.
type RoundRobin struct {
	W        *Watcher
	Cooldown time.Duration

	n       atomic.Uint64
	mu      sync.Mutex
	ejected map[string]time.Time
}

// Pick returns the next instance that is not ejected.
func (r *RoundRobin) Pick() (registry.Instance, error) {
	list := r.W.Instances()
	if len(list) == 0 {
		return registry.Instance{}, ErrNoInstance
	}
	start := r.n.Add(1)
	for i := range uint64(len(list)) {
		inst := list[(start+i)%uint64(len(list))]
		if !r.isEjected(inst.ID) {
			return inst, nil
		}
	}
	// All ejected: better to try one than to fail every request (panic mode).
	return list[start%uint64(len(list))], nil
}

// Fail ejects an instance after a connect error or a 5xx.
func (r *RoundRobin) Fail(id string) {
	r.mu.Lock()
	defer r.mu.Unlock()
	if r.ejected == nil {
		r.ejected = map[string]time.Time{}
	}
	r.ejected[id] = time.Now().Add(r.Cooldown)
}

func (r *RoundRobin) isEjected(id string) bool {
	r.mu.Lock()
	defer r.mu.Unlock()
	until, ok := r.ejected[id]
	if ok && time.Now().After(until) {
		delete(r.ejected, id)
		return false
	}
	return ok
}

Tests prove the three behaviours the page claims (lease expiry removes a crashed instance, ejected instances are skipped, not-ready instances are invisible):

go
package regclient_test

import (
	"context"
	"net/http/httptest"
	"testing"
	"time"

	"academy/service-discovery/regclient"
	"academy/service-discovery/registry"
)

func waitFor(t *testing.T, what string, ok func() bool) {
	t.Helper()
	deadline := time.Now().Add(3 * time.Second)
	for time.Now().Before(deadline) {
		if ok() {
			return
		}
		time.Sleep(20 * time.Millisecond)
	}
	t.Fatalf("timed out waiting for %s", what)
}

func TestLeaseExpiryRemovesCrashedInstance(t *testing.T) {
	reg := registry.New()
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	go reg.Run(ctx, 20*time.Millisecond)
	srv := httptest.NewServer(reg.Handler())
	t.Cleanup(srv.Close) // runs after the deferred cancel, so the long poll ends first
	c := regclient.New(srv.URL)

	// Two instances register; only "a" keeps heartbeating, "b" "crashes".
	for _, id := range []string{"a", "b"} {
		if err := c.Register(ctx, registry.Instance{ID: id, Service: "orders", Addr: id + ":1", Ready: true}, 150*time.Millisecond); err != nil {
			t.Fatal(err)
		}
	}
	w := c.Watch(ctx, "orders")
	waitFor(t, "both visible", func() bool { return len(w.Instances()) == 2 })

	go func() {
		for ctx.Err() == nil {
			_ = c.Renew(ctx, "a", true)
			time.Sleep(40 * time.Millisecond)
		}
	}()
	waitFor(t, "b expired", func() bool {
		l := w.Instances()
		return len(l) == 1 && l[0].ID == "a"
	})
}

func TestRoundRobinSkipsEjected(t *testing.T) {
	reg := registry.New()
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	srv := httptest.NewServer(reg.Handler())
	t.Cleanup(srv.Close) // runs after the deferred cancel, so the long poll ends first
	c := regclient.New(srv.URL)
	for _, id := range []string{"a", "b"} {
		reg.Register(registry.Instance{ID: id, Service: "orders", Addr: id, Ready: true}, time.Minute)
	}
	w := c.Watch(ctx, "orders")
	waitFor(t, "list", func() bool { return len(w.Instances()) == 2 })

	rr := &regclient.RoundRobin{W: w, Cooldown: time.Minute}
	rr.Fail("a")
	for range 6 {
		got, err := rr.Pick()
		if err != nil || got.ID != "b" {
			t.Fatalf("want b, got %v %v", got.ID, err)
		}
	}
}

func TestNotReadyIsInvisibleAndUnknownLeaseIsReported(t *testing.T) {
	reg := registry.New()
	reg.Register(registry.Instance{ID: "a", Service: "orders", Addr: "a", Ready: false}, time.Minute)
	if list, _ := reg.Snapshot("orders"); len(list) != 0 {
		t.Fatalf("not-ready instance must not be served, got %v", list)
	}
	if err := reg.Renew("a", true); err != nil {
		t.Fatal(err)
	}
	if list, _ := reg.Snapshot("orders"); len(list) != 1 {
		t.Fatalf("renew(ready=true) must publish it, got %v", list)
	}
	if err := reg.Renew("ghost", true); err != registry.ErrUnknown {
		t.Fatalf("want ErrUnknown, got %v", err)
	}
}

Probes with readiness gating and drain ​

go
// Package health separates three questions Kubernetes (and every load
// balancer) asks: has it started, is it alive, may it take traffic now.
package health

import (
	"context"
	"net/http"
	"sync"
	"sync/atomic"
	"time"
)

// State is the process-wide lifecycle flag set. All fields are safe for
// concurrent use.
type State struct {
	started  atomic.Bool
	draining atomic.Bool
	checks   []*Check
}

// Check is one dependency probe. Critical checks gate readiness; the others
// are reported but never flip the answer.
type Check struct {
	Name     string
	Critical bool
	Fn       func(context.Context) error
	Timeout  time.Duration
	MaxAge   time.Duration // cache the result so probes cannot hammer the dependency

	mu   sync.Mutex
	at   time.Time
	last error
}

func (c *Check) run(ctx context.Context) error {
	c.mu.Lock()
	defer c.mu.Unlock()
	if !c.at.IsZero() && time.Since(c.at) < c.MaxAge {
		return c.last
	}
	ctx, cancel := context.WithTimeout(ctx, c.Timeout)
	defer cancel()
	c.last, c.at = c.Fn(ctx), time.Now()
	return c.last
}

// New returns a State that has not started yet.
func New(checks ...*Check) *State { return &State{checks: checks} }

// MarkStarted is called once warm-up (config, migrations check, caches) is done.
func (s *State) MarkStarted() { s.started.Store(true) }

// StartDrain flips readiness to 503. Call it first on SIGTERM.
func (s *State) StartDrain() { s.draining.Store(true) }

// Draining reports whether StartDrain was called.
func (s *State) Draining() bool { return s.draining.Load() }

// Ready is the function you also hand to the registry heartbeat.
func (s *State) Ready(ctx context.Context) bool {
	if !s.started.Load() || s.draining.Load() {
		return false
	}
	for _, c := range s.checks {
		if c.Critical && c.run(ctx) != nil {
			return false
		}
	}
	return true
}

// Mux wires the three endpoints.
func (s *State) Mux() *http.ServeMux {
	mux := http.NewServeMux()
	// Liveness: shallow on purpose. It answers "is the process able to answer
	// at all". It must not look at the database or other services, or one
	// dependency outage restarts every pod at once.
	mux.HandleFunc("GET /livez", func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK)
	})
	// Startup: true once warm-up finished; Kubernetes holds liveness and
	// readiness back until this succeeds.
	mux.HandleFunc("GET /startupz", func(w http.ResponseWriter, _ *http.Request) {
		if !s.started.Load() {
			http.Error(w, "starting", http.StatusServiceUnavailable)
			return
		}
		w.WriteHeader(http.StatusOK)
	})
	// Readiness: started, not draining, critical dependencies reachable.
	mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, r *http.Request) {
		if !s.Ready(r.Context()) {
			http.Error(w, "not ready", http.StatusServiceUnavailable)
			return
		}
		w.WriteHeader(http.StatusOK)
	})
	return mux
}
go
package health

import (
	"context"
	"errors"
	"log/slog"
	"net/http"
	"time"
)

// Serve runs srv and performs the drain sequence when ctx is cancelled
// (wire ctx to signal.NotifyContext(SIGTERM, SIGINT)):
//
//  1. StartDrain: /readyz returns 503, the heartbeat publishes ready=false.
//  2. Sleep drainDelay: endpoint removal takes time to reach every proxy,
//     DNS cache and client list, and traffic keeps arriving meanwhile.
//  3. srv.Shutdown: stop accepting, wait for in-flight requests up to grace.
//
// drainDelay + grace must fit inside terminationGracePeriodSeconds.
func Serve(ctx context.Context, srv *http.Server, s *State, drainDelay, grace time.Duration) error {
	errc := make(chan error, 1)
	go func() { errc <- srv.ListenAndServe() }()
	select {
	case err := <-errc:
		return err
	case <-ctx.Done():
	}
	slog.Info("draining", "delay", drainDelay)
	s.StartDrain()
	time.Sleep(drainDelay)
	sctx, cancel := context.WithTimeout(context.Background(), grace)
	defer cancel()
	if err := srv.Shutdown(sctx); err != nil && !errors.Is(err, http.ErrServerClosed) {
		return err
	}
	return nil
}

DNS SRV discovery ​

net.Resolver.LookupSRV returns records "sorted by priority and randomized by weight within a priority" (package documentation), so the first element is the RFC 2782 first choice; Go does not expose TTLs, so the refresh interval is your decision.

go
// Package srvresolve discovers instances through DNS SRV records (RFC 2782)
// using only the standard library.
package srvresolve

import (
	"context"
	"fmt"
	"net"
	"strings"
	"sync/atomic"
	"time"
)

// Lookup returns "host:port" strings in the order a client should try them.
// net.Resolver.LookupSRV sorts by priority and randomises by weight within a
// priority, so the first element is already the RFC 2782 first choice.
func Lookup(ctx context.Context, r *net.Resolver, service, proto, name string) ([]string, error) {
	_, srvs, err := r.LookupSRV(ctx, service, proto, name)
	if err != nil && len(srvs) == 0 {
		return nil, err
	}
	out := make([]string, 0, len(srvs))
	for _, s := range srvs {
		out = append(out, fmt.Sprintf("%s:%d", strings.TrimSuffix(s.Target, "."), s.Port))
	}
	return out, nil
}

// Cache re-resolves on a fixed interval and keeps the last good answer. Go's
// resolver does not expose record TTLs, so the interval is your policy, not
// the zone's: choose it knowingly.
type Cache struct {
	last atomic.Pointer[[]string]
}

// Get returns the last good list.
func (c *Cache) Get() []string {
	if p := c.last.Load(); p != nil {
		return *p
	}
	return nil
}

// Run refreshes until ctx ends. A failed or empty lookup never replaces a good list.
func (c *Cache) Run(ctx context.Context, every time.Duration, look func(context.Context) ([]string, error)) {
	refresh := func() {
		cctx, cancel := context.WithTimeout(ctx, 2*time.Second)
		defer cancel()
		if got, err := look(cctx); err == nil && len(got) > 0 {
			c.last.Store(&got)
		}
	}
	refresh()
	t := time.NewTicker(every)
	defer t.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case <-t.C:
			refresh()
		}
	}
}

A gRPC name resolver ​

gRPC's naming doc: "gRPC supports DNS as the default name-system ... The URI scheme indicates what resolver plugin to use. If no scheme prefix is specified or the scheme is unknown, the dns scheme is used by default." The resolver pushes the watched list into the channel and round_robin spreads RPCs. Compile-only (needs a registry to run).

go
// Package grpcresolver plugs the tiny registry into gRPC-Go as a name
// resolver, so a channel dialled as "registry:///orders" always knows the
// current instance list and round_robin spreads RPCs over it.
package grpcresolver

import (
	"context"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/resolver"

	"academy/service-discovery/regclient"
)

const scheme = "registry"

type builder struct{ client *regclient.Client }

// Register installs the scheme globally. Call it once at start-up, before
// grpc.NewClient (the same rule as database/sql drivers).
func Register(c *regclient.Client) { resolver.Register(&builder{client: c}) }

func (b *builder) Scheme() string { return scheme }

func (b *builder) Build(t resolver.Target, cc resolver.ClientConn, _ resolver.BuildOptions) (resolver.Resolver, error) {
	ctx, cancel := context.WithCancel(context.Background())
	r := &watchResolver{cancel: cancel, w: b.client.Watch(ctx, t.Endpoint())}
	go r.push(ctx, cc)
	return r, nil
}

type watchResolver struct {
	cancel context.CancelFunc
	w      *regclient.Watcher
}

// push forwards the watched list to gRPC whenever it changes.
func (r *watchResolver) push(ctx context.Context, cc resolver.ClientConn) {
	var last string
	t := newTicker()
	defer t.Stop()
	for {
		list := r.w.Instances()
		var addrs []resolver.Address
		key := ""
		for _, in := range list {
			addrs = append(addrs, resolver.Address{Addr: in.Addr})
			key += in.Addr + ","
		}
		if key != last && len(addrs) > 0 {
			_ = cc.UpdateState(resolver.State{Addresses: addrs})
			last = key
		}
		select {
		case <-ctx.Done():
			return
		case <-t.C:
		}
	}
}

// ResolveNow is a hint from gRPC after a connection failure; the watcher is
// already as fresh as the registry allows, so there is nothing to force.
func (r *watchResolver) ResolveNow(resolver.ResolveNowOptions) {}

func (r *watchResolver) Close() { r.cancel() }

// Dial opens a load-balanced channel to a service by name.
func Dial(service string) (*grpc.ClientConn, error) {
	return grpc.NewClient(scheme+":///"+service,
		grpc.WithTransportCredentials(insecure.NewCredentials()), // use mTLS in production
		grpc.WithDefaultServiceConfig(`{"loadBalancingConfig":[{"round_robin":{}}]}`),
	)
}
go
package grpcresolver

import "time"

func newTicker() *time.Ticker { return time.NewTicker(500 * time.Millisecond) }

Kubernetes API and Consul, compile-only ​

Reading EndpointSlices with the three conditions (ready, serving, terminating); production code normally uses client-go informers, which make the same calls plus a watch.

go
// Package kubeapi reads EndpointSlices straight from the Kubernetes API with
// only the standard library. Production code normally uses client-go and an
// informer; this shows what that informer actually asks for. Compile-only
// here: it needs a cluster and a service account with get/list on
// endpointslices.discovery.k8s.io.
package kubeapi

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"strings"
)

const saDir = "/var/run/secrets/kubernetes.io/serviceaccount/"

// Endpoint is one pod address with the three EndpointSlice conditions.
type Endpoint struct {
	Addr        string
	Ready       bool
	Serving     bool
	Terminating bool
}

type sliceList struct {
	Items []struct {
		Ports []struct {
			Name string `json:"name"`
			Port int32  `json:"port"`
		} `json:"ports"`
		Endpoints []struct {
			Addresses  []string `json:"addresses"`
			Conditions struct {
				Ready       *bool `json:"ready"`
				Serving     *bool `json:"serving"`
				Terminating *bool `json:"terminating"`
			} `json:"conditions"`
		} `json:"endpoints"`
	} `json:"items"`
}

// Client is an in-cluster API client.
type Client struct {
	http  *http.Client
	token string
}

// InCluster builds a client from the mounted service-account files.
func InCluster() (*Client, error) {
	tok, err := os.ReadFile(saDir + "token")
	if err != nil {
		return nil, err
	}
	ca, err := os.ReadFile(saDir + "ca.crt")
	if err != nil {
		return nil, err
	}
	pool := x509.NewCertPool()
	pool.AppendCertsFromPEM(ca)
	tr := &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12}}
	return &Client{http: &http.Client{Transport: tr}, token: strings.TrimSpace(string(tok))}, nil
}

// Endpoints lists the slices of one Service and flattens them.
func (c *Client) Endpoints(ctx context.Context, namespace, service, portName string) ([]Endpoint, error) {
	host := os.Getenv("KUBERNETES_SERVICE_HOST")
	port := os.Getenv("KUBERNETES_SERVICE_PORT")
	url := fmt.Sprintf("https://%s:%s/apis/discovery.k8s.io/v1/namespaces/%s/endpointslices?labelSelector=kubernetes.io/service-name=%s",
		host, port, namespace, service)
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Authorization", "Bearer "+c.token)
	resp, err := c.http.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("endpointslices: status %d", resp.StatusCode)
	}
	var sl sliceList
	if err := json.NewDecoder(resp.Body).Decode(&sl); err != nil {
		return nil, err
	}
	var out []Endpoint
	for _, s := range sl.Items {
		var p int32
		for _, sp := range s.Ports {
			if sp.Name == portName {
				p = sp.Port
			}
		}
		for _, e := range s.Endpoints {
			// A nil condition means "unknown, treat as ready" per the API docs.
			ready := e.Conditions.Ready == nil || *e.Conditions.Ready
			for _, a := range e.Addresses {
				out = append(out, Endpoint{
					Addr:        fmt.Sprintf("%s:%d", a, p),
					Ready:       ready,
					Serving:     e.Conditions.Serving == nil || *e.Conditions.Serving,
					Terminating: e.Conditions.Terminating != nil && *e.Conditions.Terminating,
				})
			}
		}
	}
	return out, nil
}

Consul over plain HTTP: register with a check, deregister, a blocking ?passing=true query.

go
// Package consulapi speaks the three Consul HTTP calls a service needs:
// register with a check, deregister, and a blocking health query. Plain
// net/http, no SDK. Compile-only here (no Consul agent on the build machine);
// the Compose lab in the page runs it against a dev agent.
package consulapi

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"strconv"
	"time"
)

// Agent is a local Consul agent address, e.g. http://127.0.0.1:8500.
type Agent struct {
	Base string
	HTTP *http.Client
}

// Registration is the body of PUT /v1/agent/service/register.
type Registration struct {
	ID      string `json:"ID"`
	Name    string `json:"Name"`
	Address string `json:"Address"`
	Port    int    `json:"Port"`
	Check   Check  `json:"Check"`
}

// Check asks the agent to probe the instance itself.
type Check struct {
	HTTP                           string `json:"HTTP"`
	Interval                       string `json:"Interval"`
	Timeout                        string `json:"Timeout"`
	DeregisterCriticalServiceAfter string `json:"DeregisterCriticalServiceAfter"`
}

// Register adds the service and its check to the local agent.
func (a *Agent) Register(ctx context.Context, r Registration) error {
	b, _ := json.Marshal(r)
	req, err := http.NewRequestWithContext(ctx, http.MethodPut, a.Base+"/v1/agent/service/register", bytes.NewReader(b))
	if err != nil {
		return err
	}
	return a.expectOK(req)
}

// Deregister removes the service (and its check) from the local agent.
func (a *Agent) Deregister(ctx context.Context, id string) error {
	req, err := http.NewRequestWithContext(ctx, http.MethodPut, a.Base+"/v1/agent/service/deregister/"+url.PathEscape(id), nil)
	if err != nil {
		return err
	}
	return a.expectOK(req)
}

type healthEntry struct {
	Node    struct{ Address string }
	Service struct {
		ID      string
		Address string
		Port    int
	}
}

// Passing is one blocking query for instances whose checks pass. Pass the
// index from the previous call (0 the first time); the server holds the
// request until something changes or `wait` elapses.
func (a *Agent) Passing(ctx context.Context, service string, index uint64, wait time.Duration) ([]string, uint64, error) {
	u := fmt.Sprintf("%s/v1/health/service/%s?passing=true&index=%d&wait=%s", a.Base, url.PathEscape(service), index, wait)
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
	if err != nil {
		return nil, 0, err
	}
	resp, err := a.client().Do(req)
	if err != nil {
		return nil, 0, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, 0, fmt.Errorf("consul health: status %d", resp.StatusCode)
	}
	var entries []healthEntry
	if err := json.NewDecoder(resp.Body).Decode(&entries); err != nil {
		return nil, 0, err
	}
	addrs := make([]string, 0, len(entries))
	for _, e := range entries {
		host := e.Service.Address
		if host == "" {
			host = e.Node.Address // Consul leaves it empty when it equals the node address
		}
		addrs = append(addrs, fmt.Sprintf("%s:%d", host, e.Service.Port))
	}
	next, _ := strconv.ParseUint(resp.Header.Get("X-Consul-Index"), 10, 64)
	return addrs, next, nil
}

func (a *Agent) client() *http.Client {
	if a.HTTP != nil {
		return a.HTTP
	}
	return &http.Client{Timeout: 10 * time.Minute} // longer than any wait
}

func (a *Agent) expectOK(req *http.Request) error {
	resp, err := a.client().Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("consul: %s %s: status %d", req.Method, req.URL.Path, resp.StatusCode)
	}
	return nil
}

The Go angle ​

  • net.Resolver (LookupHost, LookupSRV) goes through the system resolver or Go's pure resolver; it keeps no cache between calls, so caching is yours.
  • net/http keeps idle connections per host in a pool; a pooled keep-alive connection to a dead address is the Go version of a stale DNS entry. Bound it with Transport.IdleConnTimeout and handle connection errors by retrying on another instance.
  • signal.NotifyContext is the idiom for SIGTERM; combine it with http.Server.Shutdown after the drain delay.
  • context deadlines on every registry call: a registry that hangs must not hang requests.

Laravel ​

Laravel apps are short-lived per request and normally not registry clients; discovery shows up as config, DNS, a health route and a drain step. PHP is reviewed, not run here (php is not installed on the build machine).

Health: /up for liveness, /readyz for readiness ​

The built-in route (health: '/up' in bootstrap/app.php) "will return a 200 HTTP response if the application has booted without exceptions"; Laravel's deployment docs say it "may be used to report the status of your application to an uptime monitor, load balancer, or orchestration system such as Kubernetes". Keep it shallow and add a separate readiness route that does the dependency check and honours a drain flag.

php
<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        // Built-in route: 200 once the app has booted without exceptions.
        // Use it as the LIVENESS probe. Keep it shallow: do not add a
        // DiagnosingHealth listener that touches the database, or one
        // database outage makes Kubernetes restart every pod at once.
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        //
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();
php
<?php

use App\Http\Controllers\ReadyzController;
use Illuminate\Support\Facades\Route;

// Readiness: "may this pod receive traffic right now?" Deep on purpose, but
// only about dependencies this pod cannot work without.
// Probes must not start sessions or share error bags on every hit.
Route::get('/readyz', ReadyzController::class)->withoutMiddleware([
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
]);
php
<?php

declare(strict_types=1);

namespace App\Health;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Throwable;

/**
 * Decides readiness. Three inputs: the drain flag (set on shutdown), a cheap
 * critical dependency check (database), and a short result cache so a probe
 * every second per pod cannot hammer the database.
 */
final class ReadinessGate
{
    /** A plain file works across every Octane worker and every PHP-FPM child. */
    public static function drainFlagPath(): string
    {
        return storage_path('framework/draining');
    }

    public function isDraining(): bool
    {
        return is_file(self::drainFlagPath());
    }

    public function startDrain(): void
    {
        touch(self::drainFlagPath());
    }

    public function stopDraining(): void
    {
        @unlink(self::drainFlagPath());
    }

    /** @return array{ready: bool, checks: array<string, string>} */
    public function evaluate(): array
    {
        if ($this->isDraining()) {
            return ['ready' => false, 'checks' => ['drain' => 'draining']];
        }

        // Cache for 3 seconds. The array store lives inside one PHP process, so this only
        // helps under Octane (long-lived workers); under PHP-FPM every request re-checks,
        // which is fine at one probe every few seconds.
        $db = Cache::store('array')->remember('ready:db', 3, function (): string {
            try {
                DB::select('select 1');   // keep the connect/read timeout low in config/database.php
                return 'ok';
            } catch (Throwable $e) {
                return 'fail: '.$e::class;
            }
        });

        return ['ready' => $db === 'ok', 'checks' => ['database' => $db]];
    }
}
php
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Health\ReadinessGate;
use Illuminate\Http\JsonResponse;

final class ReadyzController
{
    public function __invoke(ReadinessGate $gate): JsonResponse
    {
        $result = $gate->evaluate();

        // 503 removes this pod from Service endpoints (Kubernetes), or marks the
        // Consul check critical, or makes Envoy / the cloud LB stop routing to it.
        return response()->json($result, $result['ready'] ? 200 : 503);
    }
}

Config-driven upstreams and SRV ​

The code contains only a name. ORDERS_URL is a ClusterIP or Compose name; ORDERS_SRV switches to SRV lookup, cached for a few seconds because Octane workers live for hours and must not resolve once at boot.

php
<?php

return [
    // Config-driven upstreams: the code never contains an address, only a name.
    // Kubernetes: ORDERS_URL=http://orders.shop.svc.cluster.local:8080 (ClusterIP, kube-proxy balances)
    // Consul:     ORDERS_SRV=orders.service.consul                     (SRV lookup, client balances)
    // Compose:    ORDERS_URL=http://orders:8080                        (Docker DNS, service name)
    'orders' => [
        'url' => env('ORDERS_URL', 'http://orders:8080'),
        'srv' => env('ORDERS_SRV'),          // when set, resolve SRV records instead of using url
        'srv_ttl' => (int) env('ORDERS_SRV_TTL', 5),
        'timeout' => (float) env('ORDERS_TIMEOUT', 2.0),
    ],
];
php
<?php

declare(strict_types=1);

namespace App\Discovery;

use Illuminate\Support\Facades\Cache;

/**
 * Resolves a DNS SRV name (RFC 2782) to "host:port" targets.
 *
 * dns_get_record() returns each SRV record as ['target', 'port', 'pri', 'weight', ...].
 * The result is cached for a few seconds in the application cache: the OS
 * resolver cache and PHP cannot be trusted to honour the zone TTL, and Octane
 * workers live for hours, so "resolve once at boot" would freeze the topology.
 */
final class SrvResolver
{
    /** @return list<string> "host:port", lowest priority group first, weighted order inside a group */
    public function resolve(string $name, int $ttlSeconds): array
    {
        /** @var list<string> */
        return Cache::remember("srv:{$name}", $ttlSeconds, function () use ($name): array {
            $records = @dns_get_record($name, DNS_SRV) ?: [];
            if ($records === []) {
                return [];
            }

            usort($records, fn (array $a, array $b): int => $a['pri'] <=> $b['pri']);
            $byPriority = [];
            foreach ($records as $r) {
                $byPriority[$r['pri']][] = $r;
            }

            $ordered = [];
            foreach ($byPriority as $group) {
                foreach ($this->weightedShuffle($group) as $r) {
                    $ordered[] = rtrim($r['target'], '.').':'.$r['port'];
                }
            }

            return $ordered;
        });
    }

    /**
     * RFC 2782 selection: repeatedly pick one record with probability
     * proportional to its weight (weight 0 records get a small share).
     *
     * @param  list<array{target: string, port: int, pri: int, weight: int}>  $group
     * @return list<array{target: string, port: int, pri: int, weight: int}>
     */
    private function weightedShuffle(array $group): array
    {
        $out = [];
        while ($group !== []) {
            $sum = array_sum(array_map(fn (array $r): int => $r['weight'] + 1, $group));
            $pick = random_int(1, $sum);
            foreach ($group as $i => $r) {
                $pick -= $r['weight'] + 1;
                if ($pick <= 0) {
                    $out[] = $r;
                    unset($group[$i]);
                    $group = array_values($group);
                    break;
                }
            }
        }

        return $out;
    }
}

Http::baseUrl(), connectTimeout() and timeout() are documented in the Laravel 13 HTTP client page; a ConnectionException is the signal to try the next instance.

php
<?php

declare(strict_types=1);

namespace App\Clients;

use App\Discovery\SrvResolver;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;

/**
 * Calls the orders service. The base URL comes from configuration; with SRV it
 * is chosen per call, and a connection failure moves on to the next target.
 */
final class OrdersClient
{
    public function __construct(private readonly SrvResolver $srv) {}

    /** @return array<string, mixed> */
    public function find(int $id): array
    {
        $cfg = config('services.orders');

        if (! $cfg['srv']) {
            // Kubernetes Service / Compose name: one stable URL, the platform picks the pod.
            return $this->request($cfg['url'], $cfg['timeout'])->get("/orders/{$id}")->throw()->json();
        }

        $targets = $this->srv->resolve($cfg['srv'], $cfg['srv_ttl']);
        $last = null;
        foreach (array_slice($targets, 0, 3) as $target) {   // at most 3 attempts, never loop forever
            try {
                return $this->request("http://{$target}", $cfg['timeout'])->get("/orders/{$id}")->throw()->json();
            } catch (ConnectionException $e) {
                $last = $e;                                   // dead or draining instance: try the next one
            }
        }

        throw $last ?? new \RuntimeException('no instances of orders');
    }

    private function request(string $baseUrl, float $timeout): PendingRequest
    {
        return Http::baseUrl($baseUrl)
            ->connectTimeout(min(1.0, $timeout))   // a dead instance must fail fast
            ->timeout($timeout)
            ->acceptJson();
    }
}

Graceful shutdown with Octane ​

The Octane docs describe octane:reload ("gracefully restart the Octane server's application workers", typically after deployment), octane:stop, and --max-requests (workers are gracefully restarted after a number of requests). They do not document SIGTERM or drain behaviour, so this page does not claim any; the drain below is explicit and process-manager independent: flip readiness first, wait for the endpoint removal to propagate, then stop.

php
<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Health\ReadinessGate;
use Illuminate\Console\Command;

/**
 * Run from the Kubernetes preStop hook (or a deploy script) before the stop
 * signal reaches Octane (on Kubernetes the endpoint is already marked terminating,
 * the flag matters for load balancers and agents that only look at /readyz): flip readiness, wait for the endpoint removal to
 * propagate, then stop the server so in-flight requests can finish.
 *
 *   lifecycle:
 *     preStop:
 *       exec: { command: ["php", "artisan", "app:drain", "--wait=8"] }
 */
final class DrainCommand extends Command
{
    protected $signature = 'app:drain {--wait=8 : seconds to keep serving while endpoints update} {--reset : clear the drain flag (run at the start of a deploy on VMs)}';

    protected $description = 'Fail readiness, wait for proxies and clients to stop sending traffic, then stop Octane';

    public function handle(ReadinessGate $gate): int
    {
        if ($this->option('reset')) {
            // A flag file survives restarts on a VM or a persistent volume; clear it before serving again.
            $gate->stopDraining();
            $this->info('drain flag cleared');

            return self::SUCCESS;
        }

        $gate->startDrain();
        $this->info('readiness is now 503; still serving in-flight and late requests');

        sleep((int) $this->option('wait'));

        // octane:stop is documented in the Octane docs; it stops the server process.
        $this->call('octane:stop');

        return self::SUCCESS;
    }
}

The Laravel angle ​

  • A request-per-process model (PHP-FPM) resolves DNS per request through the OS resolver; the practical cache is the resolver (nscd, dnsmasq, systemd-resolved) and the platform. Octane keeps state in memory for hours: never store a resolved IP in a static property.
  • DiagnosingHealth runs on /up; do not put database checks there if /up is your liveness probe.
  • Queue workers (queue:work) are also pods: they need a liveness signal and a graceful stop (queue:restart or SIGTERM and --timeout), see Laravel Queue Internals.
  • Per-environment URLs belong in config/services.php and .env, not in code.

Solving the classic problems ​

Dead instances still receive traffic ​

SolutionHowAdvantageCost / limitation
Short lease/TTL plus watchHeartbeat every TTL/3; clients watchFast detectionFalse expiry under pauses
Passive ejection (outlier detection)Client or proxy ejects after N errorsReacts in one requestNeeds a retry on another instance
Active health checksProxy probes every instanceIndependent of the app's heartbeatExtra probe load
Retries with a budgetRetry on another instance, cappedHides the gap from usersAmplifies load (timeouts and retries)

Errors during rolling deploys ​

SolutionHowAdvantageCost
Readiness gatingreadinessProbe plus a real /readyzNew pods get traffic only when warmNeeds a good endpoint
maxUnavailable: 0, maxSurge: 1New pod Ready before old is drainedCapacity never dropsSlower rollout, extra capacity
preStop drain delaySleep or app:drain before SIGTERMLate requests succeedLonger rollout
Graceful server shutdownShutdown(ctx) / octane:stopIn-flight requests finishMust fit in the grace period
Connection max ageServer closes keep-alive connections graduallyRebalances after scale-outExtra TLS handshakes

Thundering herd on the registry ​

Symptoms: after a registry restart every instance re-registers at once, every client re-fetches, the registry falls over again. Fixes: jittered heartbeats and re-registration backoff (the Go client waits 1 s; add jitter), watchers with exponential backoff (Watch caps at 5 s), blocking queries instead of tight polling, and caching at an agent per node (Consul agents) so thousands of clients do not each talk to the servers.

DNS caching in clients ​

Check whether the client re-resolves: JVM networkaddress.cache.ttl, Go (no process-wide cache but pooled connections), PHP-FPM (per request, OS cache), Node (per dns.lookup call, none by default for http), gRPC (MinResolutionInterval, re-resolves on connection failure). Fixes: connection max age, re-resolve on error, headless Service plus round_robin, or a proxy/mesh.

The registry is down ​

Clients keep the last good list ("stale if error"); proxies keep last config; new instances cannot register, so scale-out and deploys stall. Run three or five registry servers across zones (Raft), keep agents local, alert on "no leader", and test restoring from a snapshot.

Split brain in the registry ​

A partition leaves two groups that both believe they own the registry. CP registries (Consul, etcd) protect you: the minority cannot commit. AP-style registries (Eureka) accept both sides, so two clients can see different lists until they merge; self-preservation then keeps dead entries. Rules: do not use the registry as a lock or leader-election primitive unless it is CP (see leader election); make the data plane tolerate stale lists.

Deploys before readiness exists ​

Without a readiness probe the container is "ready" the moment it starts, so traffic hits a process that is still loading. The fix is the startup plus readiness pair above; the temporary fix is minReadySeconds, which is a guess, not a signal.

Failure modes at a glance ​

FailureSymptomRoot causeFix
Split brainTwo clients see different listsPartitioned AP registryCP registry for coordination; tolerate stale lists
Thundering registryRegistry falls over after restartSynchronised re-registrationJitter, backoff, local agents
DNS cacheCalls to removed pods for minutesClient resolves once or ignores TTLRe-resolve, short caps, max connection age
Self-preservation lockDead hosts listed for a long timeEureka threshold reachedRetry and timeout at the client; investigate partition
FlappingEndpoint churn, latency spikesProbe too sensitiveThresholds, shallow checks
Empty pool100% errorsReadiness depends on a shared dependencyReadiness only for critical local dependencies
Restart stormPods restart togetherLiveness checks a dependencyShallow liveness
No drain502 burst at deployExit on SIGTERM, no preStopDrain delay, graceful shutdown
Zombie registrationEntry for a dead processNo TTL, or TTL very longLeases and DeregisterCriticalServiceAfter
Wrong-instance spoofTraffic to a rogue instanceOpen registry writesACLs, mTLS by name

Choosing ​

SituationRecommendationExtra techniqueReason
Everything runs on KubernetesService + CoreDNS (server-side), readiness probesHeadless + round_robin for gRPCThe platform already is the registry
Polyglot services on VMsConsul agents with service files and DNSstale reads for resilienceLanguage independent, health aware
Homogeneous JVM fleet, high RPSEureka or Consul with a smart clientClient-side LB, zone awarenessOne hop fewer, rich balancing
gRPC with many long-lived connectionsClient-side round_robin over DNS/xDS or L7 proxyMax connection ageL4 balancing pins connections
Many clusters or regionsRegistry per cluster plus explicit cross-clusterPeering, mesh gatewaysRegion isolation
Already running a meshMesh discovery (EDS) onlyOutlier detectionOne system, not two
3 services, 1 teamStatic config or Compose namesHealth route and timeoutsDo not build infrastructure you do not need
AWS-only, ECS/EC2Cloud Map or load balancer target groupsRoute 53 health checksManaged registry

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

There is no discovery: modules call each other in memory (layered monolith). The only discovery-shaped need is the process itself behind a load balancer: two or three identical copies of the monolith, a hardware or cloud LB, and a health URL. Example: a Laravel monolith on two VMs behind an ALB with /up as the target-group health check; deploy drains one VM at a time using the ALB's deregistration delay. Everyday habit to start here: the /up route, a drain step, and database-checking readiness on a separate route.

Modular monolith and multiple databases ​

Modules are still in-process; the new dependencies are databases, caches and queue workers. Discovery is configuration (DB_HOST, REDIS_HOST) and the health question is "which dependency does this process need to be useful?" For the database-backed registry case a service_instance table (SQL above) is enough for a few workers to find a leader worker or a render service; use it only for small, internal needs (modular monolith). Example: the web process and three queue workers register in a table so an admin page shows "5 instances, 1 draining".

Microservices: what survives the boundary ​

Each service has many instances and every call crosses the network. The decisions: where the registry lives (platform or Consul), who balances (kube-proxy, client, mesh), what readiness means per service, and how deploys drain. Example flow for POST /checkout:

text
     checkout (3 pods)         orders (4 pods)               payments (3 pods)        inventory (2 pods)
1    checkout -> http://orders.shop.svc:8080   (ClusterIP, kube-proxy picks a Ready orders pod)
2    orders -> dns:///payments-hl.shop.svc:8080 (headless, gRPC round_robin over 3 pod IPs)
3    payments pod 2 starts a rolling update: readiness fails, preStop sleep 8, SIGTERM, Shutdown
4    orders' gRPC channel gets the new address set on re-resolution, in-flight RPCs on pod 2 finish
5    inventory: optional for browsing, so NOT in checkout's readiness; circuit breaker handles it

What does not survive: any assumption that an address is stable, and any readiness that depends on another service. Ownership is in Service Boundaries; the data side in Data Ownership.

Distributed data: replicas, caches and multi-region ​

Databases and caches also need discovery and failover: primaries move, replicas appear. Patterns: a stable DNS name that is repointed on failover (the TTL becomes your failover time), a proxy or pooler that tracks the primary (connection pooling), driver-level topology discovery (Redis Cluster, Cassandra, Mongo replica sets), or the orchestrator's service (Patroni with Consul or etcd as the DCS, see replication and failover). Multi-region: a registry per region, GeoDNS to regional entry points, and explicit cross-region failover with its own alert. Example: orders-db-primary.internal (TTL 10 s) is repointed by Patroni; the application's connection pool must drop connections and re-resolve, otherwise the failover finishes in the database and not in the app.

Scaling path: 1x, 10x, 100x ​

ScaleDiscovery shapeTypical problemNext step
1x (a few services, one team)Config + Compose names or Kubernetes ServicesHard-coded URLs, missing health routeEnvironment-driven URLs, /up, timeouts
10x (tens of services)Kubernetes Service/DNS, readiness and startup probes, drainDeploy errors, flapping probes, DNS ndots amplificationTune probes and drain; node-local DNS cache; connection max age
100x (hundreds of services, several clusters/regions)Mesh or client-side xDS, per-region registries, peeringEndpoint churn cost, registry blast radius, cross-region failoverSubsetting, locality-aware balancing, control-plane sharding, game days

Per request, the cost of discovery should stay near zero at every rung: cached list, local decision, no registry call on the request path.

Lab: register two instances, kill one, watch the client fail over ​

The runs below were executed on a laptop with the Go binaries (the Docker daemon was not running while writing this page, so the Compose files are provided but were not executed; docker compose config accepted both). Registry TTL is 6 s, heartbeat 2 s, warm-up 3 s, drain delay 3 s.

Setup (four terminals)

bash
cd docs/snippets/architecture/service-discovery/go
go build -o /tmp/registryd ./cmd/registryd && go build -o /tmp/instance ./cmd/instance && go build -o /tmp/client ./cmd/client
/tmp/registryd                                                         # terminal 1, :8600
INSTANCE_ID=orders-1 ADDR=127.0.0.1:9001 /tmp/instance                 # terminal 2
INSTANCE_ID=orders-2 ADDR=127.0.0.1:9002 /tmp/instance                 # terminal 3
/tmp/client                                                            # terminal 4, 2 requests/s

(Compose equivalent: docker compose up --build -d then docker compose logs -f client; for Consul: docker compose -f compose.consul.yml up --build -d and dig @127.0.0.1 -p 8600 orders.service.consul SRV +short.)

Experiment 1: round robin over a watched list. Expected (observed):

text
20:37:20 ok   orders-1
20:37:21 ok   orders-2
20:37:21 ok   orders-1
20:37:22 ok   orders-2

Experiment 2: crash one instance (kill -9). The client sees one failed call, ejects the instance for 5 s, and keeps going without further errors; the registry removes the lease after the TTL.

text
20:37:23 ok   orders-1
20:37:24 FAIL orders-2          <- first call to the dead instance: passive ejection
20:37:24 ok   orders-1
20:37:25 ok   orders-1          <- only orders-1 from here
curl '127.0.0.1:8600/v1/services/orders?index=0'    -> [{"id":"orders-1",...}]   (about 9 s after the kill)

Experiment 3: readiness gating on start. Start orders-2 again; for the 3 s warm-up /readyz is 503 and the registry does not list it; once started it is ready, appears within one heartbeat (2 s) and the client starts alternating again.

text
20:37:44 ready? 503 registry: [orders-1]
20:37:45 ready? 503 registry: [orders-1]
20:37:46 ready? 200 registry: [orders-1]            <- /readyz is already 200; the next heartbeat publishes it
20:37:48 ready? 200 registry: [orders-1, orders-2]

Experiment 4: graceful stop with drain (kill -TERM orders-1). Readiness flips, the registry drops the instance within one heartbeat, the instance keeps answering /whoami for the 3 s drain delay, then exits; on a fresh run the client log had 0 FAIL lines before and 0 after this stop (grep -c FAIL client.log), and orders-2 answered every request after the drain.

text
20:37:52 readyz=503 whoami=200 registry=['orders-2']       <- draining: still serves, no longer listed
20:37:53 readyz=503 whoami=200 registry=['orders-2']
20:37:54 readyz=000 whoami=000 registry=['orders-2']       <- exited after Shutdown

Experiment 5 (Kubernetes, not run here): readiness during a rolling deploy. Apply the manifests in Mechanics on a cluster (kind or minikube), then:

bash
kubectl -n shop set image deploy/orders orders=registry.example/orders:2.4.2
kubectl -n shop get endpointslices -l kubernetes.io/service-name=orders -w
# expect: new pod addresses appear with ready=true only after /readyz is 200; old ones go terminating=true

Run a load generator (hey or wrk) against the Service during the rollout: with probes and preStop there are no non-2xx responses; remove readinessProbe and the preStop to watch 502/503 appear.

Common misconceptions ​

BeliefReality
"Service discovery means DNS."DNS is one transport; it has no health semantics and caches. Kubernetes DNS sits on top of readiness-aware EndpointSlices.
"Registered means healthy."Registration is existence; health is a separate, ongoing check. Consul registers checks as critical by default for this reason.
"Deregistration on shutdown is enough."Crashes, OOM kills and partitions never deregister; leases and TTLs are what remove those instances.
"A short DNS TTL gives instant failover."Resolvers, libraries and keep-alive connections ignore or outlive it; the staleness is a sum of layers.
"One /health endpoint is enough."Startup, liveness and readiness trigger different reactions; mixing them causes restart storms or empty pools.
"Deep health checks are safer."A dependency outage then removes or restarts every pod. Liveness stays shallow; readiness covers only critical local dependencies.
"Client-side discovery calls the registry per request."Clients cache and watch; the registry is off the request path.
"Server-side discovery has no registry."It is inside the router or platform (Kubernetes EndpointSlices, ELB target groups).
"The registry must be strongly consistent."Envoy's docs argue eventual consistency plus active health checking is sufficient and easier to operate; CP is needed for coordination (locks, leader election), not for address lists.
"Kubernetes Service load balances every request."ClusterIP balances per new TCP connection; HTTP/2 and gRPC keep one connection, so RPCs stick to one pod.
"SIGTERM means stop accepting immediately."Late requests arrive while endpoints update; fail readiness, wait, then shut down.
"The mesh replaces the registry."The mesh distributes what a registry knows; it still needs a source of truth.

Cheat sheet ​

TopicWhat to remember
Three jobsRegistration, health, lookup; every outage is a failure in one of them or in a cache between them
RegistrationSelf for state the platform cannot see; third-party (platform, agent, sidecar) for polyglot fleets
LeaseTTL = about 3 x heartbeat; add jitter; handle "lease unknown" by re-registering
Client-sideFewer hops, thick client, per-language library; cache and watch, stale if error
Server-sideOne stable name, an extra hop, the router must be HA; Kubernetes Service is the default
DNSA/AAAA no port; SRV has priority, weight, port; caches ignore TTLs; headless Service returns pod IPs
ProbesStartup (budget), liveness (shallow, restarts), readiness (critical local deps, removes from endpoints)
Deep checksNever in liveness; cache results; exclude optional and downstream services from readiness
FlappingfailureThreshold 3, timeouts 1 to 2 s, watch endpoint churn
DrainFail readiness, wait for propagation (preStop), then Shutdown; total below the grace period (default 30 s)
ConsistencyEventual plus health checks is enough for address lists; CP for locks and leader election
MeshControl plane pushes EDS to proxies; the registry is still the source
Multi-clusterRegistry per cluster, explicit failover, observable
SecurityACLs by service name, mTLS verifies the name, avoid non-local script checks
StalenessTime to stop traffic = sum of probe, controller, proxy, DNS, client and connection delays

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why can a hard-coded address not survive autoscaling and rolling deploys? Must-know ​

Answer

Answer: Instances are created and destroyed continuously with dynamic IPs, so the set of valid addresses changes faster than humans can edit config; discovery makes the list a runtime fact.

2 — What is the difference between self-registration and third-party registration, and when would you pick each? Important ​

Answer

Answer: In self-registration the instance registers and renews itself (it can publish rich state but couples the service to the registry); in third-party the platform, agent or sidecar registers it (language independent, but only as smart as its probes). Pick self for state the platform cannot see, third-party for polyglot fleets.

3 — A pod is killed with kill -9. Which mechanism removes it from the registry, and how long does it take? Important ​

Answer

Answer: Lease or TTL expiry (or a failing check). Detection takes up to the TTL (for example 6 s) after the last heartbeat, then each cache after the registry adds delay.

4 — Compare client-side and server-side discovery on hops, client complexity and trust. Important ​

Answer

Answer: Client-side: no extra hop, complex per-language client, clients must be trusted with instance details. Server-side: extra hop through a router that must be highly available, simple clients, clients see only the router.

5 — Why does a short DNS TTL not give instant failover? Must-know ​

Answer

Answer: Libraries and applications cache or resolve once, resolvers may ignore TTLs, and keep-alive connections stay on old addresses; failover time is the sum of all layers.

6 — What do startup, liveness and readiness probes each do on failure? Must-know ​

Answer

Answer: Startup failure kills the container after its budget; liveness failure restarts the container; readiness failure only removes the pod from Service endpoints.

7 — Why must a liveness probe not check the database? Must-know ​

Answer

Answer: A database outage would fail every pod's liveness at once and restart the whole fleet without fixing anything; liveness must only detect states that a restart can cure.

8 — What are the steps of a graceful shutdown that avoids errors during a deploy? Must-know ​

Answer

Answer: Fail readiness (and publish ready=false), wait for endpoint removal to propagate (preStop or drain delay) while still serving late requests, then stop accepting and finish in-flight work, all within terminationGracePeriodSeconds.

9 — Why can eventual consistency be acceptable for a service registry? Important ​

Answer

Answer: Address lists tolerate staleness if clients time out, retry elsewhere and health-check; Envoy's design routes to hosts that pass health checks even when absent from discovery. Strong consistency is needed for coordination, not for address lists.

10 — What does Eureka's self-preservation mode do and what must clients do about it? Good to know ​

Answer

Answer: When renewals fall below a threshold (85 % within 15 minutes per the wiki) the server stops expiring instances to avoid emptying its registry during a partition; clients must tolerate returned instances that are dead by using fast timeouts and trying other instances.

11 — Why does a gRPC client on a ClusterIP Service often hit only one pod? Important ​

Answer

Answer: kube-proxy balances per TCP connection and HTTP/2 multiplexes all RPCs on one connection; use a headless Service with client-side round_robin, an L7 proxy or a mesh.

12 — What is spoofed registration and how do you stop it? Good to know ​

Answer

Answer: A rogue workload registers under another service's name to receive its traffic; use registry ACLs scoped per service, RBAC on EndpointSlices, and mTLS that verifies the peer's identity by name.

Glossary ​

TermOne line
Service discoveryMechanism by which a caller finds the current addresses of a service's instances
Service registryDatabase of services, instances and locations, kept alive by registration and health
Self-registrationInstance registers and renews itself
Third-party registrationPlatform, agent or sidecar registers instances on their behalf
Registrator / PranaExamples of third-party registrars (Docker containers / Eureka sidecar)
LeaseTime-bounded registration that must be renewed
TTLTime to live: lease duration, DNS record cache time, or a Consul TTL check
HeartbeatPeriodic renewal message proving the instance is alive
DeregistrationRemoving an instance from the registry, on shutdown or by expiry
Client-side discoveryClient queries the registry and balances itself
Server-side discoveryA router queries the registry and balances; client calls one name
Lookaside load balancerA balancer server clients ask for a backend, off the data path
Ribbon / EurekaNetflix client-side load balancer and registry
ConsulHashiCorp registry with catalog, health checks, DNS and mesh
etcdRaft key-value store with leases and watches, used as a registry primitive
Blocking queryLong poll that returns when an index changes (Consul index/wait)
A / AAAA recordDNS record mapping a name to an IPv4 / IPv6 address
SRV recordDNS record with priority, weight, port and target (RFC 2782)
Headless ServiceKubernetes Service with clusterIP: None; DNS returns pod IPs
ClusterIP / kube-proxyVirtual IP and the node component that programs forwarding rules
EndpointSliceKubernetes object listing a Service's endpoints with ready/serving/terminating
CoreDNSCluster DNS server in Kubernetes; kubernetes plugin serves Service names
ndotsresolv.conf option controlling search-list expansion of short names
Startup / liveness / readiness probeBoot finished / restart if stuck / take traffic now
Deep vs shallow checkWith vs without calls to dependencies
FlappingRapid alternation between healthy and unhealthy states
Drain / lame duckState where an instance stops receiving new work but finishes existing work
preStop hookKubernetes hook run before SIGTERM, used to delay shutdown for propagation
terminationGracePeriodSecondsTime between SIGTERM and SIGKILL (default 30 s)
Self-preservationEureka mode that stops expiring instances when renewals drop
Outlier detection / passive health checkEjecting an instance after observed errors
xDS / EDS / ADSEnvoy discovery APIs / endpoint discovery / aggregated stream
Split brainTwo parts of a system each believing they are authoritative
Thundering herdMany clients acting at once and overloading a shared component
Cloud MapAWS managed service registry with DNS and API discovery

References ​

Not backed by a fetched page (general practice, treat as unverified): JVM networkaddress.cache.ttl and Node DNS caching, Patroni with Consul/etcd as its DCS, gRPC server MaxConnectionAge, the istiod name, nscd/dnsmasq/systemd-resolved caching, the Traefik, NGINX + consul-template and HAProxy integrations, ZooKeeper details, and the Eureka dashboard message text.

Built by Morteza Negahi