Java Academy

Master Java Development

Menu

Core Java

Servlets

JDBC

Microservices

Build Tools

APIs

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

OptionHow it worksTrade-off
Client-sideCaller selects an instanceMore client responsibility
Server-sideLoad balancer selectsCentral routing component
DNS-basedResolve service nameSimple platform integration
RegistryServices register healthAdditional 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

Quick Knowledge Test

Loading quiz questions...