Skip to content
Tutorials Center
My learning

Topics

Lesson 103 of 119 ยท Spring Cloud

Service Discovery with Eureka

Learn how services find each other - client-side and server-side discovery, Eureka server and clients, heartbeats, leases, self-preservation and Kubernetes DNS.

In a monolith, one part of the code reaches another with a method call. In a microservice system, the loan service has to reach the catalog service over the network, so it needs an address: a host and a port. Writing http://10.0.4.17:8080 into a properties file works on day one. It breaks the first time the catalog runs three instances instead of one, moves to another machine, or restarts with a new IP address in a container.

Service discovery solves this. Every running instance announces itself to a service registry under a logical name such as catalog-service. Callers ask the registry "where is catalog-service right now?" and get a live list of instances. The registry also notices when an instance disappears, so callers stop sending it traffic.

Microservices introduced discovery in one paragraph and one map. This lesson goes deeper: the two discovery styles, how registration, heartbeats and leases work, why a registry sometimes refuses to remove dead instances on purpose, and how Spring Cloud Netflix Eureka implements all of it. Our Java runner has no Spring Cloud, so every runnable example is a small plain-Java version of the mechanism (some over real HTTP on 127.0.0.1), and the real Eureka code is shown read-only.

Why static addresses fail

Three things make hard-coded addresses unworkable:

  • Scaling. Under load you start five catalog instances; at night you scale back to two. Every caller would need a config change each time.
  • Failures and restarts. Containers and cloud VMs get new IP addresses when they are rescheduled. A crashed instance should stop receiving traffic within seconds, not after someone edits a file.
  • Ephemeral ports. For local development and dense hosting, services often start with server.port=0, letting the operating system pick a free port. Nobody knows that port in advance except the service itself.

A registry turns "address" into a runtime fact that the instance itself reports. Here is the data model at its simplest: a map from service name to the instances currently registered.

Java A service registry as a data structure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Callers never stored 10.0.4.23; they asked again and got the new address. An unknown service returns an empty list, which a caller must treat as "unavailable", not as a bug.

Client-side and server-side discovery

There are two ways to use the registry's answer.

Client-side discovery Server-side discovery
Who asks the registry The calling service (through a library) A router or load balancer in front of the services
Who picks an instance The caller's load balancer The router
Caller knows about instances Yes, it has the list No, it only knows one stable address
Extra network hop No Yes, through the router
Language support Needs a client library per language Any client that speaks HTTP
Examples Eureka + Spring Cloud LoadBalancer, Consul with a client library Kubernetes Service, AWS load balancers, a gateway with lb:// routes

Eureka is the classic client-side design: each Spring service downloads the registry, caches it, and picks an instance itself (the next lesson, Load Balancing and OpenFeign, covers the picking). Kubernetes is server-side: you call http://catalog-service, DNS resolves it to a virtual IP, and the platform forwards the connection to a healthy pod.

Registration also comes in two styles. In self-registration, the instance calls the registry when it starts (Eureka). In third-party registration, a platform component watches deployments and registers instances for them (Kubernetes, or a Consul agent next to each process).

Registration over HTTP

A registry is itself a small web service. Eureka's REST API looks roughly like this: POST /eureka/apps/{app} registers an instance, PUT /eureka/apps/{app}/{instanceId} renews it (a heartbeat), DELETE /eureka/apps/{app}/{instanceId} removes it, and GET /eureka/apps returns the whole registry.

The next program builds that idea for real inside one JVM. A registry server runs on one port. Two catalog instances start on OS-assigned ports (port 0), so the only way to find them is through the registry. The loan service looks the catalog up by name, calls every instance, and then one catalog instance shuts down gracefully by deregistering first.

Java Self-registration over HTTP with OS-assigned ports

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The loan service never saw a port number in its own code; it learned the addresses from the registry at runtime. Notice the order in the graceful shutdown: deregister, then stop. If the instance stopped first, callers would keep getting its address and see connection errors until the registry found out some other way. Spring Cloud does this for you: the Eureka client deregisters when the application context closes.

Heartbeats and leases

Graceful shutdown is the easy case. A process killed with kill -9, a crashed JVM or a lost network link never says goodbye. Registries handle this with leases: a registration is valid only for a limited time, and the instance must keep renewing it by sending heartbeats. An eviction task periodically removes instances whose lease has expired.

Eureka's defaults are a heartbeat every 30 seconds (eureka.instance.lease-renewal-interval-in-seconds), a lease of 90 seconds (lease-expiration-duration-in-seconds), and an eviction run every 60 seconds (eureka.server.eviction-interval-timer-in-ms). The demo below uses those numbers with a simulated clock, so a few minutes pass instantly and the output is the same every run. It also shows a detail that matters in practice: when the registry receives a heartbeat for an instance it doesn't know, it answers "404, not found", and the client responds by registering again. That is how instances recover after the registry itself restarts with an empty memory.

Java Leases, heartbeats and eviction with a simulated clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

