Microservices · Lesson 8
Service Discovery
Finding Services Dynamically
Service discovery lets a service locate another service without hard-coding a machine address. Instances register their health and location with a registry or a platform such as Kubernetes. Clients or a load balancer then choose a healthy instance.
Representing a Service Instance
A discovery record should include an identity, address, and health state. The caller should treat discovery data as temporary because instances can be replaced.
public record ServiceInstance(String serviceName, String host, int port, boolean healthy) {
public String baseUrl() {
return "http://" + host + ":" + port;
}
public static void main(String[] arguments) {
ServiceInstance instance = new ServiceInstance("course-service", "course-2", 8080, true);
System.out.println(instance.serviceName() + " at " + instance.baseUrl());
}
}
Discovery Options
| Option | How it works | Trade-off |
|---|---|---|
| Client-side | Caller selects an instance | More client responsibility |
| Server-side | Load balancer selects | Central routing component |
| DNS-based | Resolve service name | Simple platform integration |
| Registry | Services register health | Additional operational system |
Common Mistake and Practices
Common Mistake: Treating a discovered address as permanent. Containers, virtual machines, and deployments change addresses, so callers need refresh, timeout, and retry behavior.
- Register health, not only process existence.
- Cache discovery briefly.
- Apply timeouts to every call.
- Remove unhealthy instances quickly.
- Log selected instance identity for diagnosis.
Real-World Use Case
A quiz service discovers healthy course-service instances through the platform network instead of reading a fixed host from source code. Rolling deployments can replace instances without changing the caller.
Quiz Check