Service Communication and Discovery
🎯 Introduction
Users, orders, inventory, and simulated payments now run independently. But independent execution alone does not complete a business operation: how does orders ask inventory for a result after a user submits an order? If inventory later runs three instances, which should orders call? We will use Express in the existing project to verify a real service call, then explain synchronous and asynchronous communication, API contracts, service discovery, and load balancing.
🧱 Synchronous Communication: Wait for a Result Before Continuing
Suppose a user buys two units. Orders needs to know whether inventory can reserve them before deciding whether to continue. This typically uses synchronous communication: send a request, wait for inventory's result, then proceed.
courseComponents.mermaid.loading
Synchronous means the current business flow waits for a response. It does not require blocking a Node.js thread. Node.js can handle other requests while await fetch() waits.
This suits operations requiring immediate results, such as looking up user information or checking stock. The cost is direct: slow inventory responses also delay order creation. Callers need timeouts and must distinguish business rejection from network failure. Later, “Fault Tolerance and Reliability” covers retries, circuit breakers, and idempotency.
Verify communication with Express
The previous article created four Express services, each with its own package.json and /health endpoint. Reuse that project and modify only orders. Inventory, users, and simulated payments keep their entry points, and Express needs no reinstallation.
Replace services/orders/src/app.mjs with this complete code (Node.js 22.x, Express 5.1.0; fetch is built into Node.js):
import express from 'express';
const app = express();
const port = 3002;
const inventoryUrl = 'http://localhost:3003';
app.get('/health', (req, res) => {
res.json({ service: 'orders', status: 'ok' });
});
app.get('/check-inventory-connection', async (req, res) => {
try {
const response = await fetch(`${inventoryUrl}/health`, {
signal: AbortSignal.timeout(1500)
});
if (!response.ok) {
return res.status(502).json({ connected: false, error: 'Unexpected inventory service response' });
}
const inventory = await response.json();
res.json({ connected: true, inventory });
} catch (error) {
console.error('Inventory service call failed:', error.message);
res.status(502).json({ connected: false, error: 'Inventory service temporarily unavailable' });
}
});
app.listen(port, () => {
console.log(`orders: http://localhost:${port}`);
});
There are three points to understand:
inventoryUrlis the local demo inventory address, using port3003from the previous article.AbortSignal.timeout(1500)gives this HTTP request a 1.5-second timeout, preventing indefinite waiting.- If inventory is unreachable or returns an unexpected response, this simplified example returns HTTP
502for a failed downstream call. This differs from a normal business rejection such as insufficient stock.
Open two terminals and start each service from the project root:
Terminal one:
cd services/inventory && npm start
Terminal two:
cd services/orders && npm start
In a third terminal, run:
curl -i http://localhost:3002/check-inventory-connection
Expect HTTP 200 with a body like:
{
"connected": true,
"inventory": {
"service": "inventory",
"status": "ok"
}
}
Stop inventory and repeat the command. Expect HTTP 502:
{
"connected": false,
"error": "Inventory service temporarily unavailable"
}
Orders is still running, but cannot reach inventory. Independent execution does not guarantee business availability when dependencies fail.
/health here only verifies communication. It does not implement stock reservation. Later business development articles cover actual inventory operations.✨ Asynchronous Communication: Announce What Has Happened
Suppose payments confirms a successful payment. It needs to notify orders, but may not need to wait for the order update before continuing all its own work.
Use asynchronous event communication: payments publishes a business fact such as PaymentSucceeded, which orders consumes later.
courseComponents.mermaid.loading
This event announces that payment succeeded; it is not a request to check whether payment succeeded. Receipt and processing can occur at different times. Whether orders receives it after temporary downtime depends on persistence, acknowledgment, and retry configuration.
You have already learned RabbitMQ, so we will not recreate exchanges, queues, or consumers. Remember:
- Synchronous request: the current flow needs an answer to choose its next step.
- Asynchronous event: announce a fact that already occurred; recipients can process it later.
🧩 API Contracts: Shared Rules Between Services
Orders should not need inventory's internal database schema to call it over HTTP. Both sides need an API contract defining how to send requests, what fields mean, and what success and failure look like.
For the future reservation operation, we can define this contract. This endpoint is not implemented yet.
POST /reservations
Content-Type: application/json
{"orderId":"o-100","sku":"A","quantity":2}
orderId identifies the order, sku identifies the stock keeping unit, and quantity is the number of units to reserve.
A successful reservation can return:
{
"reservationId": "r-100",
"status": "reserved"
}
Insufficient stock should produce an explicit business error, for example HTTP 409 with:
{
"code": "INSUFFICIENT_STOCK",
"message": "Insufficient stock"
}
Together, these rules form a minimal API contract:
| Contract item | Course design |
|---|---|
| Method and path | POST /reservations |
| Request fields | orderId, sku, quantity |
| Reservation success | HTTP 201 with reservationId and status |
| Insufficient stock | HTTP 409 with INSUFFICIENT_STOCK |
| Service call failure | Caller handles connection failures, timeouts, and server errors separately |
These HTTP statuses and field formats are one contract used in this course, not universal inventory API standards. Real implementations must also define required fields, allowed values, and error handling.
Plan upgrades too. If inventory suddenly renames quantity to count, older order instances still sending quantity may fail. Retain the old field temporarily, or publish a new API version when a breaking change is necessary.
Contracts make services depend on public rules instead of internal code. Later contract tests check whether both sides still honor them.
🔎 Service Discovery: Finding Instances When Addresses Change
Orders currently reaches inventory at http://localhost:3003, which is convenient with one local instance.
Production may run several instances, each a running copy of the same service. Inventory might run at:
Inventory instance A: 10.0.0.11:3003
Inventory instance B: 10.0.0.12:3003
Inventory instance C: 10.0.0.13:3003
These are illustrative addresses. IPs can change after restarts or relocation. Hard-coding all three means updating configuration whenever instances scale or move, increasing maintenance costs.
Service discovery determines how callers find currently reachable addresses or a stable entry point.
Two common approaches are:
- Discover instances through a registry: instances register their addresses at startup, and callers or proxies query available instances. Consul and Nacos can serve this role.
- Use a stable platform service name: Kubernetes Service, for example, lets callers reach a group of Pods through a relatively stable name, without maintaining every Pod address as instances change.
In Kubernetes, orders could access inventory through an internal name such as http://inventory:3003, provided the Service exists and its name and port match the actual configuration. This address only illustrates the principle. Our local example continues using http://localhost:3003; no platform or port change is needed.
Discovery answers where the target is. It does not require building a registry or learning Kubernetes configuration here.
⚖️ Discovery, Health Checks, and Load Balancing
Suppose inventory instance C has failed:
| Instance | Illustrative address | Status |
|---|---|---|
| A | 10.0.0.11:3003 | Healthy |
| B | 10.0.0.12:3003 | Healthy |
| C | 10.0.0.13:3003 | Unhealthy |
An order service request might follow this flow:
courseComponents.mermaid.loading
A and B represent alternative choices, not simultaneous delivery to both. A load balancer normally chooses one healthy instance for an ordinary HTTP request. Once C is considered unhealthy, it stops receiving newly assigned requests. How health information updates depends on the registry, proxy, or platform.
Each mechanism answers a different question:
- Service discovery: which addresses exist, or which stable entry point should callers use?
- Health checks: is an instance suitable for traffic? The registry, proxy, or platform may perform this role, depending on the architecture.
- Load balancing: which eligible instance should receive this request? Distribution need not be equal, and success is not guaranteed.
In client-side discovery, orders obtains an instance list and chooses a target itself. In server-side discovery, it calls a stable entry point and a proxy or platform chooses the backend. Both keep instance changes from directly affecting business code.
💡 Choosing for the Order System
| Business need | Communication or addressing | Main reason |
|---|---|---|
| Decide whether stock can be reserved during ordering | Synchronous request | The current flow needs the reservation outcome |
| Notify orders after payment succeeds | Asynchronous business event | Other services can process the fact later |
| One local inventory instance | Fixed http://localhost:3003 address | Simple and easy to debug |
| Multiple dynamic inventory instances | Stable service name or registry discovery | Avoid hard-coding every instance address |
A system can use both requests and events; they do not replace each other. Prefer synchronous requests when the current operation needs another service's result before deciding what to do next. Consider asynchronous events when announcing a completed business change that others can process later. Also consider recovery, response times, and deployment environment.
The next stage examines data ownership, then implements business events and addresses consistency.
❓ Knowledge Check
Q1: Does RabbitMQ eliminate the need for HTTP?
No. Synchronous HTTP still suits immediate reservation decisions; payment notifications can use asynchronous messages. Real systems often combine both.
Q2: Is service discovery the same as load balancing?
No. Discovery finds services, load balancing chooses an instance for a request, and health checks help exclude unsuitable instances.
Q3: Does discovery prevent API failures?
No. It locates targets but does not replace contracts, timeouts, idempotency, or business error handling.
🧪 Exercise
Perform these checks:
- Start the Express order and inventory services. Request
/check-inventory-connectionand confirmconnected: true. - Stop inventory and repeat. Observe the failure response and explain why orders still runs.
- Restart inventory, repeat, and confirm recovery to
connected: true. - Choose requests or events for reserving stock, notifying orders of payment success, and obtaining user profiles. Explain each choice.
- With only inventory A and B healthy, draw a request through the stable entry point and mark the instance that must not receive new requests.
Acceptance criteria: Observe success, failure, and recovery; distinguish HTTP reachability from successful reservation; explain discovery, health checks, and load balancing separately.
🎉 Congratulations on completing this article! You can now verify Express service calls and understand how to choose communication and discovery approaches.
Project Structure and Setup
Build four independent Express services for users, orders, inventory, and simulated payments, understand project structure and shared code boundaries, and verify independent execution.
Database Design
Understand data ownership and database isolation, choose cross-service queries, business snapshots, and read-only copies, and learn the constraints behind stock reservations.
