Fault Tolerance and Reliability
🎯 Introduction
Orders queries inventory for availability. Normally inventory responds quickly, but must orders wait indefinitely if it becomes slow? Could repeated retries make inventory even busier?
Using these services, we explore how timeouts, retries, circuit breakers, isolation, and graceful degradation protect a system. We start with an actual slow request, then examine other safeguards. We will not revisit MySQL transactions, RabbitMQ acknowledgments, or database implementations of idempotency.
🧱 How One Slow Service Affects Another
Suppose orders receives 100 requests per second, each requiring an inventory query. Inventory previously responded in about 100 milliseconds, but now takes 20 seconds.
Waiting requests accumulate and retain connections, memory, and other resources. Inventory need not crash to slow down all of orders. Different problems call for different strategies:
| Problem | Strategy |
|---|---|
| One request waits too long | Timeout: bound the waiting period |
| A transient failure may soon recover | Retry: try again a limited number of times |
| Inventory keeps failing | Circuit breaker: temporarily stop normal calls |
| Inventory calls consume excessive resources | Isolation: bound resources for a category of calls |
| A noncritical dependency is unavailable | Graceful degradation: return a business-approved alternative |
These strategies need not all be enabled. Combine them according to operation semantics and failure conditions.
⏱ Timeouts and Retries: Bound Waiting Before Retrying
A timeout determines how long to wait. A retry determines whether to try again after a transient failure. They are different: unlimited retries only increase pressure on an already busy inventory service.
Run a slow inventory example
Create two minimal Express services using Node.js 22 or a newer compatible version and Express 5. This simulates read-only inventory queries, without deducting stock.
Project structure:
resilience-demo/
├── services/
│ ├── inventory.mjs
│ └── orders.mjs
└── package.json
Run in a new directory:
mkdir -p resilience-demo/services
cd resilience-demo
npm init -y
npm install express@5
Then create these files:
import express from 'express';
const app = express();
let failOnce = true;
app.get('/availability', async (req, res) => {
const mode = req.query.mode;
// Simulate a slow inventory endpoint
if (mode === 'slow') {
await new Promise(resolve => setTimeout(resolve, 1800));
}
// Fail the first attempt and recover on the second
if (mode === 'flaky' && failOnce) {
failOnce = false;
return res.status(503).json({ message: 'Inventory service temporarily unavailable' });
}
res.json({ available: 10 });
});
app.listen(3003, () => console.log('Inventory service: http://localhost:3003'));
import express from 'express';
const app = express();
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function queryInventory(mode) {
const url = `http://localhost:3003/availability?mode=${mode}`;
for (let attempt = 1; attempt <= 2; attempt++) {
try {
const response = await fetch(url, {
signal: AbortSignal.timeout(800)
});
if (response.ok) return await response.json();
// Retry only the simulated temporary unavailability; stop on other errors
if (response.status !== 503) {
throw new Error(`Non-retryable HTTP ${response.status}`);
}
} catch (error) {
// Retry timeouts and connection failures; rethrow other errors
if (error.name !== 'TimeoutError' && !(error instanceof TypeError)) {
throw error;
}
}
console.log(`Inventory query attempt ${attempt} failed`);
if (attempt < 2) await sleep(150);
}
throw new Error('Inventory query temporarily unavailable');
}
app.get('/inventory', async (req, res) => {
const mode = ['normal', 'slow', 'flaky'].includes(req.query.mode)
? req.query.mode
: 'normal';
try {
res.json(await queryInventory(mode));
} catch {
res.status(503).json({ message: 'Inventory query temporarily unavailable; try again later' });
}
});
app.listen(3002, () => console.log('Order service: http://localhost:3002'));
Open two terminals and start from the project root:
node services/inventory.mjs
node services/orders.mjs
Visit these addresses in a browser and observe:
| URL | Expected result | Reason |
|---|---|---|
http://localhost:3002/inventory?mode=normal | Returns {"available":10} | Inventory responds normally |
http://localhost:3002/inventory?mode=flaky | Even the first visit returns inventory | First attempt receives 503; second succeeds |
http://localhost:3002/inventory?mode=slow | Returns 503 with a message | Both attempts exceed 800 milliseconds |
flaky fails only the first query in that mode after inventory starts. Restart inventory before testing if you already used it.
Each attempt waits at most 800 milliseconds, with at most two attempts and a 150-millisecond pause. 800 milliseconds is the timeout per attempt, not an overall endpoint duration limit. Real projects also need a total budget including retries and delays.
Inventory may continue processing even after orders stops waiting. Do not copy this read-only retry code directly into order creation, reservations, or charges. Those writes require idempotency and outcome queries, discussed earlier.
🧩 Circuit Breakers: Pause Calls During Persistent Failure
Timeouts bound individual waits, but repeated waiting and retries still waste resources if inventory remains unavailable.
A circuit breaker stops ordinary calls and fails fast when failures meet a configured condition over time. After a delay, it permits a few probes to see whether the dependency has recovered.
courseComponents.mermaid.loading
The names can be confusing: closed allows normal calls; open temporarily blocks them.
For example, frequent inventory timeouts during an observation window open the circuit. Requests then need not wait on inventory each time. After the recovery interval, successful probes allow normal calls again.
Circuit breakers do not repair inventory or necessarily open after one failure. Production configuration needs suitable windows, failure ratios, minimum request counts, and probe limits. Here we focus on state transitions without adding a library.
🛡 Isolation: Preserve Resources for Other Order Operations
Even with timeouts, high concurrency can leave many requests waiting on inventory. Isolation limits how much dependency calls affect other operations.
Suppose orders provides order creation and order history:
- Creation depends on inventory.
- History reads only order-owned data.
Unlimited waiting inventory requests can exhaust connections or other shared resources and disrupt history too.
A simple strategy permits at most 20 in-flight inventory queries. Excess queries fail immediately with a temporarily busy response rather than queueing indefinitely, preserving resources for other functions.
Twenty is an example, not a universal setting. Choose limits based on capacity. Unlike rate limiting, which bounds request counts over time, isolation emphasizes preventing one category of work from exhausting shared resources.
🔄 Graceful Degradation: What Can Continue Without a Dependency?
Graceful degradation provides a business-approved simplified result when a dependency is unavailable, rather than making every feature unavailable.
| Feature | Handling an inventory outage |
|---|---|
| Real-time stock on product pages | Temporarily hide the quantity and suggest refreshing later |
| Noncritical recommendations | Temporarily return an empty list |
| Order creation with reservation | Never pretend stock was reserved |
| Payment charging | Never pretend a charge succeeded or failed |
Therefore, degradation does not turn every error into success. Critical operations affecting money, stock, and order state need explicit processing or unavailable states and a recovery path.
⚖️ Combining Strategies
One failure may require several mechanisms, but retries should not be stacked unconditionally.
| Scenario | Consider first | Avoid |
|---|---|---|
| Transient read-only timeout | Per-attempt timeout, bounded retries, total budget | Unlimited retries |
| Persistent inventory failure | Timeout, circuit breaker, fail fast | Flooding the failing dependency |
| Many inventory queries waiting together | Concurrency isolation, bounded queue | Exhausting other features' resources |
| Temporary product-page dependency failure | Hide live stock and display a message | Displaying unconfirmed live quantities |
| Reservation timeout | Query with the original business identifier before deciding | Repeated deductions or fabricated success |
Distinguish whether the service can respond from whether the business outcome is correct. Fault tolerance controls failure impact; it cannot declare an unknown operation successful or failed.
Later, observability uses logs, metrics, and traces to evaluate these protections.
❓ Knowledge Check
Q1: Does an order timeout guarantee inventory stopped processing?
No. Aborting the caller's wait does not cancel downstream work. Write outcomes especially need verification.
Q2: Why not retry every failure?
Insufficient stock and invalid parameters usually do not improve on immediate retry. Even transient errors need attempt and duration limits to avoid adding load during failures.
Q3: How do circuit breakers differ from isolation?
Circuit breakers pause normal calls during persistent dependency failure. Isolation limits resource usage by a category of calls and remains useful even without complete failure.
🧪 Exercise
- Run both Express services and visit
normal,flaky, andslow. Observe responses and retry logs. - Change the slow delay from 1800 to 500 milliseconds. Visit
slowagain and explain the difference. - Explain why retrying a timed-out inventory query may be appropriate while retrying a reservation in the same way is unsafe.
- During a persistent inventory outage, explain the separate roles of circuit breaking, isolation, and product-page degradation.
Acceptance criteria: Observe timeouts and bounded retries; distinguish failed queries from unknown write outcomes; explain the limits of circuit breakers, isolation, and degradation.
🎉 Congratulations on completing this article! You can now protect orders when inventory becomes slow or unavailable and choose appropriate fault tolerance strategies for different operations.
Distributed Transactions and Data Consistency
Understand why cross-service transactions cannot simply roll back together, and learn about Sagas, eventual consistency, compensation, and recovery through orders, inventory, and payments.
Security
Understand user identity propagation, service authentication, and business authorization through order queries and stock reservations.
