System Design Part 7 Architecture evolution

Service Discovery: How Services Find Each Other, and What Happens When an Instance Disappears

Bill.Lin 15 min read

System Design series Part 7-2 | Previous: Monolith vs Microservices | Next: Sagas and the Outbox Pattern | Series map

Read first: Part 2-2 Load Balancing in Depth.

Scenario and problem

The previous post split payment out into its own service. The sign-up service has to call the payment service, and the first question is: where is the payment service?

The payment service has 3 to 12 instances and scales out and in automatically with traffic. Every deploy replaces all the instances with new ones, and their IP addresses change with them. When an instance crashes, you want to stop sending it requests as soon as possible. A config file with hard-coded IP addresses stops working after the first deploy.

Where is the payment service?1 / 4
Where is the payment service?Pay 10.0.1.5Sign-up APIPay 10.0.1.6Pay 10.0.1.7Sign-up APIPay 10.0.1.5Pay 10.0.1.6Pay 10.0.1.7fixed IPfixed IPfixed IP3 IPs hard-codedSign-up APIPay 10.0.1.6Pay 10.0.1.7fixed IPNew, nobody knowsSign-up APIPay 10.0.1.5old IP, unreachableNew IP after deploySign-up APIPay 10.0.1.6unaware, still sendsJust crashedThe list always lags
  1. Hard-coded in the configOnce payment is its own service, the sign-up service has to know where the payment service is. The most obvious approach is to write the IP addresses into a config file.
  2. A new autoscaled instanceThe payment service scales between 3 and 12 instances with traffic. A newly added instance is not in the config file, so it never gets any traffic.
  3. New IPs after a deployEvery deploy replaces all the instances with new ones, and their IP addresses change with them. The hard-coded config file stops working after the first deploy.
  4. The moment it crashesAn instance has crashed, and you want to stop sending it requests as soon as possible. But between the crash and the moment every caller knows about it, there is always a gap.

Service discovery has to answer two questions:

  • Which instances can accept requests right now (registration and health status)
  • How the caller gets this list and picks an instance from it (lookup and load balancing)

And this list is always behind: between the moment an instance crashes and the moment every caller knows, there is always a gap. Most of the design of service discovery is about handling this gap.

The simplest approach and its limits

  • Hard-code the instance addresses in a config file: every scale-out, scale-in, and deploy means changing the config and restarting the callers
  • Put a load balancer with a fixed address in front: the caller only needs to know the load balancer’s address, which is in fact the simplest form of server-side discovery. But the load balancer itself has to know which instances are behind it, so the problem has only moved to the load balancer; and every request takes one more hop

Core mechanism

Registration: who adds instances to the list

Approach How Examples
Self-registration The instance registers itself with the registry on startup, sends heartbeats periodically, and deregisters itself on shutdown Eureka and Consul client libraries
Platform registration The deployment platform does it: once an instance starts and passes its health check, the platform adds it to the list Kubernetes updates EndpointSlices from the readiness probe; target groups of cloud load balancers

Self-registration needs every service to integrate the registry’s client library, and a crashed instance cannot deregister itself, so you can only wait for its heartbeat to time out. Platform registration means the application does not need to know the registry exists, and it is the more common approach today.

Health: are the instances on the list really usable

The registry uses leases to decide whether an instance is still alive (the same idea as the etcd lease in Consensus and Raft): the instance renews its lease periodically, and if it does not renew before the deadline, it is removed.

Take Eureka’s defaults as an example: an instance sends a heartbeat every 30 seconds, and the server removes it only after 90 seconds without one; callers fetch the list from the server every 30 seconds, and the load balancer may have its own cache on top of that. After an instance crashes, callers may in the worst case keep sending it requests for close to two minutes.

Shorter intervals shrink this window, at the cost of more heartbeat traffic, and during brief network jitter even healthy instances can be judged dead and removed.

So service discovery cannot replace the caller’s own protection: the list will always contain instances that are already dead, and the caller needs timeouts, retries against other instances, and circuit breakers (Part 6).

