How Services Work Together over HTTP

Have the order service query users and products over HTTP to create orders, and understand dependencies and failure handling.

🎯 Introduction

“From a Monolith to Multiple Services” split users, products, and orders into three Express services. To query an existing order, the order service reads its own data. To create an order, it must also verify that the user and product exist and retrieve the product price.

The user and product services now supply that information. The order service cannot read another process's data as though calling a local function. How can it retrieve what it needs?

Continue with the previous project and use Node.js's built-in fetch() to call other services over HTTP, implementing a working POST /orders endpoint.


🧱 Why Do Separate Services Need HTTP Communication?

Before the split, all features could run in one process, with the order module calling user module functions directly. Now the user service runs on 4001, products on 4002, and orders on 4003. Each process runs separately without shared memory.

Creating an order follows this flow:

courseComponents.mermaid.loading

Two points matter:

  • The order service creates orders. It decides whether creation is allowed and how the total is calculated, rather than delegating these decisions to the BFF.
  • User and product services provide their own data. The order service retrieves it over HTTP instead of accessing another process's arrays directly.

Splitting services changes how data is retrieved, but does not remove business dependencies.


🛠 Call User and Product Services with fetch

Before changing the order endpoint, use a small example to see how one Node.js program requests another HTTP service.

Keep users.mjs and products.mjs running. Create a temporary test-http.mjs in the project directory:

const response = await fetch('http://127.0.0.1:4001/users/u1');

if (!response.ok) {
    throw new Error(`User API request failed: ${response.status}`);
}

const user = await response.json();
console.log(user);

Run:

node test-http.mjs

Expected output:

{ id: 'u1', name: 'Lin', email: 'lin@example.test' }

This code has three essential steps:

  1. fetch(url) sends an HTTP request to the user service and waits for the response.
  2. response.ok checks success. HTTP 404 and 500 do not automatically make fetch() throw, so check explicitly.
  3. response.json() parses the response JSON into a JavaScript object.

For product information, request the product service address:

const response = await fetch('http://127.0.0.1:4002/products/p1');
const product = await response.json();
console.log(product);

With the product service running, the result is:

{ id: 'p1', name: 'Mechanical Keyboard', priceCents: 29900 }

We have confirmed that the order service can retrieve user and product data with the same fetch() calls. This temporary file is only for understanding HTTP calls and need not remain in the final project.


🛠 Implement Order Creation in the Order Service

The previous orders.mjs only exposed GET /orders/:id. Add POST /orders in the same file while preserving the query endpoint.

Order creation has four tasks: validate client fields, fetch the user and product over HTTP, calculate the total once both exist, and save the order.

1. Receive and Validate Order Parameters

The client submits data like this:

{
    "userId": "u1",
    "productId": "p1",
    "quantity": 2
}

First use express.json() to parse the JSON request body. Check that both IDs are nonempty strings and quantity is an integer from 1 to 99. Return 400 for invalid input without calling other services.

Do not accept a client-provided totalCents: the order service calculates the transaction amount from the product price; the client cannot choose it.

2. Query Both Services and Create the Order

Replace orders.mjs with this complete code:

import express from 'express';
import { orders } from './data.mjs';

const app = express();
app.use(express.json());

const USERS_URL = 'http://127.0.0.1:4001';
const PRODUCTS_URL = 'http://127.0.0.1:4002';

// Query business services over HTTP.
// 404 means the record is missing; let the caller handle other unsuccessful statuses.
async function getData(url) {
    const response = await fetch(url);

    if (response.status === 404) return null;
    if (!response.ok) {
        throw new Error(`Downstream service returned ${response.status}`);
    }

    return response.json();
}

// Keep the existing order details endpoint.
app.get('/orders/:id', (req, res) => {
    const order = orders.find(item => item.id === req.params.id);

    if (!order) {
        return res.status(404).json({ error: 'ORDER_NOT_FOUND' });
    }

    res.json(order);
});

// New: create an order.
app.post('/orders', async (req, res) => {
    const { userId, productId, quantity } = req.body ?? {};

    if (
        typeof userId !== 'string' || !userId.trim() ||
        typeof productId !== 'string' || !productId.trim() ||
        !Number.isSafeInteger(quantity) || quantity < 1 || quantity > 99
    ) {
        return res.status(400).json({ error: 'INVALID_ORDER' });
    }

    let user;
    let product;

    try {
        // The queries are independent and can start concurrently.
        [user, product] = await Promise.all([
            getData(`${USERS_URL}/users/${encodeURIComponent(userId)}`),
            getData(`${PRODUCTS_URL}/products/${encodeURIComponent(productId)}`),
        ]);
    } catch (error) {
        // Connection failure or downstream error: do not create the order.
        console.error('Business service query failed:', error);
        return res.status(502).json({ error: 'UPSTREAM_ERROR' });
    }

    if (!user || !product) {
        return res.status(422).json({ error: 'INVALID_ORDER_REFERENCE' });
    }

    const order = {
        id: `o${orders.length + 1}`,
        userId: user.id,
        productId: product.id,
        quantity,
        totalCents: product.priceCents * quantity,
    };

    orders.push(order);
    res.status(201).json(order);
});

