Practical Patterns for Distributed Systems: Sagas, Circuit Breakers and Gateways
Sagas, circuit breakers, API gateways and backends for frontends each fix one distributed systems problem, and each adds cost to a system that doesn't have it.
When an application is split into services, calls that used to happen inside one process start crossing the network. Data that one transaction used to change now lives in several services, a slow service can stall everything that calls it, and every client has to assemble its screens from many endpoints. Each of those problems has a well-known pattern: the saga, the circuit breaker, and the API gateway with its variant, the backend for frontend.
I think each pattern is worth its cost only when a system has the problem it solves. Every one of them adds something to build, run and understand, and a team that adopts all of them by default can end up with a system that’s harder to change than the one it started with. Whether you have the problem depends on how your services call each other today, so I’d find that out before choosing a pattern.
A chain of synchronous calls
Take a hypothetical online store, where placing an order involves three services. A first version of the order flow often looks like this: the API gateway receives POST /orders, and OrderService creates an order record, charges the customer through PaymentService, reserves the items through InventoryService, and confirms the order.
In code, the whole flow is one function:
async function handleOrder(request) {
const order = await createOrderRecord(request.details);
const payment = await paymentService.charge(order.id, request.paymentInfo);
if (!payment.succeeded) {
await cancelOrder(order.id);
throw new Error("Payment failed");
}
const reservation = await inventoryService.reserveItems(order.id, order.items);
if (!reservation.succeeded) {
// If this refund fails, the customer stays charged for an order that was
// never reserved, and nothing tries the refund again.
await paymentService.refund(payment.id);
await cancelOrder(order.id);
throw new Error("Inventory unavailable");
}
await confirmOrder(order.id);
return { status: "confirmed", orderId: order.id };
}
Inside one process this would be ordinary code. Across three services, each await is a network call that can fail, time out, or succeed without the caller ever hearing back, and the function handles few of those cases well. The serverless post looks at the same kind of chain when each service is a Lambda function.
Keeping data consistent across services with sagas
One case handleOrder handles badly is a charge that succeeds followed by a reservation that fails, which leaves the customer paying for an order the store can’t fill. The code tries a refund, but the refund is one more network call, and if it fails, the customer stays charged and nothing tries again. Inside one database, a transaction would roll both changes back together. Services that each own their data don’t share a transaction, though. Two-phase commit is the classic protocol for transactions across databases, but Chris Richardson’s description of the saga pattern starts from the assumption that it isn’t an option.
A saga replaces the single transaction with a sequence of local transactions, one per service. Each service commits its own step and then publishes an event that starts the next one. Every step that might need undoing after a later step fails gets a compensating action, such as a refund for a charge. Hector Garcia-Molina and Kenneth Salem described sagas in 1987 as a way to break up long-running transactions inside one database, and the same idea works across services.
Sagas come in two forms, choreographed and orchestrated. In the choreographed form, each service reacts to the others’ events and nothing coordinates them centrally:
OrderServicecreates the order asPENDINGand publishesOrderCreated.PaymentServicereceivesOrderCreated, charges the customer, and publishesPaymentProcessedorPaymentFailed.InventoryServicereceivesPaymentProcessed, reserves the items, and publishesInventoryReservedorInventoryOutOfStock.OrderServicereceives the outcome and marks the orderCONFIRMEDorFAILED. If the items were out of stock after the payment went through, it also publishesRefundPayment.
In the orchestrated form, a coordinator tells each service which step to run and runs the compensations itself. Orchestration is often easier to follow, because the whole sequence is written down in one place, while a choreographed saga exists only as a set of subscriptions spread across the services. The cost is one more component to run and keep available.
Either way, a saga doesn’t give you everything a database transaction did. It isn’t isolated, so while it runs, other requests can see the order as PENDING, or see a charge that is about to be refunded. Garcia-Molina and Salem accepted that on purpose, and Richardson lists the lack of isolation among the pattern’s drawbacks.
Nothing is undone automatically, either. Someone has to write each compensation, and because many message brokers can deliver the same event more than once (Amazon SQS standard queues are one example), each step has to be safe to run twice. The order of the steps matters too. Releasing a reservation is invisible to the customer, but a refund shows up on their statement, so I’d reserve the stock before charging the card and leave the step that’s hardest to undo for last.
A saga is the wrong choice when the data could live in one database. If the order, the payment record and the stock count belong to one service, a local transaction is atomic and isolated without any compensations, and I’d question a split that forces a saga onto data that always changes together. It’s also a poor fit when an intermediate state must never be visible, such as an account balance that must not appear overdrawn even briefly, because a saga can’t hide its steps from other readers.
Stopping cascading failures with circuit breakers
A chain of synchronous calls also causes trouble when no call fails outright. If InventoryService slows down, every OrderService request that’s waiting on it ties up a connection and memory until the call returns, and if enough requests pile up, OrderService stops responding too, including to requests that never needed inventory. A dependency that hangs does more damage than one that refuses connections, because a refusal comes back at once and frees the caller.
A circuit breaker wraps the call and stops making it once the call is clearly failing. Martin Fowler’s description of the pattern, which credits Michael Nygard’s book Release It! with popularizing it, has three states. While the breaker is closed, calls go through and the breaker counts the failures. Once the failures pass a threshold, it opens, and from then on calls fail immediately without touching the network. After a timeout it moves to half-open and lets a trial call through. If the trial succeeds, the breaker closes again, and if it fails, the breaker goes back to open.
In the order flow, the breaker wraps OrderService’s call to InventoryService. Once it opens, an order that needs a reservation fails at once with a message to try again later, OrderService keeps responding, and InventoryService gets room to recover.
A breaker only counts failures, so a call that hangs has to time out before it counts as one. I’d set that timeout before adding the breaker. Without it, the breaker never sees the slow calls that cause the pile-up, and Microsoft’s guide to the pattern warns that a breaker might not fully protect an application from a service with a long timeout.
A circuit breaker adds little once the call has moved onto a queue, as it does in the saga above. A slow consumer only makes the queue longer, and the queue’s retries and dead-letter handling cover most failures. Microsoft’s guide makes the same point about event-driven systems. It also says a breaker may not suit calls to local resources, such as an in-memory data structure, and shouldn’t be used as a substitute for handling errors in the application’s own logic.
Even where a breaker fits, opening it has a cost. When every request needs the dependency, an open breaker turns slowness into a fast error for every user. That’s usually better for the system than a pile-up, but it’s a decision to make on purpose, with a fallback if one exists, such as showing stale data.
Serving many clients with an API gateway or a backend for frontend
The services also have to serve more than one kind of client, and each client wants something different. The web app needs order details, the mobile app needs those plus shipping status, and a partner integration only needs a confirmation. If every client calls OrderService, PaymentService and InventoryService directly, each one makes several calls per screen, fetches fields it doesn’t use, and repeats the same assembly logic. Every client also has to know where every service lives, so moving a service means changing every client.
An API gateway puts one entry point in front of the services. It routes each request to the right service, and it’s the usual place for authentication, rate limiting and TLS termination, along with some light aggregation. Clients see one address, and the services behind it can move without the clients noticing.
A single gateway still offers every client the same API, though. A backend for frontend, or BFF, gives each kind of client its own gateway. Sam Newman, who wrote up the pattern in 2015, describes a BFF as tightly coupled to one user experience and usually maintained by the same team that builds that user interface. The mobile BFF returns what the mobile screens need, assembled from whichever services have the data, and the web BFF does the same for the web app. Because one team owns both the client and its BFF, the two can change together.
With one client and a handful of services, a gateway is one more network hop and one more thing to deploy, and I’d let the client call the services directly until that becomes a problem.
The opposite problem comes with many clients. A single gateway serving many different clients tends to collect client-specific code until every team is waiting on changes to it, and Newman says general-purpose edge APIs like that have repeatedly led to bloated code. BFFs avoid that by splitting the gateway per client, at the cost of some duplicated aggregation logic between them. Newman is fairly relaxed about that duplication and would extract shared code only once it keeps recurring. He also notes that a web-only product with little server-side aggregation may not need a BFF at all.
Knowing your system’s dependencies before you choose a pattern
Each of these choices starts from facts about the system: which services one order touches, which of those calls are synchronous, and which fields each client reads. A team that guesses at those facts can end up putting a breaker on a call that was never slow, or writing a saga for data that could have lived in one database.
Those facts are harder to get than they look. Architecture diagrams show the system as someone drew it, often before the last few months of changes. Traces show the calls that happened, for the requests that were sampled. The code contains every call, including ones no recent request exercised, but it’s spread across every service’s repository, and a change in one service can break a consumer in another that nobody knew about. Finding the unknown unknowns walks through one such case, a field rename that broke a dashboard days later.
So before adopting one of these patterns, I’d list the calls in the flow it would change, mark which of them are synchronous, and find every client of the endpoints involved. That list usually shows whether the pattern is needed.
Each pattern also makes the system harder to read. The synchronous chain was one function that a reader could follow from top to bottom. After a saga, a breaker and two BFFs, the same order passes through a message broker, event handlers in three services and a BFF, and no single file shows the whole flow. That’s a good trade when each part fixes a failure the system actually has. It also means that knowing what the system does gets harder with every pattern you add, so I’d get that picture right before adding the next one.