Fault Tolerance and Reliability

Use order-to-inventory calls to learn timeouts, bounded retries, circuit breakers, isolation, and graceful degradation, preventing downstream failures from spreading.

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

ProblemStrategy
One request waits too longTimeout: bound the waiting period
A transient failure may soon recoverRetry: try again a limited number of times
Inventory keeps failingCircuit breaker: temporarily stop normal calls
Inventory calls consume excessive resourcesIsolation: bound resources for a category of calls
A noncritical dependency is unavailableGraceful 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'));

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:

URLExpected resultReason
http://localhost:3002/inventory?mode=normalReturns {"available":10}Inventory responds normally
http://localhost:3002/inventory?mode=flakyEven the first visit returns inventoryFirst attempt receives 503; second succeeds
http://localhost:3002/inventory?mode=slowReturns 503 with a messageBoth 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.

FeatureHandling an inventory outage
Real-time stock on product pagesTemporarily hide the quantity and suggest refreshing later
Noncritical recommendationsTemporarily return an empty list
Order creation with reservationNever pretend stock was reserved
Payment chargingNever 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.

ScenarioConsider firstAvoid
Transient read-only timeoutPer-attempt timeout, bounded retries, total budgetUnlimited retries
Persistent inventory failureTimeout, circuit breaker, fail fastFlooding the failing dependency
Many inventory queries waiting togetherConcurrency isolation, bounded queueExhausting other features' resources
Temporary product-page dependency failureHide live stock and display a messageDisplaying unconfirmed live quantities
Reservation timeoutQuery with the original business identifier before decidingRepeated 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

  1. Run both Express services and visit normal, flaky, and slow. Observe responses and retry logs.
  2. Change the slow delay from 1800 to 500 milliseconds. Visit slow again and explain the difference.
  3. Explain why retrying a timed-out inventory query may be appropriate while retrying a reservation in the same way is unsafe.
  4. 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.