Handling Service Call Failures
🎯 Introduction
The BFF now queries orders, users, and products over HTTP. When all three services run normally, the order details page receives complete data.
But what if the user service stops unexpectedly or takes too long to respond? The BFF cannot wait indefinitely or mistake “user service unreachable” for “order not found.”
Continue with the existing Express + fetch() example and project structure. We will add BFF request timeouts, classify failures, and simulate faults to observe the responses.
⚠️ Which Service Call Failures Should You Distinguish?
For /bff/orders/o1, the BFF fetches the order first, then queries the user and product using its IDs. Failures mean different things depending on where they occur:
| Scenario | Meaning | Status returned here |
|---|---|---|
| Order service explicitly reports a missing order | The requested order was not found | 404 |
| Order exists but its user or product is missing | Required page data is incomplete; a dependency relationship is broken | 502 |
| User or product service is unreachable or returns a server error | The BFF cannot obtain a valid downstream result | 502 |
| Downstream exceeds the time limit | The BFF stops waiting for the result | 504 |
Do not conflate 404 and 502. A working order service reporting a missing order differs from a user service that is not running at all.
502 Bad Gateway and 504 Gateway Timeout commonly represent downstream call failures. This article follows that convention for learning; actual status choices should follow your API contract.
🛠 Limit Waiting with AbortSignal.timeout()
Previously, the BFF called fetch() directly:
const response = await fetch('http://127.0.0.1:4001/users/u1');
const user = await response.json();
If the downstream service is slow, this code may wait a long time. Set an upper limit:
const response = await fetch('http://127.0.0.1:4001/users/u1', {
signal: AbortSignal.timeout(800),
});
const user = await response.json();
AbortSignal.timeout(800) allows about 800 ms for this request. After that, the signal aborts the request, and fetch() or response body reading throws. The 800 value makes the local experiment easy to observe; it is not a universal production timeout.
Remember: HTTP 404 or 500 does not normally make fetch() throw automatically. Check response.ok to distinguish a completed error response from a request that could not complete.
Also, a timeout does not undo work already performed on the server. The caller stops waiting, but the server may already have processed the request. This is especially important for writes such as order creation.
🛠 Distinguish Missing Orders, Service Failures, and Timeouts in the BFF
Update bff.mjs from “From a Monolith to Multiple Services.” Keep the fixed addresses: users on 4001, products on 4002, orders on 4003, and the BFF on 4000.
This is the complete bff.mjs, ready to replace the old file. It preserves order aggregation and supports view=mobile and view=desktop from “BFF API Adaptation and Responsibility Boundaries.”
import express from 'express';
const app = express();
const services = {
users: 'http://127.0.0.1:4001',
products: 'http://127.0.0.1:4002',
orders: 'http://127.0.0.1:4003',
};
// Attach HTTP status and application error codes for consistent handling.
function createError(status, code) {
return Object.assign(new Error(code), { status, code });
}
// Call a business service with a maximum waiting time.
async function read(service, path) {
let response;
try {
response = await fetch(`${services[service]}${path}`, {
signal: AbortSignal.timeout(800),
});
// 404 explicitly reports that the downstream record is missing.
// The caller decides what that means in the current business context.
if (response.status === 404) {
throw createError(404, 'RESOURCE_NOT_FOUND');
}
if (!response.ok) {
throw createError(502, 'UPSTREAM_ERROR');
}
return await response.json();
} catch (error) {
// Preserve HTTP errors already classified above.
if (error.status) throw error;
// This call exceeded its time limit.
if (error.name === 'TimeoutError') {
throw createError(504, 'UPSTREAM_TIMEOUT');
}
// Connection failures, invalid responses, JSON parsing failures, and similar errors.
throw createError(502, 'UPSTREAM_UNAVAILABLE');
}
}
app.get('/bff/orders/:id', async (req, res) => {
const view = req.query.view ?? 'desktop';
if (!['mobile', 'desktop'].includes(view)) {
return res.status(400).json({ error: 'INVALID_VIEW' });
}
// 1. Fetch the order first; return 404 if it is explicitly missing.
let order;
try {
order = await read('orders', `/orders/${encodeURIComponent(req.params.id)}`);
} catch (error) {
if (error.status === 404) {
throw createError(404, 'ORDER_NOT_FOUND');
}
throw error;
}
// 2. Once the order exists, fetch user and product concurrently.
// Missing related records prevent aggregation; they do not mean the order is missing.
let user;
let product;
try {
[user, product] = await Promise.all([
read('users', `/users/${encodeURIComponent(order.userId)}`),
read('products', `/products/${encodeURIComponent(order.productId)}`),
]);
} catch (error) {
if (error.status === 404) {
throw createError(502, 'UPSTREAM_ERROR');
}
throw error;
}
// 3. Preserve the previously defined page responses after successful queries.
const summary = {
id: order.id,
customerName: user.name,
productName: product.name,
totalCents: order.totalCents,
};
if (view === 'mobile') {
return res.json(summary);
}
res.json({
...summary,
quantity: order.quantity,
user: { id: user.id, name: user.name },
});
});
// Express 5 passes errors thrown by async routes to this middleware.
app.use((error, req, res, next) => {
const status = error.status ?? 500;
const code = error.code ?? 'INTERNAL_ERROR';
// Keep internal details in service logs; return only agreed error codes to the frontend.
console.error('[BFF]', code, error.message);
res.status(status).json({ error: code });
});
app.listen(4000, '127.0.0.1', () => {
console.log('bff on 4000');
});
The code is longer, but adds only two capabilities:
- Timeouts:
read()limits eachfetch()to 800 ms and returns504on timeout. - Error classification: Missing target orders return
404; missing related data, connection failures, and downstream errors return502.
Why not forward every downstream 404 unchanged? The same downstream status has different meanings in different business contexts. An order endpoint's 404 means the target order is missing; a user endpoint's 404 means an existing order's related user data is missing. Express the failure according to the current operation, rather than copying status codes mechanically.
🧪 Simulate Failures and Verify 404, 502, and 504
First ensure product and order services are running:
node products.mjs
node orders.mjs
Run these commands in separate terminals. Do not start duplicate processes if they are already running. Restart the updated BFF too:
node bff.mjs
For these experiments, request port 4000 directly to rule out interference from the unified API entry point. No changes to gateway.mjs are needed.
1. Missing Order: Return 404
Ensure the order service is running, then run:
curl -i http://127.0.0.1:4000/bff/orders/missing
Expect HTTP 404 with this body:
{
"error": "ORDER_NOT_FOUND"
}
The BFF successfully contacted the order service and received an explicit “order not found” result.
2. Stopped User Service: Return 502
Press Ctrl + C in the users.mjs terminal. Keep the order service, product service, and BFF running, then run:
curl -i http://127.0.0.1:4000/bff/orders/o1
Expect HTTP 502:
{
"error": "UPSTREAM_UNAVAILABLE"
}
Order o1 still exists, but the BFF cannot connect to the user service and cannot return complete details. It should not return ORDER_NOT_FOUND.
3. Slow User Service: Return 504
To reproduce slow requests consistently, add a configurable delay to users.mjs. Replace it with:
import express from 'express';
import { users } from './data.mjs';
const app = express();
app.get('/users/:id', async (req, res) => {
// Simulate slow user service processing for local experiments only.
const delay = Number(process.env.DELAY_MS ?? 0);
if (delay > 0) {
await new Promise(resolve => setTimeout(resolve, delay));
}
const user = users.find(item => item.id === req.params.id);
if (!user) {
return res.status(404).json({ error: 'USER_NOT_FOUND' });
}
res.json(user);
});
app.listen(4001, '127.0.0.1', () => {
console.log('users service on 4001');
});
Start it in the user service terminal with about 1200 ms of delay per request:
DELAY_MS=1200 node users.mjs
Run again:
curl -i http://127.0.0.1:4000/bff/orders/o1
The BFF allows about 800 ms for the user request, so expect HTTP 504:
{
"error": "UPSTREAM_TIMEOUT"
}
The user service did not respond in time; this does not mean the user is missing. Stop the slow process and start the user service normally:
node users.mjs
Request the same order again. It should return HTTP 200 and order details JSON. Restoring the user service does not require restarting the BFF.
The experiment results are:
| Operation | Status | Response error code |
|---|---|---|
| Query a missing order | 404 | ORDER_NOT_FOUND |
| Stop the user service | 502 | UPSTREAM_UNAVAILABLE |
| Delay the user service by 1200 ms | 504 | UPSTREAM_TIMEOUT |
| Restore normal user service | 200 | None; returns order details |
Tip: These are the expected results for the code and local conditions described here. Results may differ if a service is stopped, a port is occupied, or requests go through another entry point. Debug by calling the business service directly first, then the BFF.
⚠️ Can You Retry a Failed Service Call Immediately?
Not always. Determine whether repeating the request is appropriate.
A GET request for user details typically does not modify data, so bounded retries may help with transient network failures. Repeating a definitive result such as “order not found” usually does not help.
Order creation with POST is different: a timeout may mean only that the response never reached the caller, while the order was successfully created. Sending the same request again immediately can create duplicates.
This article therefore does not retry automatically. Real projects need retry rules suited to each operation, especially protection against duplicate submissions for writes.
❓ Questions and Answers
Q1: Does a timeout mean the user service did not execute the request?
No. It only means the caller did not receive a result within the time limit. The server may still be processing the request or may already have finished.
Q2: Why return 404 for a missing order but 502 for a stopped user service?
A missing order is a completed business query result. A stopped user service means a dependency call failed and the BFF cannot verify user data. Returning 404 for both would incorrectly tell the frontend that the order is missing.
🧪 Exercise
Independently perform these three checks:
- Request
/bff/orders/missingand record the status and error code. - Stop the user service, request
/bff/orders/o1, and record the status and error code. - Start the user service with
DELAY_MS=1200, request/bff/orders/o1, and record the status and error code.
Success criteria: Obtain 404 / ORDER_NOT_FOUND, 502 / UPSTREAM_UNAVAILABLE, and 504 / UPSTREAM_TIMEOUT respectively. Finally, restart the user service normally, confirm the BFF returns 200 again, and explain why the three failures require different errors.
🎉 You can now set HTTP service call timeouts, distinguish missing business data from dependency failures and timeouts, and verify them through practical experiments!
Unified API Entry Point
Understand a unified API entry point, reuse Nginx reverse proxying to route requests, and distinguish its role from a BFF.
Introduction to Microservices
Understand the differences between monolithic, multiservice, and microservices architectures, learn what service autonomy and independent deployment mean, and decide when microservices are appropriate.
