Service Discovery — a mechanism that allows services to dynamically find and communicate with each other without hardcoded network locations. In a microservices environment where instances are created and destroyed dynamically, service discovery is essential.
System Design Context: In traditional architectures, service URLs were static and configured in properties files. With auto-scaling, container orchestration, and rolling deployments, service instances have dynamic IPs and ports. Service discovery solves this by maintaining a registry of available instances.
Why Service Discovery is Needed:
Discovery Patterns:
Eureka (Netflix OSS) — Production Setup:
1// Eureka Server2@SpringBootApplication3@EnableEurekaServer4public class EurekaServerApp {5 public static void main(String[] args) {6 SpringApplication.run(EurekaServerApp.class, args);7 }8}910// application.yml for Eureka Server11// server:12// port: 876113// eureka:14// instance:15// hostname: eureka-server16// client:17// register-with-eureka: false18// fetch-registry: false19// server:20// eviction-interval-timer-in-ms: 600002122// Eureka Client (Service)23@SpringBootApplication24@EnableDiscoveryClient25public class UserServiceApp {26 public static void main(String[] args) {27 SpringApplication.run(UserServiceApp.class, args);28 }29}3031// application.yml for Eureka Client32// spring:33// application:34// name: user-service35// eureka:36// client:37// service-url:38// defaultZone: http://localhost:8761/eureka/39// instance:40// prefer-ip-address: true41// lease-renewal-interval-in-seconds: 3042// lease-expiration-duration-in-seconds: 904344// Consuming discovered services45@Service46public class OrderService {47 @Autowired private RestTemplate restTemplate;4849 public User getUser(Long userId) {50 // "user-service" is resolved via Eureka51 return restTemplate.getForObject(52 "http://user-service/api/users/{id}", User.class, userId);53 }54}
Alternatives:
Production Configuration:
Common Pitfalls:
Monitoring:
Benefits: