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 for | Go to |
|---|---|
| Why a hard-coded address stops working | Why it exists |
| The registry, registration styles, leases and TTLs | Registry, Registration, Leases |
| Client-side vs server-side, with a table | Client-side, Server-side, Comparison |
| DNS, SRV records, headless services, why DNS caching hurts | DNS discovery |
| Liveness vs readiness vs startup, deep vs shallow checks | Probes, Deep vs shallow, Flapping |
| Zero-error deploys, drain, lame duck | Graceful shutdown |
| AP vs CP registries, stale entries, split brain | Consistency, Failure modes |
| Envoy, xDS, EDS, Istio | Mesh discovery |
| Several clusters or regions | Multi-cluster |
| Registry ACLs, spoofed registration, mTLS | Security |
| Registry metrics, endpoint churn | Observability |
| Docker Compose, static config | Local development |
| Go: registry, heartbeat client, round robin, gRPC resolver | Go |
| Laravel: health route, SRV, config-driven upstreams, Octane drain | Laravel |
| Monolith to multi-region, step by step | In architecture |
| Run it yourself, kill an instance | Lab |
Everything in one minute
The three jobs. Every discovery system, from a hosts file to a service mesh, does the same three things.
| Job | Question it answers | Typical owner | Where 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 itself | Checks 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 plane | Caches that outlive the truth (DNS TTL, client lists, keep-alive connections) |
The patterns.
| Pattern | Who queries the registry | Who balances | Example products | Main cost |
|---|---|---|---|---|
| Client-side discovery | The client | The client | Netflix Eureka + Ribbon, gRPC name resolver, Consul HTTP API, etcd watch | A library per language, client logic to upgrade |
| Server-side discovery | A router or load balancer | The router | Kubernetes Service (kube-proxy), AWS ELB, NGINX/HAProxy fed by a registry | An extra hop; the router must be highly available |
| DNS discovery | The OS or client resolver | Round-robin DNS, or the client over SRV | CoreDNS, Consul DNS, AWS Cloud Map, Route 53 | TTL caching and clients that resolve once |
| Mesh discovery | The sidecar proxy, fed by a control plane | The sidecar | Envoy with xDS/EDS, Istio | Operating the control plane and proxies |
The three probes.
| Probe | Question | On failure | Typical endpoint | Must not check |
|---|---|---|---|---|
| Startup | "Has it finished starting?" | Kill and restart (after the budget) | /startupz | Anything 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 | /readyz | Optional 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 addresses | Discovery |
|---|---|
| Simple, works for three servers that never move | A moving part that must itself be reliable |
| Failure of a host means an outage until a human edits config | Failure of a host is removed from the list automatically |
| Scaling out means editing every client | Scaling out means starting instances; they register themselves |
| No dependency on a registry | The 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".
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.
| Product | Registry storage | Consistency | Change notification |
|---|---|---|---|
| Eureka | In-memory registry replicated between peer servers | Eventually consistent, availability first | Clients poll deltas (about every 30 s by default) |
| Consul | Raft-replicated catalog in the servers, agents on every node | Strong by default per read mode (default, consistent, stale) | Blocking queries (index, wait), DNS |
| etcd | Raft key-value store, leases | Reads are linearizable by default; serializable (local, possibly stale) reads are opt-in | Watch API |
| ZooKeeper | Quorum-replicated tree; Richardson lists it as a registry (its ephemeral-node details were not re-checked for this page) | Strong writes | Watches |
| Kubernetes | EndpointSlice objects in etcd via the API server | Strong in etcd, eventual to every node | Watch (kube-proxy, CoreDNS, Envoy-based gateways) |
| AWS Cloud Map | Managed namespaces/services/instances | Managed (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".
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| Style | Examples (from the pattern pages and docs) | Pros | Cons |
|---|---|---|---|
| Self-registration | Spring Cloud with Eureka (@EnableEurekaClient), the Go client in this chapter, Consul PUT /agent/service/register from the app | Instance knows its own state (STARTING, AVAILABLE, DRAINING); no extra component | Library per language; a stuck instance may keep renewing |
| Third-party: platform | Kubernetes (controllers create EndpointSlices from pods and readiness), AWS Auto Scaling groups registering with ELB | No code in the service | Only as smart as the probes you define |
| Third-party: sidecar / agent | Netflix Prana (sidecar that registers a non-JVM app with Eureka), Consul agent with service definition files, Registrator for Docker | Language independent, can run health checks | Another 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."
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| Knob | Too small | Too large | Typical rule |
|---|---|---|---|
| TTL | False expiries during GC pauses, CPU starvation, short network blips | Dead instances listed for long | 3x heartbeat interval; 10 to 30 s for most services |
| Heartbeat interval | Registry write load grows with instances x frequency | Slow detection | TTL/3, with jitter so heartbeats do not synchronise |
Deregister-after-critical (Consul DeregisterCriticalServiceAfter) | Instances removed during a long deploy or incident | Zombie entries forever | Minutes, not seconds |
| Client refresh interval (poll) | Registry read load | Stale client lists | Prefer 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.
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".
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)| Variant | Who watches the registry | Example | Notes |
|---|---|---|---|
| Thick client | Every client process | Netflix Ribbon with Eureka; Go regclient.Watch | Maximum control; every language needs the library |
| gRPC name resolver | gRPC channel, plugin per scheme | dns:///, custom registry:/// resolver (Go) | round_robin policy balances across resolved addresses |
| Lookaside LB | A separate balancer server that clients ask | gRPC "lookaside" / xDS-style | Clients stay thin, LB is off the data path |
| Proxy-based client (sidecar) | A local proxy per host | Netflix Prana, Envoy sidecar | Looks 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".
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 type | Registry source | Level | Examples |
|---|---|---|---|
| Platform virtual IP | EndpointSlices (the Kubernetes Service) | L4, per connection | Kubernetes ClusterIP with kube-proxy (iptables, ipvs or nftables modes) |
| Cloud load balancer | Target groups, auto scaling group membership | L4 or L7 | AWS ELB/ALB, GCP load balancers; ELB "also functions as a Service Registry" |
| Reverse proxy fed by a registry | Consul, etcd, Docker or Kubernetes provider | L7 | Traefik, NGINX + consul-template, HAProxy with DNS service discovery, Envoy |
| Edge gateway | Same sources | L7 | API 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
| Question | Client-side | Server-side |
|---|---|---|
| Extra network hop | No | Yes (router in the data path) |
| Client complexity | High: library, cache, balancer, retries | Low: one name |
| Polyglot fleet | One implementation per language | Language independent |
| Load-balancing intelligence | Can use request-level signals, zone, latency, weights | Whatever the router supports |
| Failure of the registry | Clients keep the cached list (stale but working) | Router keeps its last config; new instances do not appear |
| Failure of the router | Not applicable | The whole path fails unless the router is HA |
| Trust boundary | Clients must be trusted with the full instance list | Clients see only the router |
| Upgrade path | Roll out a new library to every service | Upgrade the router once |
| Observability | Each client emits its own metrics | One place for LB metrics |
| Typical fit | Homogeneous 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".
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| Record | Carries | Used by | Limits |
|---|---|---|---|
| A / AAAA | IPv4 / IPv6 address | Everything | No port, no weights, no health, caching |
| SRV | Priority, weight, port, target host | Consul DNS, Kubernetes named ports, Cloud Map, SIP/XMPP, gRPC grpclb | Many HTTP clients ignore SRV; Go net.LookupSRV and PHP dns_get_record(..., DNS_SRV) need you to use it explicitly |
| CNAME | Alias | ExternalName Services, DNS aliases | Redirection at DNS level, no proxying |
| TXT | Metadata | Rare for discovery | No standard schema |
| Product | What DNS returns | TTL / caching | Notes |
|---|---|---|---|
| Kubernetes + CoreDNS | ClusterIP A record; headless Service: all pod IPs; SRV per named port | CoreDNS kubernetes plugin ttl default 5 s, max 3600, 0 disables caching | Pod 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 randomised | Per Consul DNS config | "Consul randomizes DNS SRV records and ignores weights specified in service configurations", so weights are unreliable over DNS |
| AWS Cloud Map | DNS records in a VPC (or public) namespace, only healthy instances when health checking is on | Per record TTL you set | Alternative: DiscoverInstances API |
| Docker Compose | Service name resolves to container IPs on the project network | Docker's embedded DNS | "Each service registers its name with an internal DNS server"; IPs change when recreated |
| Route 53 / public DNS | Records you publish | Resolver and TTL dependent | Eureka'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.
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| Probe | Mechanism options | Default behaviour on failure | Key fields | Used by |
|---|---|---|---|---|
| Kubernetes startup | httpGet, tcpSocket, exec, grpc | Container killed, then restartPolicy | failureThreshold, periodSeconds (budget = product) | kubelet |
| Kubernetes liveness | same | Container restarted | initialDelaySeconds, periodSeconds, timeoutSeconds, failureThreshold | kubelet |
| Kubernetes readiness | same | Removed from Service endpoints | same, plus successThreshold | kubelet, EndpointSlice controller |
| Consul checks | HTTP, TCP, UDP, gRPC, script, OS service, TTL, alias | New checks start critical; critical instances are omitted from DNS and ?passing queries | Interval, Timeout, DeregisterCriticalServiceAfter | Consul agent |
| Envoy active health checking | HTTP, gRPC, L3/L4 byte buffer | Host marked unhealthy after N failures, back after M successes | interval, unhealthy/healthy thresholds | Envoy |
| AWS Cloud Map | Route 53 health checks or a third-party checker | Only healthy instances returned | per service | Cloud Map |
| Eureka | Client heartbeat (lease) plus optional health check handler | Lease expiry removes the instance | renewal interval, lease duration | Eureka 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:
| Check | Include | Exclude | Why |
|---|---|---|---|
| Liveness | Event loop responsive, no deadlock, memory sane | Any network dependency | A dependency outage cannot be fixed by restarting this pod |
| Readiness | Started, not draining, critical local dependencies (own database, own cache that the request path cannot bypass) | Optional services, downstream services you can degrade around | If readiness fails everywhere, the Service has zero endpoints and the outage is total |
| Startup | Config loaded, migrations check, warm-up complete | Slow optional work | Keep the budget focused |
Synthetic deep check (separate endpoint, e.g. /healthz/deep) | Everything, with timings | Do not wire to probes | For humans and dashboards |
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 type | Readiness? | Cache the result? | Timeout |
|---|---|---|---|
| Own primary database | Yes (cheap select 1) | 1 to 5 s | Below the probe timeout |
| Own cache (Redis) on the hot path | Only if there is no fallback | 1 to 5 s | Same |
| Another microservice | No (use a circuit breaker) | n/a | n/a |
| Message broker | Only for pure consumers that cannot do anything without it | 5 s | Same |
| Feature-flag service, analytics, email | Never | n/a | n/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".
| Setting | Effect | Typical start |
|---|---|---|
periodSeconds | Probe frequency | 5 to 10 s readiness, 10 s liveness |
timeoutSeconds | Per-probe patience | 1 to 2 s; below the app's slow-query timeouts |
failureThreshold | Failures in a row before reacting | 3 readiness, 3 or more liveness, startup large |
successThreshold | Successes in a row to become ready | 1 (liveness must be 1) |
| Startup budget | failureThreshold x periodSeconds | Worst-case boot time with margin (the K8s example: 30 x 10 s = 300 s) |
| Jitter | Spreads heartbeats and checks | 10 to 20 % |
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 3Real 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".
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)| Step | Duration to plan | Where it lives |
|---|---|---|
| Pod marked terminating (Kubernetes) or readiness flipped (other systems); endpoint removed | Controller lag (Kubernetes) or probe/heartbeat period | kubelet, EndpointSlice controller |
| Propagation to proxies, DNS, client lists | The slowest layer you have (see staleness chain) | kube-proxy, CoreDNS, Envoy, client caches |
| In-flight request completion | The longest legitimate request | Your server's Shutdown timeout |
| Total | Must be below terminationGracePeriodSeconds | Pod 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.
| Policy | Needs from discovery | Good for | Watch out |
|---|---|---|---|
| Round robin | The ready list | Uniform, cheap requests | Hot spots when costs differ; thundering herd to a new instance |
| Weighted round robin | Weights/metadata per instance (Eureka metadata, Consul Weights, EDS weights) | Mixed instance sizes, canaries | Weights go stale; SRV weights are ignored by Consul DNS |
| Least connections / least loaded | Live per-connection counts (client or proxy side) | Variable request cost | Fast-failing sick backends look idle: SRE calls it "sinkholing", fix by counting recent errors as active requests |
| Consistent hashing | Stable instance identities | Caches, sticky shards, consistent hashing | Registry churn reshuffles keys |
| Zone-aware / locality | Zone of each endpoint (EDS "zone", Kubernetes topology hints) | Latency and cross-zone cost | Zone imbalance; fallbacks |
| Subsetting | Large instance lists | Limit connections per client | Uneven subsets if done naively |
| Random with two choices, panic mode | Health state | Resilience when most hosts look unhealthy | Hides 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:
| System | Leaning | Evidence | Behaviour during a partition |
|---|---|---|---|
| Eureka | Availability 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" |
| Consul | CP for the catalog (Raft); read modes tunable | Quorum "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, stale | Writes (registrations) stop without a leader; stale reads still work on any server |
| etcd | CP (Raft) | Linearizable reads by default; serializable local reads optional; leases | Minority side cannot commit; leases cannot be renewed there |
| Kubernetes | CP store (etcd) behind an API server; eventual to every node proxy | EndpointSlices propagate via watch | Nodes keep their last programmed rules |
| Envoy + EDS | Eventual by design | 2x2 matrix below | Keeps 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.
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| Mechanism | Pushed by | Latency | Notes |
|---|---|---|---|
| Kubernetes Service + kube-proxy | API server watch | Seconds | Per-connection balancing |
| Envoy strict DNS | Periodic DNS (dns_refresh_rate default 5000 ms, respect_dns_ttl) | TTL or 5 s | Draining of removed IPs |
| Envoy EDS | Control plane stream | Push | Weights, zones, canary info |
| Consul Connect / service mesh | Consul servers to Envoy | Push | Registry 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."
| Approach | How | Examples | Trade-off |
|---|---|---|---|
| Local first, remote on failure | Local registry plus failover to remote | Consul 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 / federation | Clusters exchange services | Consul cluster peering ("connect two or more independent Consul clusters"), WAN federation | Operational overhead, explicit exports |
| Global DNS in front | GeoDNS/latency routing to regional entry points | Route 53, Cloud Map public namespaces; see GeoDNS | DNS TTL limits failover speed |
| Mesh gateways | East-west gateways expose services across clusters | Istio multi-cluster, Consul mesh gateways | Cross-cluster mTLS and policy |
| Application-level | The app chooses a region and URL | Config per region | Simple, 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.
| Threat | Example | Control |
|---|---|---|
| Spoofed registration | A rogue pod registers as payments | Registry 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 service | Read ACLs; Consul results can be filtered by ACL (X-Consul-Results-Filtered-By-ACLs: true) |
| Man-in-the-middle after discovery | Address is right, the endpoint is not | mTLS with service identity verified against the name, not the IP: see mTLS |
| Script-check execution | Remote agents can be told to run scripts | Consul warns that enabling non-local script checks "may introduce a known remote execution vulnerability"; use enable_local_script_checks, prefer HTTP/TCP checks |
| Registry takeover | Stolen server credentials | Separate gossip and RPC encryption, TLS between agents and servers, least-privilege tokens |
| DNS poisoning / cache | Spoofed A answers | DNSSEC 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.
| Signal | Why | Where from |
|---|---|---|
| Instances per service (ready vs registered) | Capacity and rollout health | Registry 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 proxy | EndpointSlice watch events, Envoy membership_change, membership_healthy |
| Registration/heartbeat failures | Registry unreachable, auth broken | Client logs and metrics |
| Lease expiries vs graceful deregisters | Crashes versus clean stops | Registry logs |
| DNS error rate and latency | NXDOMAIN storms, ndots search-list amplification | CoreDNS metrics (including per-service-kind duration), resolver logs |
| Envoy DNS stats | update_attempt, update_success, update_failure | Envoy cluster stats (documented in the service discovery page) |
| Per-instance error rate at the caller | Detects stale entries | Client metrics tagged with instance id |
| Registry health | Raft leader, quorum, commit latency | Consul/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."
| Environment | Discovery | Config the app sees |
|---|---|---|
| Laptop, one process | Static | ORDERS_URL=http://127.0.0.1:8081 |
| Docker Compose | Embedded DNS, service name | ORDERS_URL=http://orders:8080 |
| Kubernetes | Service + CoreDNS | ORDERS_URL=http://orders.shop.svc.cluster.local:8080 |
| VMs with Consul | Consul DNS or agent | ORDERS_SRV=orders.service.consul |
| Tests | Fake 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.
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
| Aspect | Eureka | Consul | etcd (DIY) | Kubernetes | AWS Cloud Map | Envoy / Istio |
|---|---|---|---|---|---|---|
| Registration | Self (client) | Self or agent service file / sidecar | Self via lease + key | Platform (pods → EndpointSlices) | RegisterInstance API, ECS integration | From Kubernetes or Consul |
| Health | Heartbeat lease; optional health handler | HTTP, TCP, gRPC, UDP, script, TTL, OS service | Lease keepalive | Probes (readiness gates endpoints) | Route 53 health checks or third party | Active HC + outlier detection |
| Lookup | Client library (REST) | HTTP API, DNS, blocking queries | Watch | DNS + virtual IP; API | DiscoverInstances or DNS | xDS push |
| Detects crash by | Missed renewals (about 90 s default) | Failing check (interval based) | Lease TTL | Probe failure; node-controller for node loss | Health check | Active HC interval |
| Consistency | Eventual (AP-style) | Raft (CP), tunable reads | Raft, linearizable | etcd store, eventual in nodes | Managed | Eventual by design |
| Strong point | Survives registry outages | Rich checks, KV, DNS, mesh | Primitive for DIY registries and leases | Built in, no extra component | No servers to run on AWS | Per-request control |
| Weak point | Stale entries, JVM-centric | You run a Raft cluster | You write everything else | Cluster-local | AWS-only | Operating the mesh |
Mechanics
Kubernetes manifests: probes, Service, headless Service, drain
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
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
| Where | Setting or message | Meaning | Remedy |
|---|---|---|---|
| Kubernetes | Readiness probe failed: HTTP probe failed with statuscode: 503 | Pod not Ready; removed from endpoints | Check the dependency named in your /readyz output |
| Kubernetes | Liveness probe failed ... Container ... failed liveness probe, will be restarted | Restart in progress | Is liveness too deep or the timeout too short? |
| Kubernetes | Startup probe failed and the container is killed after the budget | Slow boot or wrong path | Raise failureThreshold x periodSeconds |
| Kubernetes DNS | NXDOMAIN for data from another namespace | Short names expand only in the pod's namespace | Use data.prod or the FQDN |
| Kubernetes DNS | options ndots:5 | Names with fewer than 5 dots try the search list first | End FQDNs with a dot or lower ndots for external names |
| Go | dial tcp: lookup orders on 10.96.0.10:53: no such host | Name does not exist (yet) | Retry with backoff; check Service name and namespace |
| Go | connect: connection refused to a listed address | Stale entry or instance draining | Passive ejection, retry another instance |
| Consul | rpc error: No cluster leader | Raft quorum lost | Restore quorum; use stale reads in the interim |
| Consul | Check status critical | Failing check | Instance omitted from DNS and ?passing |
| etcd | Lease TTL expired; key deleted | Missed keepalives | Increase TTL or fix the stall |
| Registry | Renew returns 404 / unknown lease | Lease gone after restart/partition | Re-register (the Go client does) |
| HTTP | 502 / 503 during deploy | No readiness gating or no drain | Probes 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).
// 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)
}
}
}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.
// 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
}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.
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
}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):
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 := ®client.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
// 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
}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.
// 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).
// 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":{}}]}`),
)
}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.
// 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.
// 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/httpkeeps 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 withTransport.IdleConnTimeoutand handle connection errors by retrying on another instance.signal.NotifyContextis the idiom for SIGTERM; combine it withhttp.Server.Shutdownafter the drain delay.contextdeadlines 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
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
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
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
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
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
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
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
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.
DiagnosingHealthruns on/up; do not put database checks there if/upis your liveness probe.- Queue workers (
queue:work) are also pods: they need a liveness signal and a graceful stop (queue:restartor SIGTERM and--timeout), see Laravel Queue Internals. - Per-environment URLs belong in
config/services.phpand.env, not in code.
Solving the classic problems
Dead instances still receive traffic
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Short lease/TTL plus watch | Heartbeat every TTL/3; clients watch | Fast detection | False expiry under pauses |
| Passive ejection (outlier detection) | Client or proxy ejects after N errors | Reacts in one request | Needs a retry on another instance |
| Active health checks | Proxy probes every instance | Independent of the app's heartbeat | Extra probe load |
| Retries with a budget | Retry on another instance, capped | Hides the gap from users | Amplifies load (timeouts and retries) |
Errors during rolling deploys
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Readiness gating | readinessProbe plus a real /readyz | New pods get traffic only when warm | Needs a good endpoint |
maxUnavailable: 0, maxSurge: 1 | New pod Ready before old is drained | Capacity never drops | Slower rollout, extra capacity |
| preStop drain delay | Sleep or app:drain before SIGTERM | Late requests succeed | Longer rollout |
| Graceful server shutdown | Shutdown(ctx) / octane:stop | In-flight requests finish | Must fit in the grace period |
| Connection max age | Server closes keep-alive connections gradually | Rebalances after scale-out | Extra 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
| Failure | Symptom | Root cause | Fix |
|---|---|---|---|
| Split brain | Two clients see different lists | Partitioned AP registry | CP registry for coordination; tolerate stale lists |
| Thundering registry | Registry falls over after restart | Synchronised re-registration | Jitter, backoff, local agents |
| DNS cache | Calls to removed pods for minutes | Client resolves once or ignores TTL | Re-resolve, short caps, max connection age |
| Self-preservation lock | Dead hosts listed for a long time | Eureka threshold reached | Retry and timeout at the client; investigate partition |
| Flapping | Endpoint churn, latency spikes | Probe too sensitive | Thresholds, shallow checks |
| Empty pool | 100% errors | Readiness depends on a shared dependency | Readiness only for critical local dependencies |
| Restart storm | Pods restart together | Liveness checks a dependency | Shallow liveness |
| No drain | 502 burst at deploy | Exit on SIGTERM, no preStop | Drain delay, graceful shutdown |
| Zombie registration | Entry for a dead process | No TTL, or TTL very long | Leases and DeregisterCriticalServiceAfter |
| Wrong-instance spoof | Traffic to a rogue instance | Open registry writes | ACLs, mTLS by name |
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Everything runs on Kubernetes | Service + CoreDNS (server-side), readiness probes | Headless + round_robin for gRPC | The platform already is the registry |
| Polyglot services on VMs | Consul agents with service files and DNS | stale reads for resilience | Language independent, health aware |
| Homogeneous JVM fleet, high RPS | Eureka or Consul with a smart client | Client-side LB, zone awareness | One hop fewer, rich balancing |
| gRPC with many long-lived connections | Client-side round_robin over DNS/xDS or L7 proxy | Max connection age | L4 balancing pins connections |
| Many clusters or regions | Registry per cluster plus explicit cross-cluster | Peering, mesh gateways | Region isolation |
| Already running a mesh | Mesh discovery (EDS) only | Outlier detection | One system, not two |
| 3 services, 1 team | Static config or Compose names | Health route and timeouts | Do not build infrastructure you do not need |
| AWS-only, ECS/EC2 | Cloud Map or load balancer target groups | Route 53 health checks | Managed 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:
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 itWhat 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
| Scale | Discovery shape | Typical problem | Next step |
|---|---|---|---|
| 1x (a few services, one team) | Config + Compose names or Kubernetes Services | Hard-coded URLs, missing health route | Environment-driven URLs, /up, timeouts |
| 10x (tens of services) | Kubernetes Service/DNS, readiness and startup probes, drain | Deploy errors, flapping probes, DNS ndots amplification | Tune 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, peering | Endpoint churn cost, registry blast radius, cross-region failover | Subsetting, 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)
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):
20:37:20 ok orders-1
20:37:21 ok orders-2
20:37:21 ok orders-1
20:37:22 ok orders-2Experiment 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.
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.
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.
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 ShutdownExperiment 5 (Kubernetes, not run here): readiness during a rolling deploy. Apply the manifests in Mechanics on a cluster (kind or minikube), then:
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=trueRun 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
| Belief | Reality |
|---|---|
| "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
| Topic | What to remember |
|---|---|
| Three jobs | Registration, health, lookup; every outage is a failure in one of them or in a cache between them |
| Registration | Self for state the platform cannot see; third-party (platform, agent, sidecar) for polyglot fleets |
| Lease | TTL = about 3 x heartbeat; add jitter; handle "lease unknown" by re-registering |
| Client-side | Fewer hops, thick client, per-language library; cache and watch, stale if error |
| Server-side | One stable name, an extra hop, the router must be HA; Kubernetes Service is the default |
| DNS | A/AAAA no port; SRV has priority, weight, port; caches ignore TTLs; headless Service returns pod IPs |
| Probes | Startup (budget), liveness (shallow, restarts), readiness (critical local deps, removes from endpoints) |
| Deep checks | Never in liveness; cache results; exclude optional and downstream services from readiness |
| Flapping | failureThreshold 3, timeouts 1 to 2 s, watch endpoint churn |
| Drain | Fail readiness, wait for propagation (preStop), then Shutdown; total below the grace period (default 30 s) |
| Consistency | Eventual plus health checks is enough for address lists; CP for locks and leader election |
| Mesh | Control plane pushes EDS to proxies; the registry is still the source |
| Multi-cluster | Registry per cluster, explicit failover, observable |
| Security | ACLs by service name, mTLS verifies the name, avoid non-local script checks |
| Staleness | Time to stop traffic = sum of probe, controller, proxy, DNS, client and connection delays |
Self-check: questions & answers
- 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
| Term | One line |
|---|---|
| Service discovery | Mechanism by which a caller finds the current addresses of a service's instances |
| Service registry | Database of services, instances and locations, kept alive by registration and health |
| Self-registration | Instance registers and renews itself |
| Third-party registration | Platform, agent or sidecar registers instances on their behalf |
| Registrator / Prana | Examples of third-party registrars (Docker containers / Eureka sidecar) |
| Lease | Time-bounded registration that must be renewed |
| TTL | Time to live: lease duration, DNS record cache time, or a Consul TTL check |
| Heartbeat | Periodic renewal message proving the instance is alive |
| Deregistration | Removing an instance from the registry, on shutdown or by expiry |
| Client-side discovery | Client queries the registry and balances itself |
| Server-side discovery | A router queries the registry and balances; client calls one name |
| Lookaside load balancer | A balancer server clients ask for a backend, off the data path |
| Ribbon / Eureka | Netflix client-side load balancer and registry |
| Consul | HashiCorp registry with catalog, health checks, DNS and mesh |
| etcd | Raft key-value store with leases and watches, used as a registry primitive |
| Blocking query | Long poll that returns when an index changes (Consul index/wait) |
| A / AAAA record | DNS record mapping a name to an IPv4 / IPv6 address |
| SRV record | DNS record with priority, weight, port and target (RFC 2782) |
| Headless Service | Kubernetes Service with clusterIP: None; DNS returns pod IPs |
| ClusterIP / kube-proxy | Virtual IP and the node component that programs forwarding rules |
| EndpointSlice | Kubernetes object listing a Service's endpoints with ready/serving/terminating |
| CoreDNS | Cluster DNS server in Kubernetes; kubernetes plugin serves Service names |
| ndots | resolv.conf option controlling search-list expansion of short names |
| Startup / liveness / readiness probe | Boot finished / restart if stuck / take traffic now |
| Deep vs shallow check | With vs without calls to dependencies |
| Flapping | Rapid alternation between healthy and unhealthy states |
| Drain / lame duck | State where an instance stops receiving new work but finishes existing work |
| preStop hook | Kubernetes hook run before SIGTERM, used to delay shutdown for propagation |
| terminationGracePeriodSeconds | Time between SIGTERM and SIGKILL (default 30 s) |
| Self-preservation | Eureka mode that stops expiring instances when renewals drop |
| Outlier detection / passive health check | Ejecting an instance after observed errors |
| xDS / EDS / ADS | Envoy discovery APIs / endpoint discovery / aggregated stream |
| Split brain | Two parts of a system each believing they are authoritative |
| Thundering herd | Many clients acting at once and overloading a shared component |
| Cloud Map | AWS managed service registry with DNS and API discovery |
References
- Chris Richardson, Pattern: Client-side service discovery: https://microservices.io/patterns/client-side-discovery.html
- Chris Richardson, Pattern: Server-side service discovery: https://microservices.io/patterns/server-side-discovery.html
- Chris Richardson, Pattern: Service registry: https://microservices.io/patterns/service-registry.html
- Chris Richardson, Pattern: Self Registration: https://microservices.io/patterns/self-registration.html
- Chris Richardson, Pattern: 3rd Party Registration: https://microservices.io/patterns/3rd-party-registration.html
- Netflix Eureka wiki, Eureka at a glance: https://github.com/Netflix/eureka/wiki/Eureka-at-a-glance
- Netflix Eureka wiki, Understanding Eureka Peer to Peer Communication: https://github.com/Netflix/eureka/wiki/Understanding-Eureka-Peer-to-Peer-Communication
- Netflix Eureka wiki, FAQ: https://github.com/Netflix/eureka/wiki/FAQ
- HashiCorp Consul, Define health checks: https://developer.hashicorp.com/consul/docs/services/usage/checks
- HashiCorp Consul, DNS overview: https://developer.hashicorp.com/consul/docs/services/discovery/dns-overview
- HashiCorp Consul, Perform static DNS queries: https://developer.hashicorp.com/consul/docs/services/discovery/dns-static-lookups
- HashiCorp Consul, Consensus: https://developer.hashicorp.com/consul/docs/architecture/consensus
- HashiCorp Consul, Consistency modes: https://developer.hashicorp.com/consul/docs/concept/consistency
- HashiCorp Consul, Agent service API: https://developer.hashicorp.com/consul/api-docs/agent/service
- HashiCorp Consul, Health API: https://developer.hashicorp.com/consul/api-docs/health
- HashiCorp Consul, Blocking queries: https://developer.hashicorp.com/consul/api-docs/features/blocking
- HashiCorp Consul, Cluster peering: https://developer.hashicorp.com/consul/docs/east-west/cluster-peering
- etcd, API guarantees / gRPC API (Lease, Watch): https://etcd.io/docs/v3.5/learning/api/
- Kubernetes, Service: https://kubernetes.io/docs/concepts/services-networking/service/
- Kubernetes, EndpointSlices: https://kubernetes.io/docs/concepts/services-networking/endpoint-slices/
- Kubernetes, DNS for Services and Pods: https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/
- Kubernetes, Virtual IPs and Service proxies: https://kubernetes.io/docs/reference/networking/virtual-ips/
- Kubernetes, Configure liveness, readiness and startup probes: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/
- Kubernetes, Pod lifecycle: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/
- Kubernetes, Topology Aware Routing: https://kubernetes.io/docs/concepts/services-networking/topology-aware-routing/
- CoreDNS, kubernetes plugin: https://coredns.io/plugins/kubernetes/
- RFC 2782, A DNS RR for specifying the location of services (DNS SRV): https://www.rfc-editor.org/rfc/rfc2782
- Envoy, Service discovery: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/service_discovery
- Envoy, Health checking: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/health_checking
- Envoy, xDS configuration API overview: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/operations/dynamic_configuration
- Istio, Architecture: https://istio.io/latest/docs/ops/deployment/architecture/
- AWS, What is AWS Cloud Map?: https://docs.aws.amazon.com/cloud-map/latest/dg/what-is-cloud-map.html
- Google, Site Reliability Engineering, Load Balancing in the Datacenter: https://sre.google/sre-book/load-balancing-datacenter/
- gRPC, Load Balancing in gRPC: https://grpc.io/blog/grpc-load-balancing/
- gRPC, Name Resolution: https://github.com/grpc/grpc/blob/master/doc/naming.md
- grpc-go source,
resolver/resolver.goand the DNS resolver: https://github.com/grpc/grpc-go/blob/master/resolver/resolver.go - Laravel 13 docs, Deployment (the health route): https://laravel.com/docs/13.x/deployment
- Laravel 13 docs, Routing (
withRouting(health:)): https://laravel.com/docs/13.x/routing - Laravel 13 docs, HTTP Client: https://laravel.com/docs/13.x/http-client
- Laravel 13 docs, Octane: https://laravel.com/docs/13.x/octane
- Go source,
net/lookup.go(LookupSRV,Resolver; same text asgo doc net.LookupSRV): https://go.dev/src/net/lookup.go - PHP manual,
dns_get_record: https://www.php.net/manual/en/function.dns-get-record.php - Docker, Networking in Compose: https://docs.docker.com/compose/how-tos/networking/
- Kubernetes, Termination of Pods: https://kubernetes.io/docs/concepts/workloads/pods/pod-termination/
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.