Communication Between Services

Lesson 7 of 10 · 20 min

x
70%

Service Discovery

In Kubernetes, Docker Swarm, or any auto-scaling environment, service instances come and go. Hard-coding http://inventory-service:8080 breaks the moment a container restarts on a different port or IP. Service discovery solves this with a registry: each instance registers itself on startup ("I am inventory-service, version 2.1, at 10.0.4.12:8080, healthy") and deregisters on shutdown. Clients — or an API Gateway, or a service mesh sidecar — query the registry to find a healthy instance before each request. Kubernetes DNS (inventory-service.default.svc.cluster.local) is a built-in form of service discovery. Consul, Eureka, and etcd are standalone registries used outside Kubernetes or for multi-cluster setups.

Before
Hard-coded endpoint
const INVENTORY_URL = 'http://10.0.4.12:8080';

async function checkStock(productId: string) {
  return fetch(`${INVENTORY_URL}/stock/${productId}`);
}
// Breaks when the container moves or scales
After
Discovery-based lookup
async function checkStock(productId: string) {
  const instance = await registry.getHealthy('inventory-service');
  return fetch(
    `http://${instance.host}:${instance.port}/stock/${productId}`
  );
}
// Registry returns any healthy instance

Key Takeaway

Never hard-code service addresses in dynamic environments — register on startup and discover at request time.

PreviousNext Lesson