Service discovery with Eureka
When services run as many instances that come and go, callers cannot use fixed addresses. A service registry such as Eureka keeps the current list, each instance keeps its entry alive with heartbeats, and clients pick an instance by name. This page explains how Eureka's leases and caches work, works out their timing with runnable models, and shows the server and client setup for Spring Boot 4.
Contents
What a service registry does
In a system of services that scale up and down, the address of "the inventory service" is not one host and port but a changing set of instances. Service discovery answers the question "where are the instances of inventory
- The server: a registry that holds, for each service name, a list of instances with their host, port, status and metadata, and serves it over a REST API and a dashboard.
- Registration and leases: each instance registers itself at start-up and then renews its lease with a heartbeat, every 30 seconds by default. An instance whose lease is not renewed in time is evicted from the registry.
- Client-side discovery: callers fetch the registry, cache it locally, and choose an instance themselves, through Spring Cloud LoadBalancer. No request passes through Eureka; it only provides the list.
Eureka favours availability over consistency. Every server and client keeps its own copy, refreshed periodically, so the view of the registry is always slightly out of date, and Eureka keeps answering with that view even when it cannot reach instances. The consequence, worked out below, is that changes take tens of seconds to reach callers, and callers must cope with instances that have just gone away.
| Option | How instances are found | Best for |
|---|---|---|
| Eureka (Spring Cloud Netflix) | Registration with heartbeats; clients cache the registry | Spring services on VMs or in mixed environments |
| Consul (Spring Cloud Consul) | Registration with health checks; also a key-value store | Mixed-language systems, multi-datacenter setups |
| Kubernetes Services and DNS | The platform tracks pods; callers use a stable service name | Everything running on Kubernetes |
| Spring Cloud Kubernetes | Reads the Kubernetes API through DiscoveryClient | Kubernetes, when code needs the instance list itself |
On Kubernetes, a registry is usually unnecessary, because the platform already knows which pods are ready. Eureka remains common in Spring systems on virtual machines and in older installations. For Spring Boot 4.1, Spring Cloud 2025.1 includes Spring Cloud Netflix 5.0; the programs here use version 5.0.2. Two programs start a real Eureka server and several clients in one JVM, with intervals shortened to one second so that they finish quickly. Two more are plain-Java models of Eureka's timing with its documented default intervals, and one shows the Actuator health that Eureka can report. The page's classpath holds spring-cloud-starter-netflix-eureka-server
A Eureka server
The server is a Spring Boot application with one annotation and the spring-cloud-starter-netflix-eureka-server
@SpringBootApplication
@EnableEurekaServer
public class RegistryApplication {
public static void main(String[] args) {
SpringApplication.run(RegistryApplication.class, args);
}
}
server:
port: 8761
eureka:
instance:
hostname: localhost
client:
register-with-eureka: false # a single server: do not register with itself
fetch-registry: false
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
- The dashboard and the API are served under
. The key/eureka must be written in camel case:defaultZone is a map, and map keys are not converted by relaxed binding.service-url - For high availability, run two or three servers and list the others in each one's
. They replicate registrations to each other, and clients can use any of them.defaultZone - With Spring Security on the server, exempt
from CSRF protection, because Eureka clients do not send CSRF tokens; clients can then authenticate with credentials in the URL, as in/eureka/** .https://user:password@registry:8761/eureka/ - The Eureka server does not support AOT processing or native images.
- The next program starts this server with the same settings, except that the port is a free one chosen at start-up.
must match the host ineureka.instance.hostname ; otherwise the server sees its own URL as a peer and tries to replicate every registration to itself.defaultZone
Registering and finding services
With spring-cloud-starter-netflix-eureka-clientspring.application.name
spring:
application:
name: inventory
eureka:
client:
service-url:
defaultZone: http://registry-1:8761/eureka/,http://registry-2:8761/eureka/
healthcheck:
enabled: true # report Actuator health as the instance status
instance:
prefer-ip-address: true # register the IP, not a host name callers may not resolve
This program starts a registry and two services, inventoryorders@LoadBalancedRestClient.Builder
package demo.eureka.discovery;
import java.net.ServerSocket;
import java.util.List;
import java.util.stream.Stream;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClient;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
public class EurekaDiscovery {
@SpringBootConfiguration
@EnableAutoConfiguration
@EnableEurekaServer
static class RegistryApplication {
}
@RestController
static class WhoAmI {
private final String name;
WhoAmI(Environment env) {
this.name = env.getProperty("spring.application.name");
}
@GetMapping("/whoami")
String whoAmI() {
return "answered by " + name;
}
}
@SpringBootConfiguration
@EnableAutoConfiguration
@Import(WhoAmI.class)
static class ServiceApplication {
@Bean
@LoadBalanced // resolves service names through the registry
RestClient.Builder loadBalancedBuilder() {
return RestClient.builder();
}
@Bean
@Primary // for everything else, the Eureka client's own calls too
RestClient.Builder plainBuilder() {
return RestClient.builder();
}
}
public static void main(String[] args) throws Exception {
int registryPort;
try (ServerSocket socket = new ServerSocket(0)) {
registryPort = socket.getLocalPort(); // a free port, chosen up front
}
String registryUrl = "http://localhost:" + registryPort + "/eureka/";
String[] quiet = {"--spring.main.banner-mode=off", "--logging.level.root=WARN",
"--logging.level.org.springframework.cloud.loadbalancer=ERROR",
"--logging.level.com.netflix=ERROR"};
try (var registry = new SpringApplication(RegistryApplication.class).run(concat(quiet,
"--server.port=" + registryPort,
"--eureka.instance.hostname=localhost", // matches defaultZone: no peer
"--eureka.client.register-with-eureka=false",
"--eureka.client.fetch-registry=false",
"--eureka.client.service-url.defaultZone=" + registryUrl,
"--eureka.server.response-cache-update-interval-ms=500"))) {
String[] client = concat(quiet, "--server.port=0",
"--eureka.client.service-url.defaultZone=" + registryUrl,
"--eureka.client.jersey.enabled=false", // use RestClient, see below
"--eureka.instance.hostname=localhost",
"--eureka.instance.lease-renewal-interval-in-seconds=1",
"--eureka.client.registry-fetch-interval-seconds=1",
"--spring.cloud.loadbalancer.cache.enabled=false");
try (var inventory = start(client, "inventory");
var orders = start(client, "orders")) {
waitForServices(orders, 2);
waitForServices(inventory, 2);
for (var app : List.of(orders, inventory)) {
String me = app.getEnvironment().getProperty("spring.application.name");
DiscoveryClient discovery = app.getBean(DiscoveryClient.class);
System.out.println(me + " knows the services " + discovery.getServices());
}
ServiceInstance found = orders.getBean(DiscoveryClient.class)
.getInstances("inventory").get(0);
System.out.println("inventory instance: id=" + found.getInstanceId()
+ " host=" + found.getHost() + " port matches="
+ (found.getPort() == port(inventory)));
RestClient fromOrders = orders.getBean("loadBalancedBuilder",
RestClient.Builder.class).build();
RestClient fromInventory = inventory.getBean("loadBalancedBuilder",
RestClient.Builder.class).build();
System.out.println("orders GET http://inventory/whoami -> "
+ fromOrders.get().uri("http://inventory/whoami")
.retrieve().body(String.class));
System.out.println("inventory GET http://orders/whoami -> "
+ fromInventory.get().uri("http://orders/whoami")
.retrieve().body(String.class));
String json = RestClient.create().get()
.uri("http://localhost:" + port(registry) + "/eureka/apps")
.header("Accept", "application/json")
.retrieve().body(String.class);
System.out.println("The registry's GET /eureka/apps:");
JsonNode apps = JsonMapper.builder().build().readTree(json)
.path("applications").path("application");
for (JsonNode app : apps) {
for (JsonNode instance : app.path("instance")) {
System.out.println(" " + app.path("name").asString()
+ " status=" + instance.path("status").asString()
+ " renewal every "
+ instance.path("leaseInfo").path("renewalIntervalInSecs")
+ "s, lease " + instance.path("leaseInfo")
.path("durationInSecs") + "s");
}
}
}
}
}
static ConfigurableApplicationContext start(String[] common, String name) {
return new SpringApplication(ServiceApplication.class).run(
concat(common, "--spring.application.name=" + name,
"--eureka.instance.instance-id=" + name + "-1"));
}
static void waitForServices(ConfigurableApplicationContext app, int count)
throws Exception {
DiscoveryClient discovery = app.getBean(DiscoveryClient.class);
for (int i = 0; i < 120 && discovery.getServices().size() < count; i++) {
Thread.sleep(250);
}
}
static int port(ConfigurableApplicationContext app) {
return Integer.parseInt(app.getEnvironment().getProperty("local.server.port"));
}
static String[] concat(String[] first, String... more) {
return Stream.concat(Stream.of(first), Stream.of(more)).toArray(String[]::new);
}
}
orders knows the services [inventory, orders]
inventory knows the services [inventory, orders]
inventory instance: id=inventory-1 host=localhost port matches=true
orders GET http://inventory/whoami -> answered by inventory
inventory GET http://orders/whoami -> answered by orders
The registry's GET /eureka/apps:
INVENTORY status=UP renewal every 1s, lease 90s
ORDERS status=UP renewal every 1s, lease 90s
- Both services listed
, themselves included. Each client fetches the whole registry, here every second instead of the default 30 seconds, and answers[inventory, orders] calls from its local copy.DiscoveryClient - The
instance had the IDinventory set in the program, the hostinventory-1 , and the port its Tomcat had actually chosen. Eureka registers the real port after the web server starts, solocalhost works.server.port=0 fromhttp://inventory/whoami reachedorders , andinventory went the other way. The host part of each URL was a service name, which the load balancer replaced with a registered instance.http://orders/whoami- The registry's own API,
, listed both applications in upper case with statusGET /eureka/apps . Each renews its lease every second, as configured, and the lease would expire after the default 90 seconds without renewals.UP
Several settings in the program are there because everything runs in one JVM:
- Two builder beans: the Eureka client sends its own heartbeats with a
from the context. In a first version whose only builder bean was theRestClient.Builder one, the client treated@LoadBalanced in the registry URL as a service name, found no such service and could not register. Thelocalhost plain builder keeps the load balancer out of the client's own calls.@Primary - No Jersey: the server starter brings Jersey, and with Jersey on the classpath the client applications expected a Jersey transport that they had not configured, and failed to start.
makes them useeureka.client.jersey.enabled=false . A client application without the server jar does not need the setting.RestClient - Short intervals: renewals, registry fetches and the server's response cache are set to one second or less, and the load balancer's cache is off. With the defaults, the two services could take more than a minute and a half to see each other, as the timeline below shows.
- Quieter logs: the
and load balancer loggers are set tocom.netflix . With one-second intervals and shutdown in the middle of a fetch, they print warnings that do not matter here.ERROR
Two more points about the client:
- To read the list directly, inject Spring Cloud's
and callDiscoveryClient , as the program does. It works the same with Eureka, Consul or Kubernetes, unlike Netflix's owngetInstances("inventory") .EurekaClient - The default instance ID is host name, application name and port, such as
. Withhost1:inventory:8080 the ID contains the configured port, 0, for every instance, so setserver.port=0 to something unique, as the program does.eureka.instance.instance-id
How long changes take to reach callers
A registry entry passes through several caches before a caller uses it: the server's lease, the server's response cache, each client's copy of the registry, and the load balancer's cache. This model adds up the documented default intervals for the three events that matter, a crash, a start and a clean shutdown:
// A plain-Java model of Eureka's lease timings, using the documented default intervals.
// It is NOT Eureka; it computes how long each cache in the chain can delay a change.
public class LeaseTimeline {
// eureka.instance.lease-renewal-interval-in-seconds
static final int HEARTBEAT = 30;
// eureka.instance.lease-expiration-duration-in-seconds
static final int LEASE_EXPIRY = 90;
static final int EVICTION_TIMER = 60; // eureka.server.eviction-interval-timer-in-ms / 1000
static final int RESPONSE_CACHE = 30; // eureka.server.response-cache-update-interval-ms
static final int CLIENT_FETCH = 30; // eureka.client.registry-fetch-interval-seconds
static final int LB_CACHE = 35; // spring.cloud.loadbalancer.cache.ttl
public static void main(String[] args) {
System.out.println("An instance crashes without deregistering, at t=0:");
int lastHeartbeat = 0;
int expiresAt = lastHeartbeat + LEASE_EXPIRY;
System.out.println(" lease expires t=" + expiresAt + "s (last heartbeat + "
+ LEASE_EXPIRY + "s)");
int evictedBy = expiresAt + EVICTION_TIMER;
System.out.println(" evicted by the server t<=" + evictedBy
+ "s (eviction task runs every " + EVICTION_TIMER + "s)");
int worst = evictedBy + RESPONSE_CACHE + CLIENT_FETCH + LB_CACHE;
System.out.println(" callers stop using it t<=" + worst
+ "s (+ response cache, client fetch, load-balancer cache)");
System.out.println("A new instance starts and registers at t=0:");
int visible = RESPONSE_CACHE + CLIENT_FETCH + LB_CACHE;
System.out.println(" callers can find it t<=" + visible + "s");
System.out.println("An instance shuts down cleanly and deregisters at t=0:");
System.out.println(" callers stop using it t<=" + visible
+ "s (no lease expiry or eviction wait)");
System.out.println("Requests sent to the crashed instance in the worst case, at 50 req/s"
+ " spread over 5 instances: about " + (worst * 50 / 5));
}
}
An instance crashes without deregistering, at t=0:
lease expires t=90s (last heartbeat + 90s)
evicted by the server t<=150s (eviction task runs every 60s)
callers stop using it t<=245s (+ response cache, client fetch, load-balancer cache)
A new instance starts and registers at t=0:
callers can find it t<=95s
An instance shuts down cleanly and deregisters at t=0:
callers stop using it t<=95s (no lease expiry or eviction wait)
Requests sent to the crashed instance in the worst case, at 50 req/s spread over 5 instances: about 2450
- A crashed instance stops sending heartbeats. Its lease expires 90 seconds after the last one, but the server only removes expired leases when its eviction task runs, once a minute, so removal can take until 150 seconds.
- Then the change still has to pass the server's 30-second response cache, the clients' 30-second registry fetch and the load balancer's 35-second cache. In the worst case, callers keep choosing the dead instance for about 245 seconds, four minutes.
- With 50 requests per second spread over 5 instances, that is about 2,450 requests sent to an instance that no longer exists. Each fails with a connection error, unless the client retries on another instance.
- A new instance, or one that deregisters cleanly on shutdown, skips the lease wait: callers see the change within about 95 seconds.
The numbers are a model of the default settings, not a measurement, but they explain the two practical rules. Shut instances down gracefully, so that they deregister instead of letting their lease expire; Spring Boot's graceful shutdown and the Eureka client do that on a normal stop. And configure callers to retry a failed request on another instance, since stale entries are part of the design. Shortening the intervals helps in tests, but the Spring Cloud documentation recommends keeping the 30-second heartbeat in production, because the server's calculations assume it.
Self-preservation
If many instances stop renewing at once, the likely cause is a network problem between them and the server, not that they all crashed. Evicting them would remove healthy services from every caller's list. So the server counts the renewals it received in the last minute and compares them with what it expects; below 85% of the expected number, it stops evicting. This model applies that rule to several situations:
// A plain-Java model of Eureka's self-preservation check, with the documented defaults.
// It is NOT Eureka; it shows the arithmetic the server applies every minute.
public class SelfPreservation {
static final int HEARTBEAT_SECONDS = 30; // each instance renews twice a minute
static final double THRESHOLD = 0.85; // eureka.server.renewal-percent-threshold
static void check(String label, int instances, int renewalsLastMinute) {
int expected = instances * (60 / HEARTBEAT_SECONDS);
int threshold = (int) (expected * THRESHOLD);
boolean preserving = renewalsLastMinute < threshold;
System.out.printf("%-34s expected %3d, threshold %3d, received %3d -> %s%n", label,
expected, threshold, renewalsLastMinute,
preserving ? "SELF-PRESERVATION: expired leases are kept"
: "normal: expired leases are evicted");
}
public static void main(String[] args) {
check("20 instances, all healthy", 20, 40);
check("20 instances, 1 crashed", 20, 38);
check("20 instances, 4 crashed at once", 20, 32);
check("20 instances, network split hides 8", 20, 24);
check("2 instances, 1 crashed", 2, 2);
}
}
20 instances, all healthy expected 40, threshold 34, received 40 -> normal: expired leases are evicted
20 instances, 1 crashed expected 40, threshold 34, received 38 -> normal: expired leases are evicted
20 instances, 4 crashed at once expected 40, threshold 34, received 32 -> SELF-PRESERVATION: expired leases are kept
20 instances, network split hides 8 expected 40, threshold 34, received 24 -> SELF-PRESERVATION: expired leases are kept
2 instances, 1 crashed expected 4, threshold 3, received 2 -> SELF-PRESERVATION: expired leases are kept
- 20 instances renewing every 30 seconds should send 40 renewals a minute, and the threshold is 85% of that, 34.
- One crashed instance lowered the count to 38, still above 34, so its lease expired and it was evicted as normal.
- Four instances failing together, or a network split hiding eight, dropped the count below 34. The server entered self-preservation and kept all leases, including those of instances that may really be gone.
- With only 2 instances, losing one already halves the renewals, so a small development setup enters self-preservation almost at once.
The last case is why the Eureka dashboard of a developer's laptop so often shows a red warning that instances may be incorrectly claimed as up. It is harmless there. In production, self-preservation is the right default, and it is one more reason why callers must handle failed requests to listed instances. eureka.server.enable-self-preservation=false
Reporting health instead of only liveness
A heartbeat only proves that the process runs. An instance whose database is unreachable keeps renewing its lease, and keeps receiving requests it cannot serve. With eureka.client.healthcheck.enabled=trueDOWNDOWN
package demo.eureka.health;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.atomic.AtomicBoolean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.health.contributor.Health;
import org.springframework.boot.health.contributor.HealthIndicator;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.annotation.Bean;
public class HealthStatus {
static final AtomicBoolean DATABASE_UP = new AtomicBoolean(true);
@SpringBootApplication
static class OrdersApplication {
@Bean
HealthIndicator database() {
return () -> DATABASE_UP.get() ? Health.up().build()
: Health.down().withDetail("error", "connection refused").build();
}
}
public static void main(String[] args) throws Exception {
try (var context = SpringApplication.run(OrdersApplication.class, "--server.port=0",
"--spring.main.banner-mode=off", "--logging.level.root=WARN",
// this program needs neither the Eureka client nor the load balancer
"--eureka.client.enabled=false", "--spring.cloud.loadbalancer.enabled=false")) {
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
HttpClient http = HttpClient.newHttpClient();
HttpRequest health = HttpRequest.newBuilder(
URI.create("http://localhost:" + port + "/actuator/health")).build();
System.out.println("Database up: " + http.send(health,
HttpResponse.BodyHandlers.ofString()).body());
DATABASE_UP.set(false);
HttpResponse<String> down = http.send(health, HttpResponse.BodyHandlers.ofString());
System.out.println("Database down: " + down.statusCode() + " " + down.body());
}
}
}
Database up: {"groups":["liveness","readiness"],"status":"UP"}
Database down: 503 {"groups":["liveness","readiness"],"status":"DOWN"}
- While the database indicator was up, the overall health was
, with HTTP 200.UP - When it went down, the overall status became
and the endpoint answered 503.DOWN
The next program sends that status to a real registry. It starts two inventoryorders
package demo.eureka.healthcheck;
import java.net.ServerSocket;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.health.contributor.Health;
import org.springframework.boot.health.contributor.HealthIndicator;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClient;
public class EurekaHealthCheck {
@SpringBootConfiguration
@EnableAutoConfiguration
@EnableEurekaServer
static class RegistryApplication {
}
@RestController
static class WhoAmI {
private final String id;
WhoAmI(Environment env) {
this.id = env.getProperty("eureka.instance.instance-id");
}
@GetMapping("/whoami")
String whoAmI() {
return id;
}
}
@SpringBootConfiguration
@EnableAutoConfiguration
@Import(WhoAmI.class)
static class ServiceApplication {
final AtomicBoolean databaseUp = new AtomicBoolean(true);
@Bean
HealthIndicator database() {
return () -> databaseUp.get() ? Health.up().build() : Health.down().build();
}
@Bean
@LoadBalanced
RestClient.Builder loadBalancedBuilder() {
return RestClient.builder();
}
@Bean
@Primary
RestClient.Builder plainBuilder() {
return RestClient.builder();
}
}
public static void main(String[] args) throws Exception {
int registryPort;
try (ServerSocket socket = new ServerSocket(0)) {
registryPort = socket.getLocalPort();
}
String registryUrl = "http://localhost:" + registryPort + "/eureka/";
String[] quiet = {"--spring.main.banner-mode=off", "--logging.level.root=WARN",
"--logging.level.org.springframework.cloud.loadbalancer=ERROR",
"--logging.level.com.netflix=ERROR"};
try (var registry = new SpringApplication(RegistryApplication.class).run(concat(quiet,
"--server.port=" + registryPort, "--eureka.instance.hostname=localhost",
"--eureka.client.register-with-eureka=false",
"--eureka.client.fetch-registry=false",
"--eureka.client.service-url.defaultZone=" + registryUrl,
"--eureka.server.response-cache-update-interval-ms=500"))) {
System.out.println("registry running: " + registry.isRunning());
String[] client = concat(quiet, "--server.port=0",
"--eureka.client.service-url.defaultZone=" + registryUrl,
"--eureka.client.jersey.enabled=false",
"--eureka.instance.hostname=localhost",
"--eureka.instance.lease-renewal-interval-in-seconds=1",
"--eureka.client.registry-fetch-interval-seconds=1",
"--eureka.client.instance-info-replication-interval-seconds=1",
"--eureka.client.healthcheck.enabled=true", // report Actuator health
"--spring.cloud.loadbalancer.cache.enabled=false");
var inventory1 = start(client, "inventory", "inventory-1");
try (var inventory2 = start(client, "inventory", "inventory-2");
var orders = start(client, "orders", "orders-1")) {
DiscoveryClient discovery = orders.getBean(DiscoveryClient.class);
RestClient rest = orders.getBean("loadBalancedBuilder", RestClient.Builder.class)
.baseUrl("http://inventory").build();
waitForInstances(discovery, 2);
System.out.println("both instances UP: " + ids(discovery)
+ " -> calls answered by " + call(rest, 4));
inventory2.getBean(ServiceApplication.class).databaseUp.set(false);
waitForInstances(discovery, 1);
System.out.println("inventory-2 health DOWN: " + ids(discovery)
+ " -> calls answered by " + call(rest, 4));
inventory2.getBean(ServiceApplication.class).databaseUp.set(true);
waitForInstances(discovery, 2);
System.out.println("inventory-2 UP again: " + ids(discovery)
+ " -> calls answered by " + call(rest, 4));
inventory1.close(); // a clean shutdown deregisters
waitForInstances(discovery, 1);
System.out.println("inventory-1 shut down: " + ids(discovery)
+ " -> calls answered by " + call(rest, 4));
}
}
}
static List<String> ids(DiscoveryClient discovery) {
return discovery.getInstances("inventory").stream()
.map(i -> i.getInstanceId()).sorted().toList();
}
// round-robin starts at a random position, so count the answers per instance
static Map<String, Integer> call(RestClient rest, int times) {
Map<String, Integer> answers = new TreeMap<>();
for (int i = 0; i < times; i++) {
answers.merge(rest.get().uri("/whoami").retrieve().body(String.class), 1,
Integer::sum);
}
return answers;
}
static void waitForInstances(DiscoveryClient discovery, int count) throws Exception {
for (int i = 0; i < 200 && discovery.getInstances("inventory").size() != count; i++) {
Thread.sleep(250);
}
}
static ConfigurableApplicationContext start(String[] common, String name, String id) {
return new SpringApplication(ServiceApplication.class).run(concat(common,
"--spring.application.name=" + name, "--eureka.instance.instance-id=" + id));
}
static String[] concat(String[] first, String... more) {
return Stream.concat(Stream.of(first), Stream.of(more)).toArray(String[]::new);
}
}
registry running: true
both instances UP: [inventory-1, inventory-2] -> calls answered by {inventory-1=2, inventory-2=2}
inventory-2 health DOWN: [inventory-1] -> calls answered by {inventory-1=4}
inventory-2 UP again: [inventory-1, inventory-2] -> calls answered by {inventory-1=2, inventory-2=2}
inventory-1 shut down: [inventory-2] -> calls answered by {inventory-2=4}
- The first line only confirms that the registry started before the clients.
- With both instances
, the round-robin load balancer split the four calls two and two. It starts at a random position, which is why the program counts the answers instead of printing their order.UP - When the database indicator of
went down, its status in the registry becameinventory-2 .DOWN inDiscoveryClient then returned onlyorders , which answered all four calls, althoughinventory-1 was still running and renewing its lease.inventory-2 - When the indicator came back,
was listed again and received half the calls.inventory-2 - Closing
cleanly sent a cancel request to the registry, andinventory-1 answered everything. No lease had to expire for that.inventory-2
The status reaches the registry with the client's instance-info update, every 30 seconds by default and every second here through eureka.client.instance-info-replication-interval-seconds=1DOWN
Choose the indicators carefully. If every instance shares one database and it fails, all instances report DOWNapplication.ymlbootstrap.ymlUNKNOWN
Common problems
- Wrong address registered: in containers, the host name an instance sees may not be resolvable by callers. Use
, or setprefer-ip-address: true explicitly.eureka.instance.hostname - Slow registration in tests: as the timeline shows, a new instance can take more than a minute to be found. Integration tests that start a service and call it at once should use a fixed address, or shorter intervals in the test profile, as the two programs with a registry do.
- Refresh unregisters: the Eureka client is refreshable by default, and a configuration refresh briefly unregisters it. If that causes gaps, set
.eureka.client.refresh.enable=false - Early lookups: the Eureka client starts as a lifecycle bean, so lookups in
methods can find an empty registry.@PostConstruct - Registry as a single point of failure: clients keep using their cached copy when the server is down, but new instances cannot register. Run at least two servers.
Choosing a discovery approach
| Situation | Choice |
|---|---|
| Spring services on virtual machines | Eureka with two or more servers |
| Services in several languages | Consul, or the platform's own discovery |
| Everything on Kubernetes | Kubernetes Services and DNS, with no registry |
| Calls by service name from Spring code | @LoadBalancedRestClient.BuilderDiscoveryClient |
| Instances that must leave the list when unhealthy | eureka.client.healthcheck.enabled=true |
| Fast reaction to crashed instances | Retries on another instance; do not rely on the registry alone |
A registry tells callers where services probably are. Combine it with timeouts and retries on the client side, as on the