Service Discovery — Eureka
Eureka Server and Client setup, self-registration, heartbeat, service registry
- Stand up a Eureka Server and register multiple service instances
- Configure Eureka Client heartbeat and lease expiry
- Fetch service instances from the registry for dynamic routing
Table of Contents
- The Problem — Why We Can't Hardcode URLs in Microservices
- What is Service Discovery?
- Eureka — Netflix's Service Discovery Solution
- Setting Up the Eureka Server
- Setting Up Eureka Clients (Microservices)
- Invoking Services Using Service Discovery
- Deep Dive — How Eureka Server Knows If a Client Is Up or Down
- How Eureka Server Stores Data
- High Availability — Eureka Server Cluster
- Client-Side Caching — Solving the Latency Problem
- Complete Configuration Reference
- Common Mistakes
- Best Practices
- Interview Notes
- Summary
- Practice Questions
1. The Problem Why We Can't Hardcode URLs in Microservices
The Hardcoded URL Approach
In basic microservices tutorials, inter-service calls are made by hardcoding the target service URL:
1// OrderService calling ProductService — the naive approach2RestTemplate restTemplate = new RestTemplate();3String response = restTemplate.getForObject(4 "http://localhost:8081/api/products/123", // ← HARDCODED URL5 String.class6);This works fine when you have exactly one instance of each service running locally. But it breaks completely in production.
Why It Fails in Production
Problem 1: Single Point of Failure
If the hardcoded instance goes down, the order service cannot reach any of the other running instances — even though they are healthy and available.
Problem 2: No Load Balancing
1OrderService always calls Instance 1 (hardcoded)2 → Instance 1: 100% load 🔥3 → Instance 2: 0% load 😴4 → Instance 3: 0% load 😴Even with multiple healthy instances running, all traffic goes to the hardcoded one. The other instances sit completely idle.
Problem 3: Tight Coupling
If the product service's IP or port changes (due to migration, containerization, or scaling), you must:
- Stop order service
- Update the hardcoded URL
- Redeploy order service
- Only THEN migrate product service
The two services are now operationally coupled, defeating the purpose of microservices independence.
Problem 4: Environment-Specific Configuration Nightmare
| Environment | Product Service URL |
|---|---|
| Local Dev | http://localhost:8081 |
| Dev Server | http://dev-server-ip:8081 |
| QA | http://qa-server-ip:8081 |
| Production | http://prod-cluster-ip:8081 |
Every environment requires code or config changes. This is error-prone and violates the "build once, deploy anywhere" principle.
Summary of Hardcoded URL Problems
| Problem | Impact |
|---|---|
| Single point of failure | One instance down = entire service unreachable |
| No load balancing | Traffic doesn't distribute across healthy instances |
| Tight coupling | Changing product service forces order service redeployment |
| Environment brittleness | Different URLs per environment = constant config changes |
| Scaling doesn't help | Spinning up new instances is useless if no one calls them |
2. What is Service Discovery?
Definition
Service Discovery is a mechanism through which microservices dynamically find each other without hardcoded addresses. Instead of knowing exactly where a service is, a service asks a central registry: "Where can I find the product service?" and the registry returns current, live instance addresses.
Real-World Analogy
Think of it like a phone book (directory service):
- You don't memorize everyone's phone number
- Instead, you look up "Pizza Shop" in the directory and get the current number
- If Pizza Shop moves or changes their number, the directory is updated — you don't have to change your address book
- If Pizza Shop has 3 branches, the directory can tell you all three
Service Discovery is exactly this, but for microservice instances.
Two Roles in Service Discovery
The Server Role
The Eureka Server is the central registry. It:
- Maintains a list of all registered client services with their instance details (name, ID, IP, port, health status)
- Acts as the phone book that any registered client can query
- Tracks which instances are alive vs. dead
The Client Role
Every Eureka Client (your microservices like Order Service, Product Service) does two things:
| Action | What it means | Configuration |
|---|---|---|
| Register | "Hello Server, I exist at this IP:Port, please track me" | eureka.client.register-with-eureka=true |
| Discover | "Server, give me the list of instances for service X" | eureka.client.fetch-registry=true |
A single microservice can do both — register itself AND discover other services.
3. Eureka Netflix's Service Discovery Solution
Background
Eureka was developed by Netflix for their massive microservices infrastructure and later open-sourced. It has been adopted into Spring Cloud as the go-to service discovery solution for Spring Boot microservices.
Eureka Architecture Overview
4. Setting Up the Eureka Server
Step 1: Add the Dependency
Create a new Spring Boot project (via Spring Initializr) and add the Eureka Server dependency to pom.xml:
1<dependencies>2 <dependency>3 <groupId>org.springframework.boot</groupId>4 <artifactId>spring-boot-starter-web</artifactId>5 </dependency>6
7 <!-- Eureka Server dependency -->8 <dependency>9 <groupId>org.springframework.cloud</groupId>10 <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>11 <!-- Version managed by Spring Cloud BOM — do NOT hardcode version here -->12 </dependency>13</dependencies>14
15<!-- Spring Cloud BOM — manages version compatibility across all Spring Cloud libraries -->16<dependencyManagement>17 <dependencies>18 <dependency>19 <groupId>org.springframework.cloud</groupId>20 <artifactId>spring-cloud-dependencies</artifactId>21 <version>2023.0.0</version> <!-- Use latest compatible version -->22 <type>pom</type>23 <scope>import</scope>24 </dependency>25 </dependencies>26</dependencyManagement> instead of hardcoding the version?
Spring Cloud has many sub-libraries (Eureka, Feign, Gateway, Config Server, etc.). Their versions must be mutually compatible. Hardcoding each version independently risks incompatibility. The Spring Cloud BOM (Bill of Materials) ensures all Spring Cloud libraries use versions that are tested to work together. Let the BOM manage versions — don't fight it.Step 2: Enable the Eureka Server
Add @EnableEurekaServer to your main application class:
1@SpringBootApplication2@EnableEurekaServer // ← This is the magic annotation3public class EurekaServerApplication {4
5 public static void main(String[] args) {6 SpringApplication.run(EurekaServerApplication.class, args);7 }8}What @EnableEurekaServer does:
- Instructs Spring Boot to create the necessary beans for Eureka Server functionality
- Activates the Eureka Controller (REST API for registration/discovery)
- Activates the Eureka Dashboard (visual UI at
http://localhost:8761) - Without this annotation, the application starts as a plain Spring Boot app — no Eureka behavior
Step 3: Configure application.properties
1# Application identity2spring.application.name=eureka-server3server.port=87614
5# === CRITICAL: Disable client behavior on the server ===6# The server should NOT register itself with another Eureka server7eureka.client.register-with-eureka=false8
9# The server should NOT try to fetch a registry (it IS the registry)10eureka.client.fetch-registry=falsefalse on the server?
By default, every Spring application with Eureka on the classpath acts as a client — it tries to register itself and fetch a registry. These default behaviors make sense for microservices but are meaningless (and error-causing) for the server itself. Setting both to false tells the server: "You are the registry, not a client of a registry."
In a clustered Eureka Server setup (Section 9), these are set back to true so each server registers with its peer servers.Step 4: Verify The Eureka Dashboard
Start the application and navigate to http://localhost:8761. You should see:
1Eureka Dashboard2Spring Eureka3
4System Status5 Environment: test6 Data center: default7 Current time: [timestamp]8 Uptime: 00:009
10DS Replicas: (none)11
12Instances currently registered with Eureka:13 (No instances registered yet)This dashboard is your live view of all registered services and their health status.
5. Setting Up Eureka Clients (Microservices)
Every microservice that wants to participate in service discovery (register itself and/or discover other services) is a Eureka Client.
Step 1: Add the Eureka Client Dependency
1<dependencies>2 <dependency>3 <groupId>org.springframework.boot</groupId>4 <artifactId>spring-boot-starter-web</artifactId>5 </dependency>6
7 <!-- Eureka Client dependency -->8 <dependency>9 <groupId>org.springframework.cloud</groupId>10 <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>11 <!-- Version managed by Spring Cloud BOM -->12 </dependency>13</dependencies>14
15<!-- Same Spring Cloud BOM as server -->16<dependencyManagement>17 <dependencies>18 <dependency>19 <groupId>org.springframework.cloud</groupId>20 <artifactId>spring-cloud-dependencies</artifactId>21 <version>2023.0.0</version>22 <type>pom</type>23 <scope>import</scope>24 </dependency>25 </dependencies>26</dependencyManagement>Step 2: Configure application.properties
Product Service
1spring.application.name=product-service # ← This name appears in Eureka dashboard2server.port=80813
4# Client behavior (both true by default — shown explicitly for clarity)5eureka.client.register-with-eureka=true # Register this service with Eureka Server6eureka.client.fetch-registry=true # Fetch registry from Eureka Server7
8# === CRITICAL: Tell the client where the Eureka Server is ===9eureka.client.service-url.defaultZone=http://localhost:8761/eurekaOrder Service
1spring.application.name=order-service2server.port=80803
4eureka.client.register-with-eureka=true5eureka.client.fetch-registry=true6
7eureka.client.service-url.defaultZone=http://localhost:8761/eurekaeureka.client.service-url.defaultZone is the most critical configuration for clients. Without it, the client does not know where the Eureka Server is and cannot register or discover. The path /eureka at the end is the default Eureka Server endpoint — do not change it unless you have explicitly reconfigured the server endpoint.Step 3: Verify Registration
Start the Eureka Server first, then start Product Service and Order Service. Refresh http://localhost:8761:
1Instances currently registered with Eureka:2
3Application AMIs Availability Zones Status4PRODUCT-SERVICE n/a (1) UP (1) - 192.168.1.10:product-service:80815ORDER-SERVICE n/a (1) UP (1) - 192.168.1.10:order-service:8080The dashboard shows:
- Service name (uppercase of
spring.application.name) - Instance ID (IP + service name + port)
- Status (UP = healthy, DOWN = unreachable)
- Number of instances
6. Invoking Services Using Service Discovery
6.1 With RestTemplate + DiscoveryClient (Manual)
This approach uses the DiscoveryClient to fetch instance information from Eureka, then manually selects an instance and calls it via RestTemplate.
The Old Way (Hardcoded BAD)
1@Service2public class OrderService {3
4 private final RestTemplate restTemplate = new RestTemplate();5
6 public Product getProduct(Long productId) {7 // ❌ Hardcoded URL — all problems from Section 1 apply8 return restTemplate.getForObject(9 "http://localhost:8081/api/products/" + productId,10 Product.class11 );12 }13}The New Way (Service Discovery GOOD)
1@Service2public class OrderService {3
4 @Autowired5 private DiscoveryClient discoveryClient;6 // DiscoveryClient is from: org.springframework.cloud.client.discovery.DiscoveryClient7
8 @Autowired9 private RestTemplate restTemplate;10
11 public Product getProduct(Long productId) {12
13 // Step 1: Fetch all registered instances of "product-service" from Eureka14 // The name MUST match the spring.application.name of the target service15 List<ServiceInstance> instances =16 discoveryClient.getInstances("product-service");17
18 if (instances.isEmpty()) {19 throw new RuntimeException("No instances of product-service available");20 }21
22 // Step 2: Choose an instance23 // ⚠️ This is simplified — in production, use a proper load balancing algorithm24 // e.g., round-robin, weighted, least-connections25 ServiceInstance instance = instances.get(0); // Just picking the first one26
27 // Step 3: Use the URI from the chosen instance (no hardcoding)28 URI uri = instance.getUri();29 // uri = "http://10.0.0.1:8081" (fetched dynamically from Eureka)30
31 // Step 4: Make the call using the dynamic URI32 return restTemplate.getForObject(33 uri + "/api/products/" + productId, // Only the path is hardcoded34 Product.class35 );36 }37}What ServiceInstance Contains
1// ServiceInstance interface provides:2instance.getServiceId() // "product-service"3instance.getHost() // "10.0.0.1"4instance.getPort() // 80815instance.getUri() // URI("http://10.0.0.1:8081")6instance.getInstanceId() // "10.0.0.1:product-service:8081"7instance.isSecure() // false (http) or true (https)8instance.getMetadata() // Map of additional metadataThe Load Balancing Gap
1// ⚠️ Manual load balancing — you must implement the logic yourself:2List<ServiceInstance> instances = discoveryClient.getInstances("product-service");3
4// Option A: Always pick first (not balanced — bad)5ServiceInstance instance = instances.get(0);6
7// Option B: Random selection8ServiceInstance instance = instances.get(new Random().nextInt(instances.size()));9
10// Option C: Round-robin (stateful — needs counter)11ServiceInstance instance = instances.get(callCount++ % instances.size());12
13// Option D: Integrate Spring Cloud LoadBalancer (recommended over manual logic)14// → Use @LoadBalanced RestTemplate instead (see below)6.2 With FeignClient (Automatic)
FeignClient with service discovery is the most elegant approach. The framework handles instance discovery, selection, and load balancing automatically. You just provide the service name.
Required Dependency
1<dependency>2 <groupId>org.springframework.cloud</groupId>3 <artifactId>spring-cloud-starter-openfeign</artifactId>4</dependency>5
6<!-- Load balancer — required when Feign + Service Discovery -->7<dependency>8 <groupId>org.springframework.cloud</groupId>9 <artifactId>spring-cloud-starter-loadbalancer</artifactId>10</dependency>spring-cloud-starter-loadbalancer dependency. Without it, the framework cannot pick which instance to call when multiple instances are available.Enable Feign Clients
1@SpringBootApplication2@EnableFeignClients // ← Required to activate Feign client scanning3public class OrderServiceApplication {4 public static void main(String[] args) {5 SpringApplication.run(OrderServiceApplication.class, args);6 }7}Define the Feign Client
1// The old way: url hardcoded2// @FeignClient(name = "product-service", url = "http://localhost:8081")3
4// The new way: just the service name — NO URL needed5@FeignClient(name = "product-service") // ← Matches spring.application.name of target6public interface ProductServiceClient {7
8 @GetMapping("/api/products/{id}")9 Product getProductById(@PathVariable("id") Long id);10
11 @GetMapping("/api/products")12 List<Product> getAllProducts();13}Use the Feign Client in OrderService
1@Service2public class OrderService {3
4 @Autowired5 private ProductServiceClient productServiceClient; // Injected like any Spring bean6
7 public Product getProduct(Long productId) {8 // Framework internally:9 // 1. Looks up "product-service" in local Eureka cache10 // 2. Gets list of available instances11 // 3. Applies load balancing (round-robin by default)12 // 4. Picks an instance13 // 5. Makes the HTTP call to that instance14 // All of this happens transparently!15 return productServiceClient.getProductById(productId);16 }17}Comparison: Manual vs Automatic Discovery
| Aspect | RestTemplate + DiscoveryClient | FeignClient + LoadBalancer |
|---|---|---|
| Instance fetching | Manual (discoveryClient.getInstances()) | Automatic |
| Load balancing | Manual (write your own logic or integrate LoadBalancer) | Automatic (round-robin by default) |
| Code verbosity | High — explicit URI construction | Low — just a method call |
| Error handling | Manual | Can integrate Resilience4j |
| When to use | When you need fine-grained control over instance selection | Most production use cases |
7. Deep Dive How Eureka Server Knows If a Client Is Up or Down
This is one of the most important interview topics. There are exactly two mechanisms.
Mechanism 1: Graceful Shutdown De-registration Request
When a client application shuts down normally (e.g., you stop it from your IDE or via kill signal), the Eureka client library automatically sends a de-registration request to the Eureka Server before shutting down.
What you see in logs:
Product Service (client) logs:
1INFO - Unregistering application PRODUCT-SERVICE with eureka with status DOWN2INFO - Shutting down Eureka ConnectionEureka Server logs:
1INFO - Cancelled instance: PRODUCT-SERVICE/192.168.1.10:product-service:80812INFO - DS: Registry: cancel called for PRODUCT-SERVICEMechanism 2: Heartbeat Detecting Non-Graceful Failures
When a service crashes (power failure, OOM, network partition, kill -9), it cannot send a de-registration request. Eureka handles this through periodic heartbeats.
Heartbeat Configuration
Client-side (product-service/application.properties):
1# How often the client sends a heartbeat to the server (seconds)2# Default: 30 seconds3eureka.instance.lease-renewal-interval-in-seconds=304
5# Tell the server: wait at most this long for my heartbeat before removing me6# Default: 90 seconds7# This value MUST be greater than lease-renewal-interval-in-seconds8eureka.instance.lease-expiration-duration-in-seconds=90Server-side (eureka-server/application.properties):
1# Enable removal of instances when heartbeat is missed2# Default is true (self-preservation mode ON) — set to false for dev/testing3eureka.server.enable-self-preservation=false4
5# How often the server checks for and evicts expired instances (milliseconds)6# Default: 60000 (60 seconds)7eureka.server.eviction-interval-timer-in-ms=6000 # Check every 6 seconds (for testing)Understanding Lease Renewal vs Lease Expiration
1Timeline example (renewal=60s, expiration=90s):2
3T=0s: Client registers. lastRenewalTime = T+04T=60s: Client sends heartbeat. lastRenewalTime = T+605T=120s: Client sends heartbeat. lastRenewalTime = T+1206T=121s: Client CRASHES 💀 (no more heartbeats)7
8Server eviction check runs at T=127s (6s interval):9 currentTime (127) - lastRenewalTime (120) = 7s10 7s < 90s (expiration duration) → NOT yet expired11
12Server eviction check runs at T=133s:13 currentTime (133) - lastRenewalTime (120) = 13s14 13s < 90s → still not expired15
16... (server keeps waiting)17
18Server eviction check runs at T=211s:19 currentTime (211) - lastRenewalTime (120) = 91s20 91s > 90s (expiration duration) → EXPIRED ✅21 Instance removed from registry!What is Self-Preservation Mode?
Eureka has a built-in defense mechanism called Self-Preservation Mode (default: ON).
1Normally, if >15% of expected heartbeats are missing in the last minute,2Eureka assumes there is a NETWORK PARTITION (not that the services are dead).3In this case, it STOPS removing instances — better to keep stale entries4than to accidentally remove healthy services that just can't send heartbeats5due to a network issue.| Setting | Behavior |
|---|---|
enable-self-preservation=true (default) | Eureka stops evicting instances if too many heartbeats are missed simultaneously. Safe for production. |
enable-self-preservation=false | Eureka always evicts instances with missed heartbeats. Better for local dev/testing. |
enable-self-preservation=false in production. In a network partition event, disabling self-preservation would cause Eureka to evict ALL your instances even though they're healthy. Only disable it in development/testing environments where you want fast instance removal.8. How Eureka Server Stores Data
Storage Mechanism
Eureka Server stores all registry data in memory only — there is no database persistence.
1// Simplified representation of Eureka's internal data structure:2// Key: Application name / Instance ID3// Value: Instance details4
5Map<String, List<InstanceInfo>> registry = new ConcurrentHashMap<>();6
7// Example contents:8// "PRODUCT-SERVICE" → [9// InstanceInfo{10// appName: "PRODUCT-SERVICE",11// instanceId: "10.0.0.1:product-service:8081",12// ipAddr: "10.0.0.1",13// hostname: "prod-host-1",14// port: 8081,15// status: UP,16// lastRenewalTime: 1716239022000,17// leaseExpirationDuration: 9018// },19// InstanceInfo{20// appName: "PRODUCT-SERVICE",21// instanceId: "10.0.0.2:product-service:8081",22// ...23// status: UP24// }25// ]26// "ORDER-SERVICE" → [ ... ]What Each InstanceInfo Contains
| Field | Description | Example |
|---|---|---|
appName | Service name | PRODUCT-SERVICE |
instanceId | Unique identifier | 10.0.0.1:product-service:8081 |
ipAddr | IP address of the instance | 10.0.0.1 |
hostname | Hostname | prod-host-1 |
port | Port number | 8081 |
status | Current health status | UP, DOWN, STARTING, OUT_OF_SERVICE |
lastRenewalTime | Timestamp of last heartbeat | 1716239022000 |
leaseExpirationDuration | Seconds server waits for heartbeat | 90 |
Why In-Memory? Trade-offs
| Pro | Con |
|---|---|
| Extremely fast reads and writes | All data lost if Eureka Server restarts |
| No DB dependency or latency | Requires clustering for durability |
| Simplicity — no schema, migration, etc. | Not suitable for single-node deployments in production |
9. High Availability Eureka Server Cluster
Is a Single Eureka Server a Single Point of Failure?
Yes — if you run only one Eureka Server. If it goes down:
- No new instances can register
- Existing clients cannot discover new instances
- Depending on cache freshness, existing calls may still work (from client-side cache) for some time — but degraded
The Solution: Eureka Server Cluster
In production, three Eureka Server nodes are run on different machines/containers. Each server acts as both a server (maintaining a registry) and a client of the other two servers (registering with them and syncing data).
Configuring Eureka Server Cluster
Server 1 configuration
1# eureka-server-1/application.properties2spring.application.name=eureka-server3server.port=87614eureka.instance.hostname=eureka-server-15
6# ← These are TRUE now (unlike standalone setup)7# Server 1 registers itself with Server 2 and Server 38eureka.client.register-with-eureka=true9eureka.client.fetch-registry=true10
11# Point to the OTHER servers (not itself)12eureka.client.service-url.defaultZone=\13 http://eureka-server-2:8762/eureka,\14 http://eureka-server-3:8763/eurekaServer 2 configuration
1# eureka-server-2/application.properties2spring.application.name=eureka-server3server.port=87624eureka.instance.hostname=eureka-server-25
6eureka.client.register-with-eureka=true7eureka.client.fetch-registry=true8
9# Point to Server 1 and Server 310eureka.client.service-url.defaultZone=\11 http://eureka-server-1:8761/eureka,\12 http://eureka-server-3:8763/eurekaServer 3 configuration
1# eureka-server-3/application.properties2spring.application.name=eureka-server3server.port=87634eureka.instance.hostname=eureka-server-35
6eureka.client.register-with-eureka=true7eureka.client.fetch-registry=true8
9eureka.client.service-url.defaultZone=\10 http://eureka-server-1:8761/eureka,\11 http://eureka-server-2:8762/eurekaClient configuration pointing to all 3 servers
1# product-service/application.properties2spring.application.name=product-service3server.port=80814
5# All three Eureka Server URLs — client tries them in order, falls back to next if one is down6eureka.client.service-url.defaultZone=\7 http://eureka-server-1:8761/eureka,\8 http://eureka-server-2:8762/eureka,\9 http://eureka-server-3:8763/eurekaData Replication and Consistency Model
10. Client-Side Caching Solving the Latency Problem
Does Every Service Call Go Through Eureka?
No. This is a critical insight. If every service-to-service call first hit Eureka, you'd have doubled latency and Eureka would become a bottleneck.
Instead, Eureka clients maintain a local cache of the registry:
Cache Refresh Configuration
1# How often the client refreshes its local registry cache from Eureka Server (seconds)2# Default: 30 seconds3eureka.client.registry-fetch-interval-seconds=30The Stale Cache Problem and Trade-off
This is a critical trade-off that every engineer must understand:
1Product Service Instance 1: RUNNING (ID: ip1:8081)2Product Service Instance 2: RUNNING (ID: ip2:8081) ← Goes DOWN at T=100s3
4Order Service local cache (refreshed at T=90s):5 product-service: [ip1:8081 UP, ip2:8081 UP] ← Still shows ip2 as UP!6
7Order Service next refresh: T=90+30=120s8
9Between T=100s and T=120s:10 Order Service may choose ip2 and call it → CONNECTION REFUSED 💥The Trade-off Matrix
registry-fetch-interval-seconds | Cache Freshness | Load on Eureka Server |
|---|---|---|
| Very small (e.g., 1s) | Very fresh — stale window is ~1s | Very high — Eureka polled constantly |
| Small (e.g., 5s) | Fresh — stale window is ~5s | High |
| Default (30s) | Acceptable — stale window is ~30s | Low |
| Large (e.g., 300s) | Stale — stale window is 5 minutes | Very low |
| Too large (e.g., 10000s) | Very stale — dangerous | Negligible |
registry-fetch-interval-seconds is set too high, your services may attempt to call instances that have been dead for minutes. This leads to timeout errors that must be caught with retry logic and circuit breakers (Resilience4j).
The default of 30 seconds is a reasonable balance for most production workloads. Adjust based on how quickly your environment scales up/down.Handling Stale Cache Calls
Since stale cache calls to dead instances are possible, always add retry and circuit breaker logic:
1// With Feign + Resilience4j2@FeignClient(name = "product-service")3@CircuitBreaker(name = "product-service", fallbackMethod = "getProductFallback")4@Retry(name = "product-service")5public interface ProductServiceClient {6 @GetMapping("/api/products/{id}")7 Product getProductById(@PathVariable Long id);8}11. Complete Configuration Reference
Eureka Server application.properties
1# ===== SERVER IDENTITY =====2spring.application.name=eureka-server3server.port=87614
5# ===== STANDALONE MODE (single server) =====6eureka.client.register-with-eureka=false # Don't register self7eureka.client.fetch-registry=false # Don't fetch registry8
9# ===== SELF-PRESERVATION =====10# true (default): Don't evict instances even if heartbeats missed (safe for production)11# false: Evict instances when heartbeat missed (good for dev/testing)12eureka.server.enable-self-preservation=false13
14# ===== EVICTION =====15# How often (milliseconds) server checks for and evicts expired instances16# Default: 60000 (60 seconds)17eureka.server.eviction-interval-timer-in-ms=6000018
19# ===== CLUSTER MODE (uncomment when running multi-node) =====20# eureka.client.register-with-eureka=true21# eureka.client.fetch-registry=true22# eureka.instance.hostname=eureka-server-123# eureka.client.service-url.defaultZone=http://server2:8762/eureka,http://server3:8763/eurekaEureka Client (Microservice) application.properties
1# ===== SERVICE IDENTITY =====2spring.application.name=product-service # This name used for discovery3server.port=80814
5# ===== REGISTRATION =====6eureka.client.register-with-eureka=true # Default: true7eureka.client.fetch-registry=true # Default: true8
9# ===== SERVER LOCATION =====10# Single server:11eureka.client.service-url.defaultZone=http://localhost:8761/eureka12# Cluster (multiple servers):13# eureka.client.service-url.defaultZone=http://s1:8761/eureka,http://s2:8762/eureka,http://s3:8763/eureka14
15# ===== HEARTBEAT (client → server) =====16# How often client sends heartbeat (seconds). Default: 3017eureka.instance.lease-renewal-interval-in-seconds=3018
19# Max time server waits for heartbeat before marking instance expired (seconds). Default: 9020# Must be > lease-renewal-interval-in-seconds21eureka.instance.lease-expiration-duration-in-seconds=9022
23# ===== CACHE REFRESH (client local cache) =====24# How often client refreshes its local registry copy from server (seconds). Default: 3025eureka.client.registry-fetch-interval-seconds=30Quick Config Decision Guide
| Question | Config Key | Recommendation |
|---|---|---|
| How fast should dead instances be detected? | lease-expiration-duration-in-seconds | 90s (default) for production |
| How often should client send heartbeat? | lease-renewal-interval-in-seconds | 30s (default) |
| How stale can my instance list get? | registry-fetch-interval-seconds | 30s (default) |
| Should server evict dead instances? | enable-self-preservation | true in prod, false in dev |
| How often should server check for dead instances? | eviction-interval-timer-in-ms | 60000ms (default) |
12. Common Mistakes
Mistake 1: Starting Client Before Server
1❌ Start Order Service before Eureka Server is running2→ Client logs: "Connection refused to http://localhost:8761/eureka"3→ Client enters retry mode but errors flood the logs4→ Service still starts, but may not register properly5
6✅ Always start Eureka Server first, then clientsMistake 2: Wrong `spring.application.name` in Discovery Call
1// If product-service has: spring.application.name=product-service2// Then in order-service:3
4// ❌ WRONG name (case mismatch or typo)5discoveryClient.getInstances("ProductService"); // Returns empty list6discoveryClient.getInstances("product_service"); // Returns empty list7
8// ✅ CORRECT — matches spring.application.name exactly (case-insensitive in Eureka, but be consistent)9discoveryClient.getInstances("product-service"); // Returns instancesMistake 3: Forgetting LoadBalancer Dependency with Feign
1<!-- ❌ Missing — Feign with service discovery will fail to pick an instance -->2<!-- Only have: spring-cloud-starter-openfeign -->3
4<!-- ✅ Both required -->5<dependency>6 <groupId>org.springframework.cloud</groupId>7 <artifactId>spring-cloud-starter-openfeign</artifactId>8</dependency>9<dependency>10 <groupId>org.springframework.cloud</groupId>11 <artifactId>spring-cloud-starter-loadbalancer</artifactId>12</dependency>Mistake 4: Disabling Self-Preservation in Production
1# ❌ DANGEROUS in production2eureka.server.enable-self-preservation=false3
4# If a network hiccup causes heartbeats to fail temporarily,5# Eureka will DELETE ALL INSTANCES even though they're healthy.6# Your entire service mesh goes down.7
8# ✅ Only disable in local dev/testing9# Leave it true (default) in productionMistake 5: Setting lease-renewal > lease-expiration
1# ❌ WRONG — renewal interval is LONGER than expiration window2eureka.instance.lease-renewal-interval-in-seconds=1203eureka.instance.lease-expiration-duration-in-seconds=904
5# Client sends heartbeat every 120s, but server removes after 90s6# Server will ALWAYS think the client is dead!7
8# ✅ CORRECT — renewal must be significantly less than expiration9eureka.instance.lease-renewal-interval-in-seconds=3010eureka.instance.lease-expiration-duration-in-seconds=90Mistake 6: Hardcoding Port in Application Name
1# ❌ WRONG — port is not part of the application name2spring.application.name=product-service-80813
4# This creates separate registry entries for each port,5# defeating the purpose of multi-instance discovery6
7# ✅ CORRECT — same name for all instances8spring.application.name=product-service9server.port=8081 # Port is registered separately in instance metadata13. Best Practices
| Practice | Explanation |
|---|---|
| Use Spring Cloud BOM | Never hardcode Spring Cloud dependency versions. Use BOM for compatibility management. |
| Run Eureka in 3-node cluster in production | Eliminates single point of failure. Use odd numbers (3, 5) for quorum. |
Keep enable-self-preservation=true in production | Prevents mass eviction during network blips. |
| Use FeignClient over manual DiscoveryClient | Less code, automatic load balancing, cleaner interface. |
Add spring-cloud-starter-loadbalancer | Required for automatic load balancing with Feign/RestClient. |
| Pair with circuit breaker (Resilience4j) | Handle stale cache calls to dead instances gracefully. |
Use meaningful spring.application.name | Use kebab-case consistently (e.g., order-service, not OrderService or order_service). |
Set appropriate registry-fetch-interval-seconds | Default 30s is fine for most cases. Increase only if Eureka load is a concern. |
| Start Eureka Server before clients | In Docker Compose, use depends_on and health checks. |
| Monitor the Eureka dashboard | The dashboard at :8761 shows instance health in real-time — use it for debugging. |
Use different defaultZone per environment | In dev: localhost:8761, in prod: cluster addresses. Use Spring profiles. |
14. Interview Notes
Common Interview Questions
Concept Questions
| Question | Key Points |
|---|---|
| What is service discovery? Why is it needed? | Dynamic URL resolution for microservices. Solves hardcoding, single point of failure, no load balancing, tight coupling. |
| What are the two roles in Eureka? | Server (registry/phone book) and Client (registers + discovers). |
| What are the two things a Eureka client does? | Register itself + Fetch/discover other instances. |
| What is the difference between registration and discovery? | Registration: "Here I am." Discovery: "Where is service X?" |
| Can a Eureka Server also be a client? | Yes — in a cluster setup, each server registers with the other servers. |
Deep Technical Questions
| Question | Key Points |
|---|---|
| How does Eureka Server know if a client is down? | Two ways: (1) Graceful shutdown → de-registration request. (2) Abrupt shutdown → missed heartbeat → lease expiration → eviction. |
| How is data stored in Eureka Server? | In-memory only (Map). No DB persistence. |
| Is Eureka Server a single point of failure? | Only if you run one instance. Solution: 3-node cluster with each server also acting as a client of the others. |
| Does every API call go through Eureka? | No. Client fetches registry at startup and caches it locally. Future calls use the local cache. Eureka is only called periodically to refresh the cache. |
| What is self-preservation mode? | When >15% of heartbeats are missed, Eureka assumes network partition and stops evicting instances. Prevents mass deletion during transient network issues. |
| What is eventual consistency in Eureka? | Data replicated between server nodes is asynchronous. A newly registered instance may not be visible on all servers immediately. |
| What happens if the local registry cache is stale? | Client may call a dead instance → connection error. Mitigated by circuit breakers and retry logic. |
Configuration Questions
| Question | Key Points |
|---|---|
| What configs do you set on Eureka Server? | register-with-eureka=false, fetch-registry=false, enable-self-preservation, eviction-interval-timer-in-ms |
| What configs do you set on Eureka Client? | spring.application.name, service-url.defaultZone, lease-renewal-interval-in-seconds, lease-expiration-duration-in-seconds, registry-fetch-interval-seconds |
| Why do you set register-with-eureka=false on the server? | A standalone server doesn't need to register itself with another Eureka server. In cluster mode, it's set back to true. |
| What is the difference between lease-renewal-interval and lease-expiration-duration? | Renewal: how often client sends heartbeat. Expiration: how long server waits before declaring client dead. |
Tricky / Advanced Questions
| Question | Key Points |
|---|---|
| What is the CAP theorem trade-off in Eureka? | Eureka chooses AP (Availability + Partition tolerance) over CP (Consistency + Partition tolerance). It prefers to show possibly stale data over being unavailable. |
| What happens to in-flight requests when an instance goes down but cache isn't refreshed yet? | Order service calls the dead instance → connection error → must be handled by retry/circuit breaker (Resilience4j) |
| How does FeignClient know which instance to call when there are multiple? | Spring Cloud LoadBalancer (round-robin by default) picks an instance from the client's local cache. |
| How do you implement a custom load balancing strategy? | Implement ReactorServiceInstanceLoadBalancer and register it as a Spring bean. |
| What if you only want a service to discover others but not register itself? | eureka.client.register-with-eureka=false and eureka.client.fetch-registry=true |
15. Summary
Quick Revision Bullets
- Service Discovery eliminates hardcoded URLs. Services find each other dynamically via a central registry
- Eureka = Netflix's service discovery tool, integrated in Spring Cloud
- Two roles: Eureka Server (central registry) and Eureka Client (microservices that register + discover)
- Client does two things: Register itself (
register-with-eureka=true) and Discover others (fetch-registry=true) eureka.client.service-url.defaultZone= tells client where the Eureka Server is. Most critical client config@EnableEurekaServer= required on server main class. Creates all needed beansregister-with-eureka=false+fetch-registry=false= required on standalone server- Two health detection mechanisms: (1) De-registration on graceful shutdown. (2) Heartbeat + lease expiration on abrupt failure
lease-renewal-interval-in-seconds= how often client sends heartbeat (default 30s)lease-expiration-duration-in-seconds= how long server waits before evicting (default 90s). Must be > renewal intervaleviction-interval-timer-in-ms= how often server checks for dead instances (default 60000ms)- Self-preservation mode = prevents mass eviction during network partition. Keep
truein production - Data storage = in-memory only. No DB. Map of
appName → List - Single node Eureka = SPOF. Solution: 3-node cluster where each server is also a client of the others
- Eventual consistency = registry replicated async between cluster nodes. Brief inconsistency window possible
- Client-side cache = registry fetched at startup, cached locally. API calls do NOT hit Eureka — they use the local cache
registry-fetch-interval-seconds= how often cache is refreshed (default 30s). Stale cache → dead instance calls → need circuit breaker- FeignClient with service discovery: just use service name in
@FeignClient(name = "product-service")+ addspring-cloud-starter-loadbalancerdependency - Load balancing with DiscoveryClient + RestTemplate = manual. With FeignClient = automatic (round-robin)
16. Practice Questions
Easy
- What are the two problems with hardcoding service URLs in microservices?
- What is the role of the Eureka Server? Use a real-world analogy.
- What are the two things an Eureka Client can do? Which configs control them?
- What annotation must be added to the main class of an Eureka Server application?
- What is the most critical configuration property a client needs to connect to Eureka Server?
- Why do we set
register-with-eureka=falseon the Eureka Server in standalone mode? - What happens on the Eureka dashboard when you start a client service?
Medium
- Explain the two mechanisms by which Eureka detects a client is down. When is each used?
- What is the relationship between
lease-renewal-interval-in-secondsandlease-expiration-duration-in-seconds? What happens if renewal > expiration? - Compare using
DiscoveryClient + RestTemplatevsFeignClientfor calling a service with multiple instances. What's the key difference in load balancing? - Why do you need to add
spring-cloud-starter-loadbalancerwhen using FeignClient with service discovery? - A product service goes from 1 instance to 3 instances. How does the order service discover and call all three? What Spring configuration is needed?
- Explain what
eureka.server.enable-self-preservation=falsedoes. When should and should NOT you set this? - How does the client-side cache prevent every API call from hitting the Eureka Server?
Hard
- Draw the complete sequence of events from the moment Order Service wants to call Product Service (using FeignClient + Eureka) — from application startup to the final HTTP response.
- Product Service Instance 2 crashes (OOM — no graceful shutdown). Walk through exactly what happens: from the crash moment to when Order Service stops calling that instance. Mention all timing configurations involved.
- Eureka Server 1 (of a 3-node cluster) goes down. What happens to: (a) clients that were using Server 1, (b) newly registering services, (c) the data that was in Server 1's memory?
- Explain the stale cache problem in detail. A client's
registry-fetch-interval-secondsis set to 300 (5 minutes). What are the risks? How do you mitigate them in application code? - You are designing a microservices system with 20 services and 5 instances each (100 total instances). Describe your complete Eureka setup: server configuration, client configuration, HA strategy, and timing parameters. Justify each decision.
- An interviewer asks: "Service discovery adds an extra network hop (client → Eureka → service). Doesn't that cause latency?" — How do you respond? What is the actual latency profile?
lease-expiration-duration-in-seconds=5 and eviction-interval-timer-in-ms=3000 to see fast eviction in action
This hands-on sequence makes all the timing concepts concrete and unforgettable.Mastery check
How well can you recall this?
Finished this lesson?