Service Communication and Discovery

Choose synchronous and asynchronous communication, define API contracts, and understand how service discovery, load balancing, and health checks work together.

🎯 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:

  • inventoryUrl is the local demo inventory address, using port 3003 from 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 502 for 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.

Calling /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.
Asynchronous communication does not guarantee no waiting or successful delivery. “Business Events” covers reliable publication, duplicate consumption, and recovery.

🧩 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 itemCourse design
Method and pathPOST /reservations
Request fieldsorderId, sku, quantity
Reservation successHTTP 201 with reservationId and status
Insufficient stockHTTP 409 with INSUFFICIENT_STOCK
Service call failureCaller 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:

  1. 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.
  2. 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:

InstanceIllustrative addressStatus
A10.0.0.11:3003Healthy
B10.0.0.12:3003Healthy
C10.0.0.13:3003Unhealthy

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.

Finding instances, assessing health, and choosing an instance are separate responsibilities. A platform may combine them, but the concepts remain distinct.

💡 Choosing for the Order System

Business needCommunication or addressingMain reason
Decide whether stock can be reserved during orderingSynchronous requestThe current flow needs the reservation outcome
Notify orders after payment succeedsAsynchronous business eventOther services can process the fact later
One local inventory instanceFixed http://localhost:3003 addressSimple and easy to debug
Multiple dynamic inventory instancesStable service name or registry discoveryAvoid 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:

  1. Start the Express order and inventory services. Request /check-inventory-connection and confirm connected: true.
  2. Stop inventory and repeat. Observe the failure response and explain why orders still runs.
  3. Restart inventory, repeat, and confirm recovery to connected: true.
  4. Choose requests or events for reserving stock, notifying orders of payment success, and obtaining user profiles. Explain each choice.
  5. 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.