Circuit Breaker Pattern on Azure

Your payment service is down. A customer has just pressed “Place order”. What happens next?

The textbook answer is the circuit breaker pattern. Detect the failures, stop calling the broken service, and give it time to recover. Three states: closed, open, half-open. Every explanation of the pattern ends there, and so does most code I review.

But the breaker answers only one question: when do we stop calling? It says nothing about the order. The customer does not care that your circuit is open. They care whether their order went through.

So I built it. One order API, one payment provider that fails on command, and four ways to connect them on Azure. Then I broke the provider and counted. The sample is on GitHub: circuit-breaker-azure. One azd up deploys it.

The setup

The Orders API is an Azure Function App on Flex Consumption. It saves every order to Table Storage first and then tries to charge. The payment provider is a second Function App, a stub with five modes: healthy, down, slow, slow-success, and flaky. The stub counts every call it receives. That count proves what a breaker stopped.

A query parameter selects the path:

  1. naive: a plain HttpClient. No breaker.
  2. breaker: a Polly circuit breaker inside the Function App process.
  3. gateway: Azure API Management holds the breaker. The app has none.
  4. fallback: the breaker from path 2, plus a Service Bus queue for payments that could not be made.

Paths 1 to 3 fail the order when the payment fails. Only path 4 answers the opening question.

Without a breaker, slow is worse than down

First, the baseline. A provider that is down answers quickly with an error. That is annoying, but cheap. The expensive failure is a slow provider. Every caller waits, holds a connection, and holds memory. Then the error arrives anyway.

I set the stub to answer after eight seconds with a 503 and sent 40 orders, eight at a time, through the naive path.

Naive path, provider answers 503 after 8 sMeasured
Orders failed40 of 40
Latency per order, p50 / p958,240 ms / 8,273 ms
Time to work through 40 orders41.3 s
Calls that reached the provider40

A healthy order in the same setup takes 232 ms at p50. During the slow outage, every order held its connection 35 times longer, only to fail.

Every one of those calls reached a provider that was already in trouble. This is how one failing service takes its callers down with it. The callers are not broken. They are waiting.

The circuit breaker pattern in the process

In .NET, the circuit breaker pattern is a few lines. Microsoft.Extensions.Http.Resilience puts a Polly pipeline on an HttpClient:

services.AddHttpClient(PaymentClient.Breaker, client =>
{
client.BaseAddress = new Uri(settings.PaymentUrl);
})
.AddResilienceHandler("payment", (pipeline, context) =>
{
pipeline.AddCircuitBreaker(new HttpCircuitBreakerStrategyOptions
{
FailureRatio = 0.5,
MinimumThroughput = 10,
SamplingDuration = TimeSpan.FromSeconds(10),
BreakDuration = TimeSpan.FromSeconds(15)
});
pipeline.AddTimeout(TimeSpan.FromSeconds(2));
});

Two details matter more than the three states.

The timeout is half of the pattern. A breaker counts failures. A call that hangs for eight seconds is not a failure until something says so. The two-second attempt timeout sits inside the breaker, so every timed-out call counts in the sampling window. Without it, the breaker watches slow calls and does nothing.

The threshold is not a count. “Failures greater than threshold” is the usual phrasing. A real breaker opens on a failure ratio, over a sampling window, and only after a minimum number of calls. Three failures out of three calls at 03:00 should not open a circuit. The defaults of the standard resilience handler show the intent: a 10 percent failure ratio, a minimum throughput of 100 calls, a 30-second sampling window, and a 5-second break. My demo values are much smaller, so the circuit trips within seconds.

It also matters what counts. The HTTP breaker counts 5xx, 408, 429, timeouts, and connection errors. A 400 or a 404 is the caller’s problem. It should never open a circuit.

Same slow provider, 200 orders, through the breaker path:

Breaker path, same slow providerMeasured
Orders sent200
Calls that reached the provider30
Rejected by an open circuit170
Latency per order, p50 / p95199 ms / 2,215 ms
Time to work through 200 orders13.3 s
Function App instances that answered4

