Start Learning
Javaneer
Back to stage
Module 7·Microservices & Spring Cloud

Service Discovery

Let services find each other by name through a registry (Eureka) instead of hard-coded hosts, with client-side load balancing.

14 min readIntermediate
On this page

When the lending service needs to call the catalog service, where is the catalog service? Hard-coding http://192.168.1.42:8081 breaks the moment that instance moves, restarts, or scales to five copies. Service discovery solves this: services register themselves and find each other by name.

Register and discover

A discovery server (like Netflix Eureka) is a live registry. Each service instance registers itself on startup ("I'm catalog-service at this address") and sends heartbeats. Other services look up catalog-service by name and get the current address(es):

// lending-service calls catalog-service by NAME, not a hard-coded host
Book book = restClient.get()
    .uri("http://catalog-service/api/books/{isbn}", isbn)   // resolved via discovery
    .retrieve()
    .body(Book.class);

Spring resolves catalog-service to a real, currently-registered instance - and if there are several, it load-balances across them client-side.

A phone directory, not memorized numbers

Memorizing everyone's phone number means chaos the moment someone changes theirs. A phone directory lets you look people up by name and always get their current number. Service discovery is that directory for your services: you call them by name, and the registry always resolves the up-to-date address - even as instances come and go.

Discovery makes scaling and healing automatic

Because callers resolve by name, you can add instances (they register and start receiving traffic) or lose one (it stops heartbeating and is removed) with no config change anywhere. Discovery is what lets a microservice system scale and self-heal dynamically.

Why not just hard-code the URL?

The catalog service runs as three instances that autoscale up and down through the day, and their addresses change. Explain what breaks if lending-service hard-codes one instance's URL, and how service discovery fixes both the addressing and the load-balancing.

What problem does service discovery (e.g. Eureka) solve?

Key takeaways

  • Service discovery lets services find each other by logical name through a live registry (e.g. Eureka), not hard-coded addresses.
  • Instances register and heartbeat on startup; callers resolve the name to current, healthy instances.
  • When several instances exist, Spring load-balances across them client-side.
  • Adding or losing instances needs no config change - discovery enables dynamic scaling and self-healing.
  • It removes brittle hard-coded hosts, the root cause of fragile inter-service calls.
Was this lesson helpful?
Edit this page on GitHub