catalog-2 crashed at 45 seconds, its last heartbeat was at 30, and it was only removed at 180 seconds: the lease was only more than 90 seconds old after 120, and the next eviction run came at 180. For more than two minutes, callers could still be handed a dead address. This is normal for any lease-based registry, and it's why discovery alone isn't enough: callers also need timeouts, retries on another instance and circuit breakers (Circuit Breakers and Resilience).

You can shorten the intervals, but every instance then sends more heartbeats and the registry does more work. In practice teams keep the defaults (or lower them modestly) and rely on client-side retries to cover the gap.

Self-preservation: when the registry refuses to evict

Imagine a network glitch between the registry and half of your instances. The instances are fine and serving traffic, but their heartbeats don't arrive. A naive registry would evict them all and tell every caller that half the system is gone, turning a small network problem into a big outage.

Eureka guards against this with self-preservation mode. It knows how many renewals it should receive per minute (two per instance with the 30-second default). If the actual number falls below a threshold, by default 85% of the expected count (eureka.server.renewal-percent-threshold: 0.85), it assumes the network is the problem, not the instances, and stops evicting until renewals recover. The Eureka dashboard shows a red warning while this mode is on.

The simulation compares two incidents with ten registered instances: one instance really crashes, and later a partition hides six of them.

Java Self-preservation mode with ten instances

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

With one crash, 18 renewals arrive, which is at least 17, so the dead instance is evicted normally. With six silent instances, only 8 arrive, and Eureka keeps everyone. The trade-off is deliberate: Eureka prefers availability over consistency (in CAP terms, an AP system). It would rather hand out a few stale addresses, which callers survive with retries, than wipe out healthy ones.

Self-preservation surprises people in development. You stop a service on your laptop, it stays listed, and the dashboard shows the warning, because with only one or two instances the threshold math is unstable. Turning it off locally (eureka.server.enable-self-preservation: false) is common; keep it on in production.

Clients cache the registry

Asking the registry before every call would make it a bottleneck and a single point of failure. Eureka clients therefore download the registry, keep a local cache, and refresh it every 30 seconds (eureka.client.registry-fetch-interval-seconds), fetching only the changes after the first full download. Spring Cloud LoadBalancer adds its own short-lived cache on top.

The consequence is pleasant and unpleasant at the same time. The registry can go down completely and calls keep working from the cache. But the cache can be stale, so a caller may pick an instance that is already gone, and must try another one:

Java A client-side registry cache that survives a registry outage

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Request 1 succeeded although the registry was down. Request 4 started at the dead catalog-2 and recovered by trying the next instance. That retry-on-another-instance behavior is exactly what Spring Cloud LoadBalancer's retry support provides, as you'll see in the next lesson.

Eureka with Spring Cloud

Now the real thing. Spring Cloud Netflix Eureka has two parts: a server (the registry, with a web dashboard) and a client that every service includes. Versions come from the Spring Cloud release train (2025.1 "Oakwood" pairs with Spring Boot 4; check the current release train) through the spring-cloud-dependencies BOM, so you don't write version numbers on individual starters.

The Eureka server

The server is an ordinary Spring Boot application with one extra starter and one annotation:

XML
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
Java
@SpringBootApplication
@EnableEurekaServer
public class DiscoveryServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(DiscoveryServerApplication.class, args);
    }
}
YAML
server:
  port: 8761                       # the conventional Eureka port

eureka:
  client:
    register-with-eureka: false    # a standalone server shouldn't list itself
    fetch-registry: false
  server:
    enable-self-preservation: true # turn off only for local development

Open http://localhost:8761 and you get the dashboard: registered applications, their instances and status, and the self-preservation warning when it's active. The REST API lives under /eureka/apps.

For production, run two or three Eureka servers as peers. Each one is configured with the others' URLs in eureka.client.service-url.defaultZone (and registers with them), and they replicate registrations to each other. Replication is asynchronous, which fits Eureka's availability-first design: peers can briefly disagree.

Eureka clients

A service becomes a client by adding spring-cloud-starter-netflix-eureka-client. No annotation is needed: when the starter is on the classpath, the service registers on startup, renews every 30 seconds and deregisters on shutdown. (@EnableDiscoveryClient is optional in current versions.)

YAML
spring:
  application:
    name: catalog-service          # the logical name others look up

server:
  port: 0                          # let the OS choose; the registry knows the real port

eureka:
  client:
    service-url:
      defaultZone: http://eureka-1:8761/eureka/,http://eureka-2:8761/eureka/
  instance:
    prefer-ip-address: true        # register the IP instead of the host name
    instance-id: ${spring.application.name}:${random.value}   # unique even when ports collide
    lease-renewal-interval-in-seconds: 30
    lease-expiration-duration-in-seconds: 90

With server.port: 0, set a unique instance-id, as above. The default id includes the configured port, which would be 0 for every instance, so the instances would overwrite each other in the registry.

By default an instance reports itself UP as long as it sends heartbeats, even if its database is unreachable. Add Spring Boot Actuator and set eureka.client.healthcheck.enabled: true, and the client reports the status from the application's health endpoint instead, so a service whose health is DOWN is taken out of rotation (Actuator, Metrics and Observability explains health indicators).