The breaker stopped 85 percent of the calls. A rejected order came back in 199 ms, as fast as a healthy one. Five times the orders took a third of the time of the naive run. The p95 of 2.2 seconds is the price of learning: the 30 calls that ran into the attempt timeout before the circuits opened.

One breaker per instance

Look at the last row. The breaker lives in one process’s memory. Flex Consumption scales out under load, and every new instance starts with a closed circuit. Each instance has to learn about the outage on its own. In my run, four instances answered, and together they let 30 calls through before all four circuits were open.

Every response from the sample carries an instance id and the breaker state of that instance. Under load, you see both change from call to call. With N instances, the provider receives up to N times the calls you planned for, and N probes when the break ends. That is fine for most systems. Still, you should know it before you promise the payment team that “the breaker protects you”.

The circuit breaker pattern at the gateway

API Management moves the breaker out of the app. A backend resource carries the rule:

circuitBreaker: {
rules: [
{
name: 'paymentBreaker'
failureCondition: {
count: 5
interval: 'PT10S'
statusCodeRanges: [ { min: 500, max: 599 } ]
}
tripDuration: 'PT15S'
acceptRetryAfter: false
}
]
}

While the circuit is tripped, the gateway answers 503 itself, and the backend receives nothing. Every consumer of the API gets the protection, in any language, without a library. That is the appeal.

The limits are worth reading before you rely on it:

  • There is no half-open state. After the trip duration, the full load returns at once. If the provider is still down, failures must add up again before the circuit trips again.
  • A backend takes one rule.
  • Gateway instances do not synchronize. Each applies the rule to what it has seen, so tripping is approximate.
  • The Consumption tier does not support it.
  • A 503 from the gateway looks like a 503 from the backend. The sample tells them apart with a marker header on the stub’s responses.
Gateway path, provider downMeasured
Orders sent200
Calls that reached the provider8
Answered by the gateway with 503192
Latency per order, p50 / p95198 ms / 227 ms

The rule says five failures. Eight calls got through because eight were in flight when the fifth failure was counted. That is what approximate means in practice. The burst took 5.1 seconds, shorter than the trip duration, so the circuit tripped once.

In-process or gateway? I use both for different reasons. The in-process breaker protects the caller: its threads, its memory, its latency. The gateway breaker protects the backend and every client you do not control. Neither one protects the order.

The breaker opens, the order still exists

At this point the provider is safe and the callers fail fast. The customer still gets an error. In paths 1 to 3 the order ends as PaymentFailed, and the best the API can do is a 503 with a Retry-After header.

For a payment, there is a better answer. Accept the order. Park the payment. Tell the customer the truth.

[DIAGRAM 3: images/fallback-flow.png] Alt text: The fallback flow of the circuit breaker pattern when the payment service is down Caption: The breaker decides when to stop calling. The fallback decides what happens to the order.

In the fallback path, a rejected or failed charge puts a message on a Service Bus queue. The order becomes PaymentPending and the API answers 202. A Service Bus triggered function settles the payment later, through the same breaker.

I took the provider down, placed 100 orders, and brought the provider back.

Fallback pathMeasured
Orders accepted with 202 during the outage100 of 100
Latency per order, p50 / p95209 ms / 575 ms
Orders PaymentPending during the outage100
All 100 orders Paid after recovery11.3 s
Charges at the provider100, no duplicates

No order lost. No customer waiting. The provider received 29 failed calls before the four circuits opened, then nothing until it was healthy again. But the fallback brings three problems of its own, and the breaker makes one of them worse.

Fast failure burns the delivery count

A queue consumer that fails throws an exception. Service Bus then redelivers the message. During an outage, that normally takes a while, because each attempt waits for a timeout.