Lookup: how the caller picks an instance

flowchart TB
    subgraph S["Server-side discovery"]
        C1[Sign-up service] --> LB[Load balancer<br/>or Kubernetes Service]
        LB --> P1[Payment #1]
        LB --> P2[Payment #2]
    end
    subgraph CS["Client-side discovery"]
        C2[Sign-up service<br/>with built-in load balancing] -->|fetch the list| R[(Registry)]
        C2 --> P3[Payment #1]
        C2 --> P4[Payment #2]
    end
Approach Advantages Cost
Server-side (load balancer, Kubernetes Service) The caller only needs a name and no special library, so any language works One more hop; L4 load balancing works per connection, so long-lived connections stick to one instance
Client-side (Eureka + Spring Cloud LoadBalancer, gRPC name resolution) No hop in the middle, and smarter algorithms are possible (such as P2C from Load Balancing in Depth) Every language needs a client library, and the algorithm and settings are spread across every caller
DNS Every language and tool supports it TTLs and DNS caches at every layer slow updates down; a plain A record carries no port or weight
Service mesh (sidecar or per-node proxy) Discovery, load balancing, retries, and mTLS all go to the proxy, with no changes to the application Latency and resources of one more proxy layer; the control plane itself has to be operated

Should the registry be CP or AP

The registry is a distributed system too, and it faces the same CAP trade-off:

  • CP (etcd, Consul, ZooKeeper): the list is consistent, but when the registry loses a majority of its nodes, it can no longer be updated
  • AP (Eureka): during a network partition, each node serves its own, possibly stale, list. When a large number of instances miss their renewals within a short time, Eureka enters self-preservation mode and stops removing instances, because it judges that “a network problem is more likely than every instance dying”

For service discovery, a stale list is usually better than no list: a few dead instances on the list can be handled by the caller’s retries; with no list at all, every call fails. So whatever kind of registry you use, callers should cache the last list they fetched successfully and keep using it while the registry is down.

Kubernetes: Services, EndpointSlices, and the shutdown order

On Kubernetes, service discovery is built into the platform:

  • Each Service has a stable DNS name (payment.lectures.svc.cluster.local) and a virtual IP
  • Pods that pass the readiness probe are added to that Service’s EndpointSlice
  • kube-proxy on each node sets up forwarding rules from the EndpointSlice and hands each connection to the virtual IP to one of the Pods

The easiest thing to get wrong is the shutdown order. When a Pod is deleted, two things start at the same time, and neither waits for the other:

  1. The kubelet runs the preStop hook, then sends SIGTERM to the container
  2. The control plane removes the Pod from the EndpointSlice, and kube-proxy on each node, the Ingress controller, and the service mesh update their forwarding rules one after another

If the application stops accepting connections the moment it gets SIGTERM while some nodes have not updated their forwarding rules yet, requests sent to this Pod fail. The fix is to wait a few seconds in preStop so the forwarding rules finish updating, and only then start the graceful shutdown:

sequenceDiagram
    participant K as kubelet
    participant A as Payment service Pod
    participant E as EndpointSlice and kube-proxy
    Note over K,E: Delete the Pod
    par Start at the same time
        K->>A: preStop: wait 10 seconds (still serving requests normally)
    and
        E->>E: Remove this Pod, each node updates its forwarding rules
    end
    K->>A: SIGTERM
    A->>A: Spring Boot graceful shutdown:<br/>no new requests, wait for in-flight ones to finish (up to 20 seconds)
    Note over K,A: All of it must finish within terminationGracePeriodSeconds

Another common problem: kube-proxy distributes per connection. Once an HTTP keep-alive or gRPC long-lived connection is set up, every request goes to the same Pod, and newly added Pods get no traffic. For long-lived connections like gRPC, use a headless Service so the client gets the addresses of all the Pods and balances across them itself (REST, gRPC, and GraphQL), or let a service mesh do L7 load balancing.

Comparing options

Environment Recommendation
Kubernetes, mostly short HTTP requests Use the Service’s DNS name directly; no extra registry needed
Kubernetes, gRPC, or a need for L7 load balancing and mTLS A headless Service plus client-side load balancing, or adopt a service mesh
Virtual machines or hybrid environments A registry such as Consul, or cloud load balancer target groups
An existing Spring Cloud Netflix system Eureka plus Spring Cloud LoadBalancer still works; when moving to Kubernetes, you usually switch to the platform’s built-in mechanism

The talk platform’s choice: it deploys on Kubernetes, and the sign-up service calls the payment service by its Service DNS name; gRPC calls between the live interaction services use a headless Service and round robin. No service mesh for now; mTLS between services will be evaluated in Part 8.

In Java

1. Kubernetes: call by name and let the platform handle discovery

yaml
spring:
  http:
    serviceclient:
      payment:
        base-url: http://payment.lectures.svc.cluster.local
        connect-timeout: 300ms
        read-timeout: 1s
  lifecycle:
    timeout-per-shutdown-phase: 20s     # wait at most 20 seconds for graceful shutdown

management:
  endpoint:
    health:
      probes:
        enabled: true
        add-additional-paths: true      # serve /readyz and /livez on the main port

spring.http.serviceclient.payment configures the “payment” group of HTTP service clients, which you use with a declarative interface:

java
@HttpExchange("/v1/charges")
public interface PaymentApi {

    @PostExchange
    ChargeResult charge(@RequestHeader("Idempotency-Key") String idempotencyKey, @RequestBody ChargeRequest request);
}

@Configuration
@ImportHttpServices(group = "payment", types = PaymentApi.class)
public class PaymentClientConfig {
}
  • The caller knows only the Service’s name; Kubernetes handles instances coming and going
  • Put the readiness probe on the main port: it should reflect “can the application handle requests”, and the management endpoints may be on a different port (Observability), so the management port may still answer normally even after the main port has stopped serving
  • Spring Boot enables the liveness and readiness health groups by default on Kubernetes; they are written out explicitly here

2. The Pod shutdown order

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: payment
  namespace: lectures
spec:
  replicas: 3
  selector:
    matchLabels:
      app: payment
  template:
    metadata:
      labels:
        app: payment
    spec:
      terminationGracePeriodSeconds: 40        # 10 s preStop + 20 s graceful shutdown + buffer
      containers:
        - name: payment
          image: registry.example.com/lectures/payment:2026.11.23
          ports:
            - containerPort: 8080
          readinessProbe:
            httpGet:
              path: /readyz
              port: 8080
            periodSeconds: 5
          livenessProbe:
            httpGet:
              path: /livez
              port: 8080
            periodSeconds: 10
          lifecycle:
            preStop:
              sleep:
                seconds: 10                    # wait for the forwarding rules to update, then start shutting down
  • terminationGracePeriodSeconds covers both preStop and the application’s shutdown, and defaults to 30 seconds. The 10 + 20 seconds here is already close to the default, so it is raised to 40 seconds
  • The preStop sleep action is built into Kubernetes and does not need a sleep command in the container image (distroless images have none), but it needs a fairly recent Kubernetes version; older versions can only run sleep through exec
  • The liveness probe should not check the database or downstream services; otherwise, when a downstream fails, every Pod is restarted at once (Load Balancing in Depth)

3. Not on Kubernetes: client-side discovery

java
@Configuration
public class LoadBalancedClientConfig {

    @Bean
    @LoadBalanced
    RestClient.Builder loadBalancedRestClientBuilder() {
        return RestClient.builder();
    }
}

@Component
public class PaymentClient {

    private final RestClient restClient;

    public PaymentClient(@LoadBalanced RestClient.Builder builder) {
        // payment-service is the service name in the registry, not a DNS name
        this.restClient = builder.baseUrl("http://payment-service").build();
    }

    public ChargeResult charge(ChargeRequest request, String idempotencyKey) {
        return restClient.post()
                .uri("/v1/charges")
                .header("Idempotency-Key", idempotencyKey)
                .body(request)
                .retrieve()
                .body(ChargeResult.class);
    }
}

@LoadBalanced makes Spring Cloud LoadBalancer intercept the request and replace the service name with the address of one of the instances the registry (Eureka, Consul) provides. The Spring Cloud version has to be compatible with the Spring Boot version.

The configuration and code above are written from the official Spring Boot 4.1, Spring Cloud, and Kubernetes documentation and have not been run.

Pitfalls and gotchas

  • Assuming the list is real-time: between an instance crashing and the caller finding out, there are delays from heartbeat intervals, timeouts, and caches. Callers still need timeouts and retries
  • Not waiting on shutdown: the instance stops serving as soon as it gets SIGTERM, before the forwarding rules have updated, so every deploy has a short window of errors
  • terminationGracePeriodSeconds too short: preStop plus graceful shutdown runs past the deadline, and in-flight requests are cut off forcibly
  • Readiness checks too much: readiness checks downstream services, so the moment a downstream has a problem, every instance is removed from the Service and the service goes down completely
  • Long-lived connections stuck to old instances: after scaling out, the new Pods get no traffic and the old Pods are overloaded
  • DNS caching: the JVM, the operating system, and the DNS servers in between each keep their own cache, so after the address behind a name changes, some callers still connect to the old address (see the JVM DNS settings in Redundancy, Failover, and DR)
  • The registry becomes a single point of failure: callers do not cache the list, so once the registry stops, every call between services fails with it
  • Self-registered instances that never deregister: an instance that crashes or is force-killed stays listed until its lease expires, and requests during that time fail

Security

  • Registry spoofing: if any program can register instances with the registry, an attacker who gets hold of one machine on the internal network can register that machine as payment-service and receive the payment requests the sign-up service sends, along with the data in them. Require authentication and authorization on the registry (for example Consul ACLs), and on Kubernetes restrict who can create or modify Services and EndpointSlices. Kubernetes CVE-2020-8554 is one example: a user who can create a Service and set an external IP can intercept traffic inside the cluster that is headed for that IP
  • A name is not an identity: service discovery returns an address, not proof of identity. Even if the registry or DNS has been tampered with, as long as the caller verifies the other side’s certificate with mTLS (for example a SPIFFE-format service identity), a connection to the wrong instance fails at the TLS handshake. Authentication between services is covered in detail in Part 8
  • Use network policies to limit who can call whom: by default, any Pod in a Kubernetes cluster can reach any other Pod. Use a NetworkPolicy so only the sign-up service can reach the payment service, and a compromised recommendation service cannot call the payment API directly:
yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: payment-ingress
  namespace: lectures
spec:
  podSelector:
    matchLabels:
      app: payment
  policyTypes: ["Ingress"]
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: registration
      ports:
        - port: 8080

A NetworkPolicy only takes effect when the cluster’s network plugin supports it; after applying one, verify that it actually works.

  • The registry leaks your internal topology: Eureka’s dashboard and Consul’s UI list the name, address, and metadata of every service, and exposing them to the outside hands attackers a map. Allow only internal access to these interfaces and require authentication; and do not put credentials in instance metadata
  • SSRF abuses internal names: if the application sends requests to URLs that users supply, an attacker can enter http://payment.lectures.svc.cluster.local/... and have your server call the internal service for them. Restrict the destinations of outbound requests so they cannot resolve to internal names and addresses (SSRF in Part 8)

When to use it, and when not to

  • Use the platform’s built-in discovery: on Kubernetes or a managed cloud environment, this is almost always the simplest choice
  • Use a registry plus client-side load balancing: when you are not on Kubernetes, need to span several environments, or need a finer-grained load balancing strategy
  • Use a service mesh: many services, a need for consistent mTLS, retries, and traffic control, and a team able to operate the control plane
  • Do not build your own: implementing registration and heartbeats yourself on a database or Redis amounts to reinventing an Eureka that nobody has battle-tested

References

Comments