Looking services up in code

Most of the time you never look up instances by hand: a lb://catalog-service URI or a load-balanced client does it (next lesson). When you do need the list, Spring Cloud's portable DiscoveryClient interface works with Eureka, Consul and Kubernetes alike:

Java
@RestController
class InstancesController {

    private final DiscoveryClient discoveryClient;

    InstancesController(DiscoveryClient discoveryClient) {
        this.discoveryClient = discoveryClient;
    }

    @GetMapping("/debug/instances/{service}")
    List<String> instances(@PathVariable String service) {
        return discoveryClient.getInstances(service).stream()
                .map(instance -> instance.getInstanceId() + " " + instance.getUri())
                .toList();
    }
}

getServices() returns all known service names. Because the data comes from the local cache, both calls are cheap.

Alternatives: Kubernetes DNS and Consul

If your services run on Kubernetes, you usually don't need Eureka. The platform already does server-side discovery: a Service object gives a set of pods a stable name, cluster DNS resolves it, and traffic is spread across pods that pass their readiness probe. Registration and health checking are done by the platform, not by your code:

YAML
apiVersion: v1
kind: Service
metadata:
  name: catalog-service
spec:
  selector:
    app: catalog            # every ready pod with this label receives traffic
  ports:
    - port: 80
      targetPort: 8080

The loan service then simply calls http://catalog-service (or http://catalog-service.library.svc.cluster.local from another namespace). Spring Cloud Kubernetes can additionally expose pods through the same DiscoveryClient interface if you want client-side load balancing on Kubernetes, but many teams don't need it. Deploying Java Applications covers the Kubernetes objects.

HashiCorp Consul is the other common registry. It runs active health checks itself (calling each instance's health URL) instead of relying only on heartbeats, adds a key-value store for configuration, and works with any language. Spring Cloud Consul plugs into the same DiscoveryClient abstraction.

Two older building blocks are also used as registries. Apache ZooKeeper is a coordination service (the historical home of Kafka's metadata and of Dubbo-style RPC registries); services register ephemeral nodes that vanish when the session ends, and Spring Cloud Zookeeper plugs it into DiscoveryClient. etcd is the consistent key-value store behind Kubernetes itself; services can register keys with a lease (a time-to-live that they keep renewing), which is the same lease idea as Eureka's heartbeats, but you build or borrow the discovery layer yourself. Both choose consistency over availability, which makes them excellent for coordination and leader election, and heavier than Eureka for a plain service list.

Eureka Consul Kubernetes Service
Discovery style Client-side Client-side or DNS Server-side (DNS + virtual IP)
Health information Heartbeats (optionally health endpoint) Active health checks Readiness probes
Consistency choice Availability first (AP) Consistent core (Raft) Platform-managed
Best fit Spring services on VMs Mixed languages, VMs + containers Anything running on Kubernetes

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Two catalog instances start with server.port=0 and Eureka's default instance id. What goes wrong?

    The default id contains the configured port. With port 0 that part is identical, so set a unique eureka.instance.instance-id such as name plus a random value.
  2. 2. With Eureka's defaults (heartbeat 30 s, lease 90 s, eviction every 60 s), an instance crashes right after a heartbeat. What is true?

    The lease must expire and then an eviction run must happen. In the lesson's demo the instance was removed 150 seconds after its last heartbeat.
  3. 3. A registry with 10 instances suddenly receives only 8 renewals per minute instead of 20. What does Eureka do with self-preservation on?

    8 is below 85% of 20 (17), so Eureka enters self-preservation and keeps all registrations until renewals recover.
  4. 4. The Eureka server goes down for five minutes. What happens to calls between services that use Eureka clients?

    Clients cache the registry and refresh it every 30 seconds. A failed refresh keeps the old data, so discovery degrades gracefully.
  5. 5. Why do many teams on Kubernetes skip Eureka?

    The platform registers pods, checks readiness and load-balances a stable service name, which covers what Eureka would do.

Summary

  • Service discovery replaces hard-coded addresses with a registry that maps logical names (catalog-service) to live instances.
  • Client-side discovery (Eureka) lets callers fetch the instance list and choose; server-side discovery (Kubernetes Services, load balancers) hides instances behind one stable address.
  • Instances self-register, renew a lease with heartbeats (30 s by default) and deregister on graceful shutdown; expired leases are evicted (90 s lease, eviction every 60 s), so dead instances can linger for minutes.
  • A heartbeat answered with 404 makes the client register again, which is how instances recover after a registry restart.
  • Self-preservation stops eviction when renewals drop below 85% of the expected rate: Eureka chooses availability over consistency.
  • Clients cache the registry, so calls survive a registry outage, but must retry on another instance when the cache is stale.
  • In Spring Cloud: @EnableEurekaServer plus the server starter for the registry; the client starter, spring.application.name and eureka.client.service-url.defaultZone for services; DiscoveryClient for lookups. On Kubernetes, the platform's DNS-based discovery usually replaces Eureka.

Next: Load Balancing and OpenFeign