CodeBlanks Logo Icon CodeBlanks

Service discovery

Learn the service discovery pattern.

Service discovery

Service discovery is the mechanism that lets services find each other. Instead of a fixed IP, each service registers itself in a registry; other services fetch its address from there. This is essential in dynamic environments (containers, auto-scaling).

Example: when the user service starts it registers with registry.register("user-service", "10.0.0.5:3000"). When the order service needs to call the user service it gets the address with registry.lookup("user-service"). Popular tools: Consul, etcd, Eureka. Without service discovery each service hard-codes the other's address, which fails in environments where the number of replicas changes. Dynamic discovery lets new replicas be called as soon as they are added.

The registry pattern

A registry is a simple dictionary that maps service names to addresses. Services register when they start and unregister when they stop. The calling service asks the registry for the current address each time.

Example: const registry = new Map(); registry.set("user-service", "10.0.0.5:3000"); registry.get("user-service");. In production this becomes a more sophisticated tool (Consul), but the core idea is the same. The registry must be highly available; otherwise all service communication stops. Health checks remove dead replicas from the registry. This lets the system self-heal.

Practice Write a simple registry

Assign a new Map to a registry variable. Add a record with registry.set("user-service", "10.0.0.5:3000"). Fetch the address with registry.get("user-service") and print it with console.log.

Starter code

index.js
// Create a new Map as registry
// write here

// Add the user-service record
// write here

// Fetch the address and print it
// write here

Sample solution

index.js
const registry = new Map();
registry.set("user-service", "10.0.0.5:3000");
console.log(registry.get("user-service"));

Expected output

10.0.0.5:3000

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is service discovery for?

index.js
registry.register(name, addr)
  • Shuts down the service
  • Counts requests
  • Dynamically finds a service address Correct answer
  • Backs up the database

Explanation: Service discovery finds the address dynamically.

2 Complete the registry.set call

Question
registry.set("user-service", "10.0.0.5:3000");
const addr = registry.____("user-service");
Answer
registry.set("user-service", "10.0.0.5:3000");
const addr = registry.get("user-service");

Explanation: registry.get fetches the address.

3 Match each concept to its role

Term Meaning
registry Holds addresses
register Registers when service starts
lookup Asks for address
health check Cleans dead replicas

All lessons in Advanced