The Pattern Map
Cloud Resilience Patterns and the GoF Patterns Inside Them
October 26, 2026 · 16 min read
Design Patterns, Cloud, Resilience, C#, Python, Swift, Azure
This post is part of The Pattern Map, my series tracing design patterns from the Gang of Four, through the cloud, to the AI era. The GoF posts covered patterns for objects talking to objects in one process. This is the first of three cloud posts, and it's about what happens when the thing you're calling is on the other side of a network and might not answer.
The theme of the series is "same patterns, new clothes," and resilience patterns fit it better than I expected. A circuit breaker is the State pattern. A timeout is a Decorator. An idempotency key only works because a request is treated as a Command with an identity. The new part isn't the structure. It's the failure modes they're shaped around.
| Cloud pattern | GoF ancestor | What it adds |
|---|---|---|
| Retry with backoff and jitter | Decorator (+ Strategy for the backoff) | Time, randomness, a limit |
| Timeout | Decorator | A deadline on a call that might never return |
| Circuit breaker | State (wrapped in a Proxy) | Memory of recent failures |
| Bulkhead | Proxy, loosely | A hard cap on how much of you one dependency can consume |
| Idempotency key | Command | A request with an identity, so a repeat is recognizable |
Why this matters: two Azure incidents in one week
At the end of September, Azure published two post-incident reviews within a few days of each other, and between them they hit almost every pattern in this post.
September 29, Sweden Central (Azure OpenAI and AI services). Per Microsoft's review, a planned deployment of an internal service cleared its caches during peak hours. Two defects meant most lookups bypassed the cache anyway, and backend traffic rose to about 20 times normal. The backend's health checks depended on reaching the database, so instances that couldn't get a connection failed their checks and were "automatically restarted by design," which made things worse. The mitigation was to make the health check stop depending on the database. The follow-ups include more throttling and rate limiting and partitioning the cache.
September 30 to October 1, network gateways in multiple regions. A paused platform update resumed across regions and overloaded the regional control plane, which was already slower because of an earlier change. Restarting ExpressRoute gateway instances were marked healthy before their configuration was ready, so the update moved on to their redundant partners too soon. Microsoft's follow-ups: make paused updates resume through staged rollout, strengthen the health checks, and improve control plane throttling and load shedding.
Microsoft doesn't use the phrase in either review, but this is what people call a thundering herd: lots of things doing the same expensive thing at the same moment. Synchronized restarts, a cold cache, an update that resumed everywhere at once. Every pattern below exists to stop one of those from turning into the next.
Retry with backoff and jitter
I wrote a whole post on this in 2024: the retry pattern with higher-order functions, with exponential backoff and full jitter in C#, Python and TypeScript. I won't repeat it. The GoF view: a retry wrapper is a Decorator around a function, and the backoff formula is a Strategy you can swap.
Three things I'd add now:
- Retry at one layer only. If the app retries 3 times, the API it calls retries 3 times, and the service behind that retries 3 times, one user tap can become 4 × 4 × 4 = 64 calls on the bottom layer. That's how retries turn a blip into an outage.
- Honor
Retry-After. When a service returns 429 or 503 with aRetry-Afterheader, it's telling you exactly how long to back off. Use that instead of your own formula. - Only retry what's safe to repeat. Microsoft's .NET resilience docs point out that the standard handler retries every HTTP method by default, and that retrying a POST "could lead to data duplication." That's what idempotency keys, later in this post, are for.
Timeout: a Decorator with a deadline
A call without a timeout is a promise to wait forever. A timeout wraps the call (Decorator again) and gives up after a deadline.
There are two kinds, and you usually want both: a per-attempt timeout so one slow try doesn't eat the budget, and a total timeout so retries can't stretch a request past what the caller will wait.
In Python 3.11+ it's built in:
async def with_timeout(coro_fn, *args, seconds: float, fallback):
try:
async with asyncio.timeout(seconds):
return await coro_fn(*args)
except TimeoutError:
return fallback
In C#, Task.WaitAsync does the same job for a task that doesn't take a cancellation token:
try { return await SlowRecs(id).WaitAsync(TimeSpan.FromMilliseconds(500)); }
catch (TimeoutException) { return "recs unavailable"; }
One caution: WaitAsync stops waiting; it doesn't stop the work. If the operation accepts a CancellationToken, pass one with CancelAfter so the work actually stops.
Circuit breaker: the State pattern
If a dependency is down, retrying just adds load to something that's already struggling. A circuit breaker remembers recent failures and, past a threshold, stops calling for a while. Requests fail fast instead of piling up.
It has three states, and that's exactly the GoF State pattern: the object's behavior changes with its state, and each state is its own class.
- Closed: calls go through; count failures.
- Open: calls fail immediately until a cooldown passes.
- Half-open: let a probe through. Success closes the circuit; failure opens it again.
import time
class CircuitOpenError(Exception):
pass
class Closed:
def __init__(self, breaker):
self.breaker, self.failures = breaker, 0
def before_call(self):
pass # calls flow normally
def on_success(self):
self.failures = 0
def on_failure(self):
self.failures += 1
if self.failures >= self.breaker.failure_threshold:
self.breaker.transition(Open(self.breaker))
class Open:
def __init__(self, breaker):
self.breaker, self.opened_at = breaker, breaker.clock()
def before_call(self):
if self.breaker.clock() - self.opened_at >= self.breaker.reset_after:
self.breaker.transition(HalfOpen(self.breaker)) # let one probe through
else:
raise CircuitOpenError("circuit open, failing fast")
def on_success(self):
pass
def on_failure(self):
pass
class HalfOpen:
def __init__(self, breaker):
self.breaker = breaker
def before_call(self):
pass
def on_success(self):
self.breaker.transition(Closed(self.breaker))
def on_failure(self):
self.breaker.transition(Open(self.breaker))
class CircuitBreaker:
def __init__(self, failure_threshold=3, reset_after=30.0, clock=time.monotonic):
self.failure_threshold, self.reset_after, self.clock = failure_threshold, reset_after, clock
self.state = Closed(self)
def transition(self, new_state):
print(f" {type(self.state).__name__} -> {type(new_state).__name__}")
self.state = new_state
def call(self, fn, *args, **kwargs):
self.state.before_call() # may raise CircuitOpenError
try:
result = fn(*args, **kwargs)
except Exception:
self.state.on_failure()
raise
self.state.on_success()
return result
Driving it with a fake clock (so the demo doesn't wait 30 real seconds):
call 1: ConnectionError: backend down
call 2: ConnectionError: backend down
Closed -> Open
call 3: ConnectionError: backend down
call 4: CircuitOpenError: circuit open, failing fast
call 5: CircuitOpenError: circuit open, failing fast
Open -> HalfOpen
HalfOpen -> Closed
after 31s: ok
Calls 4 and 5 never touch the backend. That's the point.
The C# version has the same shape. The states are nested classes, and the breaker itself acts as a Proxy in front of the real call:
sealed class CircuitOpenException() : Exception("circuit open, failing fast");
interface IBreakerState
{
void BeforeCall();
void OnSuccess();
void OnFailure();
}
sealed class CircuitBreaker(int failureThreshold, TimeSpan resetAfter, Func<DateTimeOffset> clock)
{
private IBreakerState _state = null!;
public int FailureThreshold => failureThreshold;
public TimeSpan ResetAfter => resetAfter;
public DateTimeOffset Now => clock();
public void TransitionTo(IBreakerState next)
{
if (_state is not null) Console.WriteLine($" {_state.GetType().Name} -> {next.GetType().Name}");
_state = next;
}
public async Task<T> CallAsync<T>(Func<Task<T>> action)
{
_state ??= new Closed(this);
_state.BeforeCall();
try
{
var result = await action();
_state.OnSuccess();
return result;
}
catch (Exception e) when (e is not CircuitOpenException)
{
_state.OnFailure();
throw;
}
}
sealed class Closed(CircuitBreaker b) : IBreakerState
{
private int _failures;
public void BeforeCall() { }
public void OnSuccess() => _failures = 0;
public void OnFailure() { if (++_failures >= b.FailureThreshold) b.TransitionTo(new Open(b)); }
}
sealed class Open(CircuitBreaker b) : IBreakerState
{
private readonly DateTimeOffset _openedAt = b.Now;
public void BeforeCall()
{
if (b.Now - _openedAt >= b.ResetAfter) b.TransitionTo(new HalfOpen(b));
else throw new CircuitOpenException();
}
public void OnSuccess() { }
public void OnFailure() { }
}
sealed class HalfOpen(CircuitBreaker b) : IBreakerState
{
public void BeforeCall() { }
public void OnSuccess() => b.TransitionTo(new Closed(b));
public void OnFailure() => b.TransitionTo(new Open(b));
}
}
This is a teaching version: it counts consecutive failures and isn't thread-safe. Production breakers (Polly's, below) use a failure ratio over a sampling window and a minimum throughput, so a single failure on a quiet service doesn't trip them.
Bulkhead: one leak doesn't sink the ship
The name comes from ships: watertight compartments, so one breach floods one section, not the hull. In software, a bulkhead caps how many concurrent calls go to one dependency. If recommendations hang, they can tie up at most N workers. Everything else (profiles, checkout) still has room.
There isn't a clean GoF ancestor. The closest is a Proxy that rations access to the real object. What's new is the decision to reject when full rather than queue, because a queue in front of a dead dependency is just a slower way to fail.
import asyncio
class BulkheadFullError(Exception):
pass
class Bulkhead:
"""At most `max_concurrent` calls in flight; reject the rest instead of queueing forever."""
def __init__(self, max_concurrent: int):
self._slots = asyncio.Semaphore(max_concurrent)
async def run(self, make_call):
if self._slots.locked():
raise BulkheadFullError("no free slots, shedding load")
async with self._slots:
return await make_call()
Combined with the timeout above, four concurrent requests to a hanging recommendations service, with a bulkhead of 2:
recs unavailable
recs unavailable
rejected: no free slots, shedding load
rejected: no free slots, shedding load
profile 0
profile 1
profile 2
profile 3
Two calls get the timeout fallback, two are rejected immediately, and the profile calls, in their own compartment, are untouched.
In C#, SemaphoreSlim.Wait(0) is the "try, don't wait" check:
sealed class BulkheadFullException() : Exception("no free slots, shedding load");
sealed class Bulkhead(int maxConcurrent)
{
private readonly SemaphoreSlim _slots = new(maxConcurrent, maxConcurrent);
public async Task<T> RunAsync<T>(Func<Task<T>> action)
{
if (!_slots.Wait(0)) throw new BulkheadFullException(); // don't queue, reject
try { return await action(); }
finally { _slots.Release(); }
}
}
The Sweden Central review is a bulkhead lesson in reverse. A health check that depends on the database ties every instance's fate to one shared dependency. When the database struggled, every instance looked unhealthy, and restarting them added load to the very thing that was struggling.
Idempotency keys: a Command with an identity
Retries are only safe if doing something twice has the same effect as doing it once. Reads are naturally like that. "Charge this card" isn't. If the charge succeeds but the response is lost, the client can't tell the difference between "failed" and "succeeded, but I never heard back," so it retries, and the customer pays twice.
The fix: the client attaches a unique idempotency key to the request. The server stores the key with the result. A repeat with the same key gets the stored result instead of a second charge.
The GoF ancestor is Command: once a request is an object you can store and replay, you can also give it an identity and refuse to execute it twice. Stripe's API is the reference most people point to. Its docs recommend V4 UUIDs as keys, and say the server compares the parameters of a repeat to the original and returns an error if they differ.
import hashlib
import json
import uuid
class IdempotencyConflict(Exception):
pass
class IdempotentHandler:
"""Remembers (key -> request fingerprint, response). In production this is a table with a TTL."""
def __init__(self, handler):
self._handler = handler
self._seen: dict[str, tuple[str, dict]] = {}
def handle(self, idempotency_key: str, request: dict) -> dict:
fingerprint = hashlib.sha256(json.dumps(request, sort_keys=True).encode()).hexdigest()
if idempotency_key in self._seen:
seen_fingerprint, response = self._seen[idempotency_key]
if seen_fingerprint != fingerprint:
raise IdempotencyConflict("same key, different request body")
return response # replay: no second side effect
response = self._handler(request)
self._seen[idempotency_key] = (fingerprint, response)
return response
{'charge_id': 'ch_1', 'amount': 499} {'charge_id': 'ch_1', 'amount': 499} charges made: 1
rejected: same key, different request body
The C# version handles a subtlety the Python one skips: a retry that arrives while the original is still running. ConcurrentDictionary.GetOrAdd with a Lazy<Task<T>> makes both callers await the same execution:
sealed class IdempotentHandler<TRequest, TResponse>(Func<TRequest, Task<TResponse>> handler)
{
// Lazy makes concurrent duplicates share ONE execution. In production: a table with a unique key and a TTL.
private readonly ConcurrentDictionary<string, Lazy<Task<TResponse>>> _seen = new();
public Task<TResponse> HandleAsync(string idempotencyKey, TRequest request) =>
_seen.GetOrAdd(idempotencyKey, _ => new Lazy<Task<TResponse>>(() => handler(request))).Value;
}
var key = Guid.NewGuid().ToString(); // one key per user action
var results = await Task.WhenAll( // a retry racing the original
payments.HandleAsync(key, 499),
payments.HandleAsync(key, 499));
// ch_1 for 499 | ch_1 for 499 | charges made: 1
The server half is only useful if the client does its half, and this is where it matters for app developers. The key has to be created once per user action, not once per HTTP attempt. In Swift:
import Foundation
struct PurchaseAction {
// Created once when the user taps "Buy", NOT once per HTTP attempt.
let idempotencyKey = UUID().uuidString
let amountCents: Int
func makeRequest() -> URLRequest {
var req = URLRequest(url: URL(string: "https://api.example.com/v1/charges")!)
req.httpMethod = "POST"
req.setValue(idempotencyKey, forHTTPHeaderField: "Idempotency-Key")
req.httpBody = try? JSONEncoder().encode(["amount": amountCents])
req.timeoutInterval = 10
return req
}
}
let tap = PurchaseAction(amountCents: 499)
let first = tap.makeRequest()
let retry = tap.makeRequest() // the retry
print(first.value(forHTTPHeaderField: "Idempotency-Key") == retry.value(forHTTPHeaderField: "Idempotency-Key"))
// true
If the key were generated inside makeRequest(), every retry would look like a brand-new purchase, and the whole pattern would quietly do nothing.
Putting them together: a Decorator stack
Each pattern so far wraps a call. Stack them and you get a chain of Decorators, and the order matters. In .NET, Polly v8 makes the stack explicit. The first strategy you add is the outermost:
var pipeline = new ResiliencePipelineBuilder()
.AddTimeout(TimeSpan.FromSeconds(10)) // total budget, outermost
.AddRetry(new RetryStrategyOptions
{
ShouldHandle = new PredicateBuilder().Handle<HttpRequestException>().Handle<TimeoutRejectedException>(),
MaxRetryAttempts = 3,
BackoffType = DelayBackoffType.Exponential,
UseJitter = true,
Delay = TimeSpan.FromMilliseconds(100),
OnRetry = args => { Console.WriteLine($" retry {args.AttemptNumber + 1} after {args.RetryDelay.TotalMilliseconds:F0} ms"); return default; }
})
.AddCircuitBreaker(new CircuitBreakerStrategyOptions
{
ShouldHandle = new PredicateBuilder().Handle<HttpRequestException>(),
FailureRatio = 0.5,
MinimumThroughput = 4,
SamplingDuration = TimeSpan.FromSeconds(30),
BreakDuration = TimeSpan.FromSeconds(15)
})
.AddTimeout(TimeSpan.FromSeconds(2)) // per attempt, innermost
.Build();
var attempts = 0;
var result = await pipeline.ExecuteAsync(async token =>
{
attempts++;
await Task.Delay(10, token);
if (attempts < 3) throw new HttpRequestException("503 from upstream");
return "ok";
});
retry 1 after 96 ms
retry 2 after 75 ms
ok after 3 attempts
(Jitter means your delays will differ.) The retry sits outside the circuit breaker, so once the circuit opens, retries fail fast instead of hammering. The per-attempt timeout sits inside, so each try gets its own deadline, and the retry strategy is told to treat Polly's TimeoutRejectedException as retryable.
If you use HttpClient, you rarely need to build this yourself. Microsoft's AddStandardResilienceHandler() chains five strategies, outermost first: a rate limiter, a 30-second total timeout, a retry (3 attempts, exponential, with jitter), a circuit breaker, and a 10-second per-attempt timeout. That's this whole post in one line, which is exactly why it's worth knowing what each layer does before you trust the defaults.
In Python, Tenacity covers retry with backoff and jitter, and asyncio.timeout (Python 3.11+) gives you both deadlines. Same stack, same order:
import asyncio
from tenacity import (AsyncRetrying, retry_if_exception_type, stop_after_attempt,
wait_random_exponential)
attempts = 0
async def call_upstream() -> str:
global attempts
attempts += 1
await asyncio.sleep(0.01)
if attempts < 3:
raise ConnectionError("503 from upstream")
return "ok"
def log_retry(state):
print(f" retry {state.attempt_number} after {state.next_action.sleep * 1000:.0f} ms")
async def resilient_call() -> str:
async with asyncio.timeout(10): # total budget, outermost
async for attempt in AsyncRetrying(
stop=stop_after_attempt(4), # 1 try + 3 retries
wait=wait_random_exponential(multiplier=0.1, max=2), # backoff with full jitter
retry=retry_if_exception_type((ConnectionError, TimeoutError)),
before_sleep=log_retry,
reraise=True,
):
with attempt:
async with asyncio.timeout(2): # per attempt, innermost
return await call_upstream()
result = asyncio.run(resilient_call())
print(f"{result} after {attempts} attempts")
retry 1 after 36 ms
retry 2 after 91 ms
ok after 3 attempts
The nesting is the Decorator stack: the total timeout wraps the retry loop, and each attempt gets its own 2-second deadline inside it. Tenacity has no circuit breaker or bulkhead, so for those I've ended up with small classes like the ones above, which is part of why I wanted to understand them properly. To add the breaker here, make its call async and wrap call_upstream() with it inside the attempt, where Polly puts it.
What I took from the Azure reviews
Reading both reviews with this list in hand, three things stood out:
- Health checks are a dependency too. A check that calls the database turns a database problem into a restart storm. Check that this instance can do its job, not that everything downstream is fine.
- Anything that resumes all at once is a herd. Paused updates, restarts, cache expiry. Staged rollout is jitter for deployments.
- Load shedding is a feature. Both reviews list more throttling and rate limiting as follow-ups. A bulkhead that rejects is better than a queue that drowns.
Next in the series: messaging, where queues, outboxes and sagas take these ideas from "one call" to "one business process."
Further reading
- Azure Architecture Center, cloud design patterns catalog
- Azure Architecture Center, Retry pattern
- Azure Architecture Center, Circuit Breaker pattern
- Azure Architecture Center, Bulkhead pattern
- Azure Architecture Center, Rate Limiting pattern
- Azure Architecture Center, transient fault handling best practices
- Microsoft Learn, building resilient HTTP apps with Microsoft.Extensions.Http.Resilience (the standard handler's strategy order and defaults)
- Polly docs, circuit breaker strategy
- Stripe API reference, idempotent requests
- AWS Builders' Library, timeouts, retries and backoff with jitter
- Martin Fowler, CircuitBreaker
- Azure status history, post-incident reviews (tracking IDs 7QL5-Z50, Sep 29, 2026, and 7Q30-010, Sep 30 – Oct 1, 2026)
Thoughts on this?
Tell me on X: @bobbyencoded · Share this post on X
Want more like this? Subscribe to The Decode, a weekly email on the AI and developer news worth your time.