What is Service Discovery and why is it needed?
Topic: microservices, Infrastructure. Level: Intermediate.
Answer
In dynamic environments instances come and go and get ephemeral IPs, so hardcoding addresses breaks. **Service discovery** lets services find each other by logical name. Two models:
- **Client-side**: the client queries a registry (Eureka, Consul) for healthy instances and load-balances itself.
- **Server-side**: the client hits a stable virtual address (load balancer / k8s Service / DNS) that routes to healthy instances.
A registry tracks registrations and health so traffic only goes to live instances.
```java
// Client-side discovery: call by service name, not IP:port
@FeignClient(name = "payment-service") // resolved via registry (Eureka/Consul)
interface PaymentClient {
@PostMapping("/charge") ChargeReply charge(@RequestBody ChargeRequest r);
}
// In Kubernetes, server-side discovery is just DNS:
// http://payment-service.default.svc.cluster.local/charge
```