With an open breaker, each attempt fails without a single network call. The message returns at once, fails at once, and uses up the queue’s MaxDeliveryCount of 10 in about a second. The breaker that protects the provider drains the queue into the dead-letter queue. The provider recovers a minute later, and every parked payment is already dead.

20 parked payments, provider downConsumer throwsConsumer reschedules
Dead-lettered20 of 20, within 1.5 s0
Waiting in the queue during the outage020, scheduled
Orders after recovery20 still PaymentPending, forever20 Paid after 20.1 s

The fix is to stop treating “circuit open” as a failure of the message. The consumer sends a copy that becomes visible after the break duration, plus jitter, and completes the original:

var delay = wait + TimeSpan.FromMilliseconds(Random.Shared.Next(500, 3000));
// Send first, complete second. A crash in between produces a duplicate
// message, never a lost one.
await _sender.SendMessageAsync(NewPendingMessage(order, attempt + 1, "reschedule", delay), ct);
await actions.CompleteMessageAsync(message, ct);

After 20 attempts the function dead-letters the message on purpose, with a reason a human can read.

A timeout is not a failure

The two-second timeout tells you that you stopped waiting. It does not tell you what the provider did. In slow-success mode the stub charges the card after four seconds. The caller gave up after two.

So the order is PaymentPending and the money has already moved. When the settlement runs, it charges again. Unless every call carries an idempotency key. In the sample, the key is the order id, on the first attempt and on every later one.

Provider charges after 4 s, caller gives up after 2 sMeasured
Orders PaymentPending after the timeout8 of 8
Charges already made at that moment8
Later settlement attempts that found the charge16
Charges in the end8

Sixteen times the settlement tried to charge an order that was already paid. Sixteen times the key said no.

Without the key, the fallback turns an outage into double charges. I would rather have the outage. I covered the consumer side of this in Idempotent Consumers on Azure.

Two writes, one gap

The API saves the order as pending and then sends the queue message. Those are two operations. A crash between them leaves a pending order with no message behind it. The sample marks the spot in a comment and leaves it open. Production code closes it with a transactional outbox.

Recovery is slower than the outage

One more measurement. After the provider is healthy again, how long does a caller keep getting errors?

After the provider recoveredMeasured
First paid order14.8 s later
Orders rejected while the provider was healthy12
Break duration15 s

A breaker cannot see recovery. It can only wait and probe. The break duration is a trade-off: short means more probes against a struggling service; long means rejected customers after it is fine. Pick the number with the team that owns the dependency, and alert on every transition. The sample logs one line each time a circuit opens, half-opens, or closes, with the instance id. The KQL is in docs/queries.kql.

Where this is the wrong answer

The circuit breaker pattern isn’t free, and it doesn’t fit everywhere.

  • Low traffic. A ratio over ten calls is noise. If the dependency sees a handful of calls a minute, a timeout and a retry with backoff do the job.
  • A fallback that lies. Parking a payment works because a payment can happen later. A stock check, a fraud decision, or a price cannot. If there is no honest “later”, fail fast and say so.
  • One breaker for everything. A breaker per dependency, and per tenant or region where they fail apart. A shared breaker lets one bad endpoint cut off the healthy ones.
  • Retries on top. A retry inside the breaker multiplies load at the worst moment. Three retries on every call turn a struggling provider into a dead one before the circuit opens. Keep retry counts low and budgets tight.
  • Non-transient errors. A wrong API key fails every call. The breaker opens, half-opens, opens again, forever. That needs an alert, not a pattern.

Wrapping up

The three states are the easy part of the circuit breaker pattern. A library gives you them in ten lines, and API Management gives you two of them in a Bicep block.

The work is around the breaker. A timeout, so slow counts as failed. A threshold that is a ratio. The knowledge that every instance has its own circuit. And above all, a decision about the thing the customer asked for. In my sample, that decision is a queue, a delayed retry, and an idempotency key.

The breaker opens. The order still exists. Decide what happens to it before the outage does.

The code, the Bicep, and the test script are in the circuit-breaker-azure repository.

Leave a Reply