How does service discovery work in microservices?

Service discovery is the mechanism that lets microservices find and communicate with each other dynamically, without hard-coding network locations that change as services scale or move.

Key Points: • When a service instance starts up, it registers itself with a central Service Registry, providing its network location and metadata. • When one service needs to call another, it queries the registry to get the current, up-to-date location of a healthy instance rather than relying on a static address. • Health checks run continuously so the registry can remove instances that have crashed or become unresponsive, keeping the registry accurate. • Client-side discovery has the calling service query the registry directly and choose an instance itself; server-side discovery has a load balancer or gateway do that lookup on the caller's behalf. • This dynamic lookup is what allows services to scale up, scale down, restart, or move between hosts without breaking communication between them.

Example: When the Inventory Service is scaled from two instances to five, each new instance registers itself with Eureka on startup, and the Order Service's next lookup for "inventory-service" automatically includes all five instances without any manual configuration change.

Interview Tip: A concise interview answer is:

"Each service registers its location with a central registry on startup, and other services query that registry to find a current, healthy instance instead of using a hard-coded address. Health checks keep the registry accurate by removing instances that go down, which is what lets services scale, restart, or move without breaking how they find each other."