app.listen(4003, '127.0.0.1', () => {
    console.log('orders service on 4003');
});

Refer to the flowchart and focus on three places:

  • Promise.all() starts user and product queries concurrently. The aggregation article introduced concurrent requests; here a business service calls other business services.
  • if (!user || !product) verifies both business references. null comes from getData() handling a downstream 404.
  • orders.push(order) runs only after successful queries. The order is created only when both records are valid, using the product service's priceCents to calculate the total.

This example stores orders in memory to illustrate communication. New records disappear when the order service restarts. orders.length + 1 is also only a teaching example for generating IDs in one process, not a production approach.


🧪 Verify HTTP Communication in the Order Service

Keep user and product services running and restart orders.mjs to activate the new route. This order creation experiment does not involve the BFF.

1. Create an Order Successfully

In another terminal, run:

curl -i -X POST http://127.0.0.1:4003/orders \
  -H 'Content-Type: application/json' \
  -d '{"userId":"u1","productId":"p1","quantity":2}'

With the previous article's initial data.mjs, the first successful creation since the order service started should return HTTP 201 Created, with a body like:

{
    "id": "o2",
    "userId": "u1",
    "productId": "p1",
    "quantity": 2,
    "totalCents": 59800
}

The unit price is 29900 fen and quantity is 2, giving a total of 59800 fen. Query the new order:

curl http://127.0.0.1:4003/orders/o2

The query endpoint should return the new order. If other orders have already been created, its ID may differ from o2.

2. Do Not Create an Order When the User Is Missing

curl -i -X POST http://127.0.0.1:4003/orders \
  -H 'Content-Type: application/json' \
  -d '{"userId":"missing","productId":"p1","quantity":2}'

This example returns HTTP 422:

{
    "error": "INVALID_ORDER_REFERENCE"
}

The user service returned a valid 404 response indicating that the user does not exist. The order service knows the business data fails creation requirements, so it rejects the order instead of saving it.

3. Do Not Create an Order When a Dependency Is Unavailable

Press Ctrl + C in the products.mjs terminal to stop only the product service, then submit a valid creation request again:

curl -i -X POST http://127.0.0.1:4003/orders \
  -H 'Content-Type: application/json' \
  -d '{"userId":"u1","productId":"p1","quantity":2}'

This time the example returns HTTP 502:

{
    "error": "UPSTREAM_ERROR"
}

A missing product differs from an unreachable product service. The former is a completed business query result; the latter means the order service cannot determine whether the product is valid and must not treat it as missing.

After the experiment, run node products.mjs again to restore the product service.


⚠️ What Should You Consider with HTTP Calls Between Services?

The client only calls the order service, but that service must wait for user and product results before completing the order. Therefore:

  • Slow dependencies slow down order creation. The requests can run concurrently, but their results are still required.
  • Failed dependencies can prevent order creation. Independent startup does not mean every business operation can complete independently.
  • Distinguish missing business data from service failures. This example's error contract uses 422 for invalid user or product references and 502 for failed dependency requests.

To focus on HTTP communication, this article does not yet implement timeouts, retries, or finer error classification. “Handling Service Call Failures” addresses those concerns later. Do not use this simplified implementation directly in a production ordering system.

This example only creates an in-memory order. It does not handle inventory deductions, payment, or cross-service transactions; repeated successful submissions also create multiple records. It demonstrates retrieving another service's data over HTTP, rather than a complete ecommerce transaction system.


❓ Questions and Answers

Q1: Can the order service directly import the user service's data.mjs after the split?

Technically it can import the file, but the order process only reads its own copy. It cannot see live changes in the user service process and also bypasses the service's data ownership boundary. Query the user service's HTTP API instead.

Q2: Why not let the BFF calculate the total when creating an order?

The total is a business rule result, not merely display formatting. The BFF can shape order information for pages, but different frontends must not independently determine actual transaction amounts. Here the order service retrieves the product price, calculates the total, and saves it.


🧪 Exercise

Complete these two tasks:

  1. Verify normal communication. Start all three business services and submit a valid order with quantity 1. Check for 201 and totalCents: 29900, then query the order to confirm it was created.
  2. Verify the dependency. Stop the user service and submit a valid order. Check for 502, restart the user service, and confirm requests recover. Explain why an unavailable user service does not prove that the user is missing.

You should be able to explain which services the order service calls, why it waits for their results, and when it actually saves an order.


🎉 You can now have the order service call user and product services over HTTP and create orders after retrieving their business data!