Architecture Patterns in Practice
How Services Talk: API Gateway, BFF, Pub/Sub, Event-Driven and Rate Limiting in Practice
October 7, 2026 · 26 min read
Software Architecture, Design Patterns, C#, Python, API Gateway, Backend for Frontend, Event-Driven Architecture, Rate Limiting, Distributed Systems
This post is part of Architecture Patterns in Practice, a series that takes the patterns named in my architecture patterns map and gives each one runnable code. This is part 3, and it covers the question "how do the parts talk to each other?"
Every pattern here sits on one trade-off. Synchronous calls are simple to write and simple to debug, but they couple services in time: if the service you call is down, so are you. Messages and events decouple services in time, but the system gets harder to follow, and data is only eventually consistent. None of the patterns below makes that trade go away. They help you choose where to pay it.
| Pattern | The problem it solves | The old idea underneath |
|---|---|---|
| API gateway | Clients shouldn't know your internal topology | Facade, with a routing Proxy |
| Backend for Frontend | Different clients need different shapes of the same data | One Facade per client |
| Publish/subscribe | One thing happening should trigger several independent reactions | Observer, with a broker in the middle |
| Event-driven architecture | Services should change and fail independently | Observer at system scale |
| Rate limiting | One caller shouldn't be able to drown you | Protection Proxy, with a swappable algorithm (Strategy) |
All the code below runs as is: C# as .NET 10 file-based apps (dotnet run file.cs), Python with 3.12 and only the standard library. The "services" are in-memory functions, so you can see the pattern without a cluster.
API gateway
The problem. You have five services. A mobile app that calls all five directly needs to know five hostnames, handle five auth schemes, and break whenever you split or merge a service. Every service also re-implements token validation, request IDs, CORS and logging.
The pattern. Put one front door in front of everything. Clients call the gateway. The gateway routes each request to the right internal service and handles the cross-cutting work once. Microsoft's catalog splits this into three jobs: gateway routing (one endpoint, many services), gateway offloading (auth, TLS, rate limits in one place) and gateway aggregation (one client call fans out to several services).
The version below does routing and offloading. Note two details that matter more than the routing: it validates the token once and passes a trusted user ID inward, and it does not forward client headers blindly. Otherwise a client could send its own X-User-Id header and become anyone.
Python
import uuid
from dataclasses import dataclass, field
from typing import Callable
@dataclass
class Request:
path: str
headers: dict[str, str] = field(default_factory=dict)
@dataclass
class Response:
status: int
body: str
# Internal services. Clients never see these names or addresses.
def orders_service(req: Request) -> Response:
return Response(200, f"orders: {req.path} for {req.headers['X-User-Id']}")
def catalog_service(req: Request) -> Response:
return Response(200, f"catalog: {req.path}")
VALID_TOKENS = {"token-abc": "user-42"} # stand-in for JWT validation
class ApiGateway:
"""One front door: route by prefix, check auth once, stamp a request ID, hide the topology."""
def __init__(self):
self._routes: list[tuple[str, Callable, bool]] = [] # (prefix, service, needs_auth)
def route(self, prefix: str, service: Callable, needs_auth: bool = True) -> None:
self._routes.append((prefix, service, needs_auth))
def handle(self, req: Request) -> Response:
match = next((r for r in self._routes if req.path.startswith(r[0])), None)
if match is None:
return Response(404, "no such route")
prefix, service, needs_auth = match
inner = Request(req.path, {}) # don't forward client headers blindly
inner.headers["X-Request-Id"] = req.headers.get("X-Request-Id", str(uuid.uuid4()))
if needs_auth:
user = VALID_TOKENS.get(req.headers.get("Authorization", "").removeprefix("Bearer "))
if user is None:
return Response(401, "unauthorized")
inner.headers["X-User-Id"] = user # services trust the gateway, not the client
return service(inner)
gateway = ApiGateway()
gateway.route("/api/orders", orders_service)
gateway.route("/api/catalog", catalog_service, needs_auth=False)
print(gateway.handle(Request("/api/catalog/sku-1")))
print(gateway.handle(Request("/api/orders/42", {"Authorization": "Bearer token-abc"})))
print(gateway.handle(Request("/api/orders/42", {"Authorization": "Bearer stolen"})))
print(gateway.handle(Request("/api/orders/42", {"X-User-Id": "admin"}))) # spoofing attempt
print(gateway.handle(Request("/internal/admin")))
Response(status=200, body='catalog: /api/catalog/sku-1')
Response(status=200, body='orders: /api/orders/42 for user-42')
Response(status=401, body='unauthorized')
Response(status=401, body='unauthorized')
Response(status=404, body='no such route')
The fourth line is the spoofing attempt. The client sent X-User-Id: admin with no token, and the gateway ignored the header and returned 401.
C#
var tokens = new Dictionary<string, string> { ["token-abc"] = "user-42" }; // stand-in for JWT validation
var gateway = new ApiGateway(tokens);
gateway.Route("/api/orders", req => new(200, $"orders: {req.Path} for {req.Headers["X-User-Id"]}"));
gateway.Route("/api/catalog", req => new(200, $"catalog: {req.Path}"), needsAuth: false);
Console.WriteLine(gateway.Handle(new("/api/catalog/sku-1", [])));
Console.WriteLine(gateway.Handle(new("/api/orders/42", new() { ["Authorization"] = "Bearer token-abc" })));
Console.WriteLine(gateway.Handle(new("/api/orders/42", new() { ["X-User-Id"] = "admin" })));
Console.WriteLine(gateway.Handle(new("/internal/admin", [])));
record Request(string Path, Dictionary<string, string> Headers);
record Response(int Status, string Body);
sealed class ApiGateway(Dictionary<string, string> tokens)
{
private readonly List<(string Prefix, Func<Request, Response> Service, bool NeedsAuth)> _routes = [];
public void Route(string prefix, Func<Request, Response> service, bool needsAuth = true) =>
_routes.Add((prefix, service, needsAuth));
public Response Handle(Request req)
{
var match = _routes.FirstOrDefault(r => req.Path.StartsWith(r.Prefix));
if (match.Service is null) return new(404, "no such route");
var inner = new Request(req.Path, new() // don't forward client headers blindly
{
["X-Request-Id"] = req.Headers.GetValueOrDefault("X-Request-Id") ?? Guid.NewGuid().ToString()
});
if (match.NeedsAuth)
{
var token = req.Headers.GetValueOrDefault("Authorization", "").Replace("Bearer ", "");
if (!tokens.TryGetValue(token, out var user)) return new(401, "unauthorized");
inner.Headers["X-User-Id"] = user; // services trust the gateway, not the client
}
return match.Service(inner);
}
}
Response { Status = 200, Body = catalog: /api/catalog/sku-1 }
Response { Status = 200, Body = orders: /api/orders/42 for user-42 }
Response { Status = 401, Body = unauthorized }
Response { Status = 404, Body = no such route }
In a real system you wouldn't write this class. You'd configure one: YARP in .NET, Azure API Management, Kong, Envoy, or your cloud's managed gateway. The code is here so you know what the configuration is doing.
The old idea underneath. A gateway is a Facade: one simple interface over a messy subsystem. Its routing table is a Proxy that picks the real object per request, and its filters (auth, logging, limits) form a Chain of Responsibility. I covered all three in Adapter, Facade and Proxy and Command, Chain, Mediator and Template Method.
When not to use it.
- One service, one client. A gateway in front of a single API is an extra hop and an extra thing to deploy. Your web framework's middleware already does auth and logging.
- Business logic in the gateway. The moment the gateway knows what a discount is, it becomes a monolith that every team has to change. Keep it to routing and cross-cutting concerns.
- A single point of failure. Everything goes through it, so it needs to be scaled and monitored like your most important service, because it is.
Backend for Frontend (BFF)
The problem. The iOS home screen needs a name, the latest order's status and a count. The web dashboard needs the full order list, an address and a recommendations carousel. If both call the same general-purpose API, the phone downloads a lot of data it throws away, over several round trips on a mobile network. If you add mobile-specific fields to the shared API, it slowly becomes everybody's API and nobody's.
The pattern. Sam Newman's description: one backend per user experience. A small mobile BFF and a small web BFF, each owned by the team that builds that client, each calling the same downstream services and shaping the result for exactly one screen. The BFF also decides how its client degrades when a downstream service is slow, because "hide the carousel" is a product decision for the web, not for the recommendations service.
Python
import asyncio
import json
# Shared downstream services. They return everything; they don't know who's asking.
async def get_profile(user_id: str) -> dict:
return {"id": user_id, "name": "Asha", "email": "asha@example.com", "address": "12 Long Street",
"marketing_prefs": {"email": True, "sms": False}, "created": "2021-03-04T10:00:00Z"}
async def get_orders(user_id: str) -> list[dict]:
return [{"id": f"o-{i}", "status": "shipped" if i else "packing", "total_cents": 1999 + i,
"lines": [{"sku": f"sku-{i}", "qty": 1, "description": "A long product description " * 3}],
"shipping_address": "12 Long Street"} for i in range(5)]
async def get_recommendations(user_id: str) -> list[str]:
await asyncio.sleep(5) # this service is having a bad day
return ["sku-9"]
async def mobile_home(user_id: str) -> dict:
"""Mobile BFF: one round trip, only what the home screen draws."""
profile, orders = await asyncio.gather(get_profile(user_id), get_orders(user_id))
latest = orders[0]
return {"greeting": f"Hi {profile['name']}", "latest_order": {"id": latest["id"], "status": latest["status"]},
"open_orders": sum(o["status"] != "shipped" for o in orders)}
async def web_dashboard(user_id: str) -> dict:
"""Web BFF: richer page, and it degrades if recommendations are slow."""
profile, orders = await asyncio.gather(get_profile(user_id), get_orders(user_id))
try:
async with asyncio.timeout(0.2):
recs = await get_recommendations(user_id)
except TimeoutError:
recs = [] # show the page without the carousel
return {"profile": {k: profile[k] for k in ("name", "email", "address")},
"orders": [{"id": o["id"], "status": o["status"], "total_cents": o["total_cents"]} for o in orders],
"recommendations": recs}
async def main():
raw = json.dumps({"profile": await get_profile("u1"), "orders": await get_orders("u1")})
mobile = json.dumps(await mobile_home("u1"))
web = json.dumps(await web_dashboard("u1"))
print(f"raw services: {len(raw)} bytes over 2 calls")
print(f"mobile BFF: {len(mobile)} bytes over 1 call -> {mobile}")
print(f"web BFF: {len(web)} bytes over 1 call, recommendations={json.loads(web)['recommendations']}")
asyncio.run(main())
raw services: 1366 bytes over 2 calls
mobile BFF: 93 bytes over 1 call -> {"greeting": "Hi Asha", "latest_order": {"id": "o-0", "status": "packing"}, "open_orders": 1}
web BFF: 407 bytes over 1 call, recommendations=[]
The phone gets 93 bytes in one call instead of 1,366 bytes across two. The web page still renders when recommendations hang, because its BFF gave that call a 200 ms deadline and a fallback. The timeout is the same idea as in the resilience post.
C#
var services = new DownstreamServices();
var mobile = new MobileBff(services);
var web = new WebBff(services);
Console.WriteLine($"mobile: {await mobile.HomeAsync("u1")}");
var page = await web.DashboardAsync("u1");
Console.WriteLine($"web: {page.Orders.Count} orders, {page.Recommendations.Count} recommendations (degraded: {page.Degraded})");
// Shared downstream services: they return everything and don't know who's asking.
record Profile(string Id, string Name, string Email, string Address);
record Order(string Id, string Status, int TotalCents, string ShippingAddress);
sealed class DownstreamServices
{
public Task<Profile> GetProfileAsync(string id) => Task.FromResult(new Profile(id, "Asha", "asha@example.com", "12 Long Street"));
public Task<List<Order>> GetOrdersAsync(string id) => Task.FromResult(
Enumerable.Range(0, 5).Select(i => new Order($"o-{i}", i == 0 ? "packing" : "shipped", 1999 + i, "12 Long Street")).ToList());
public async Task<List<string>> GetRecommendationsAsync(string id, CancellationToken ct)
{
await Task.Delay(5000, ct); // having a bad day
return ["sku-9"];
}
}
// Mobile BFF: one round trip, only what the home screen draws.
record MobileHome(string Greeting, string LatestOrderStatus, int OpenOrders);
sealed class MobileBff(DownstreamServices s)
{
public async Task<MobileHome> HomeAsync(string userId)
{
var (profile, orders) = (s.GetProfileAsync(userId), s.GetOrdersAsync(userId));
await Task.WhenAll(profile, orders);
return new($"Hi {profile.Result.Name}", orders.Result[0].Status, orders.Result.Count(o => o.Status != "shipped"));
}
}
// Web BFF: a richer page that degrades if recommendations are slow.
record WebDashboard(string Name, string Email, List<Order> Orders, List<string> Recommendations, bool Degraded);
sealed class WebBff(DownstreamServices s)
{
public async Task<WebDashboard> DashboardAsync(string userId)
{
var profileTask = s.GetProfileAsync(userId);
var ordersTask = s.GetOrdersAsync(userId);
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
List<string> recs; var degraded = false;
try { recs = await s.GetRecommendationsAsync(userId, cts.Token); }
catch (OperationCanceledException) { recs = []; degraded = true; } // page without the carousel
var profile = await profileTask;
return new(profile.Name, profile.Email, await ordersTask, recs, degraded);
}
}
mobile: MobileHome { Greeting = Hi Asha, LatestOrderStatus = packing, OpenOrders = 1 }
web: 5 orders, 0 recommendations (degraded: True)
The C# version passes a CancellationToken with a deadline, so the slow call actually stops instead of running on in the background.
The old idea underneath. Each BFF is a Facade for one client, often with an Adapter inside it that maps the services' models to the screen's. It's also the API version of gateway aggregation, scoped to one client.
When not to use it.
- One client, or clients that need the same data. A web app and a near-identical admin app don't need two backends. Field selection (GraphQL, sparse fieldsets) may be enough.
- No team to own it. Newman's point is that the client team owns its BFF. A BFF owned by a separate backend team turns back into a shared API with extra steps.
- Duplicated logic. If three BFFs each calculate "is this order late?", that rule belongs in a downstream service. BFFs should shape and combine, not decide.
Publish/subscribe
The problem. When an order is placed, you need to send a receipt, update analytics and award loyalty points. If the order service calls all three, it now depends on all three. When loyalty is down, checkout fails. When marketing wants a fourth reaction, the order team has to ship a change.
The pattern. The order service publishes an OrderPlaced message to a topic and moves on. Each interested service has its own subscription to that topic and gets its own copy. Subscribers can be added without touching the publisher, and one failing subscriber doesn't affect the others.
That last property comes from giving each subscription its own queue, retries and dead-letter list. That's how Azure Service Bus topics, Amazon SNS with SQS, and Google Pub/Sub all work.
Python
from collections import defaultdict
from typing import Callable
Handler = Callable[[dict], None]
class Broker:
"""Topics fan out to subscriptions. Each subscription fails, retries and dead-letters on its own."""
def __init__(self, max_attempts: int = 3):
self._subs: dict[str, dict[str, Handler]] = defaultdict(dict)
self.dead_letters: list[tuple[str, dict]] = []
self._max_attempts = max_attempts
def subscribe(self, topic: str, name: str, handler: Handler) -> None:
self._subs[topic][name] = handler
def publish(self, topic: str, event: dict) -> None:
# The publisher doesn't know who listens. Zero subscribers is fine too.
for name, handler in self._subs[topic].items():
for attempt in range(1, self._max_attempts + 1):
try:
handler(event)
break
except Exception as e:
print(f" {name} attempt {attempt} failed: {e}")
else:
self.dead_letters.append((name, event)) # park it; don't block the others
def send_email(e): print(f" email: receipt for {e['order_id']}")
def update_analytics(e): print(f" analytics: +{e['total_cents']} cents revenue")
def award_points(e): raise ConnectionError("loyalty db unavailable")
broker = Broker()
broker.subscribe("order-placed", "email", send_email)
broker.subscribe("order-placed", "analytics", update_analytics)
print("publish o-1")
broker.publish("order-placed", {"order_id": "o-1", "total_cents": 4999})
broker.subscribe("order-placed", "loyalty", award_points) # new feature, publisher untouched
print("publish o-2")
broker.publish("order-placed", {"order_id": "o-2", "total_cents": 1500})
print("dead letters:", broker.dead_letters)
publish o-1
email: receipt for o-1
analytics: +4999 cents revenue
publish o-2
email: receipt for o-2
analytics: +1500 cents revenue
loyalty attempt 1 failed: loyalty db unavailable
loyalty attempt 2 failed: loyalty db unavailable
loyalty attempt 3 failed: loyalty db unavailable
dead letters: [('loyalty', {'order_id': 'o-2', 'total_cents': 1500})]
Loyalty joined after o-1, so it never saw it. That's normal for pub/sub: a new subscription starts from now. If a new subscriber needs history, you need a replayable log (Kafka, Event Hubs) or a backfill job. And loyalty's failure didn't stop email or analytics. The message sits in loyalty's dead-letter list until someone fixes the database and replays it.
C#
The C# version gives each subscription its own Channel<T> and its own pump task, which is closer to how a real broker isolates subscribers. A slow handler only slows its own queue.
using System.Threading.Channels;
var broker = new Broker<OrderPlaced>();
broker.Subscribe("email", async e => { await Task.Delay(10); Console.WriteLine($" email: receipt for {e.OrderId}"); });
broker.Subscribe("analytics", e => { Console.WriteLine($" analytics: +{e.TotalCents} cents"); return Task.CompletedTask; });
broker.Subscribe("loyalty", e => throw new InvalidOperationException("loyalty db unavailable"));
await broker.PublishAsync(new OrderPlaced("o-1", 4999));
await broker.PublishAsync(new OrderPlaced("o-2", 1500));
await broker.DrainAsync();
Console.WriteLine($"dead letters: {string.Join(", ", broker.DeadLetters)}");
record OrderPlaced(string OrderId, int TotalCents);
sealed class Broker<TEvent>
{
// One channel per subscription: a slow or broken subscriber can't hold up the others.
private readonly List<(Channel<TEvent> Queue, Task Pump)> _subs = [];
public List<string> DeadLetters { get; } = [];
public void Subscribe(string name, Func<TEvent, Task> handler, int maxAttempts = 3)
{
var queue = Channel.CreateUnbounded<TEvent>();
var pump = Task.Run(async () =>
{
await foreach (var e in queue.Reader.ReadAllAsync())
{
for (var attempt = 1; ; attempt++)
{
try { await handler(e); break; }
catch (Exception ex) when (attempt < maxAttempts) { Console.WriteLine($" {name} attempt {attempt}: {ex.Message}"); }
catch { lock (DeadLetters) DeadLetters.Add($"{name}:{e}"); break; }
}
}
});
_subs.Add((queue, pump));
}
public async Task PublishAsync(TEvent e)
{
foreach (var (queue, _) in _subs) await queue.Writer.WriteAsync(e); // fan out, don't wait for handlers
}
public Task DrainAsync()
{
foreach (var (queue, _) in _subs) queue.Writer.Complete();
return Task.WhenAll(_subs.Select(s => s.Pump));
}
}
loyalty attempt 1: loyalty db unavailable
analytics: +4999 cents
loyalty attempt 2: loyalty db unavailable
analytics: +1500 cents
loyalty attempt 1: loyalty db unavailable
loyalty attempt 2: loyalty db unavailable
email: receipt for o-1
email: receipt for o-2
dead letters: loyalty:OrderPlaced { OrderId = o-1, TotalCents = 4999 }, loyalty:OrderPlaced { OrderId = o-2, TotalCents = 1500 }
The lines interleave differently on every run, because the three subscriptions really are independent. Email is the slowest handler and finishes last, without holding anyone else up. Each subscription keeps its own order, though: o-1 is always handled before o-2 within email.
The old idea underneath. Observer: subjects notify observers without knowing who they are. The broker adds what Observer never had: durability, retries, and observers that can be offline when the event happens.
When not to use it.
- You need an answer. "Is this card valid?" is a question, not an event. Use a request/response call. Faking request/response over a topic gives you the costs of both.
- Exactly one worker should do the job. That's a point-to-point queue with competing consumers, not a topic.
- You need the publish and the database write to both happen. Publishing right after a commit can lose the message if the process dies in between. That's what the transactional outbox is for.
- Delivery is at least once. Every subscriber will eventually see a duplicate, so every subscriber must be idempotent. The resilience post covers idempotency keys.
Event-driven architecture
Pub/sub is the plumbing. Event-driven architecture is the style you build with it: services announce facts that already happened ("CustomerAddressChanged") instead of telling each other what to do ("UpdateShippingAddress"). Martin Fowler's article on the topic separates a few things that all get called "event-driven", and two of them matter most here:
- Event notification. The event says something changed, with an ID. Consumers that care call back for details. Small events, but the callback brings the coupling back.
- Event-carried state transfer. The event carries the data consumers need. Each consumer keeps its own local copy. No callback, so the consumer keeps working when the publisher is down.
The example below is event-carried state transfer. The shipping service keeps its own copy of customer addresses, built from events, so it can print a label without calling the customer service.
That buys independence, and costs you two problems you have to handle in code. Events can arrive twice and out of order. So each event carries an ID (for dedupe) and a per-customer version number (so an old event can't overwrite a newer one).
Python
from dataclasses import dataclass
@dataclass(frozen=True)
class CustomerAddressChanged:
"""A fact, in the past tense, carrying the state consumers need (event-carried state transfer)."""
event_id: str
customer_id: str
version: int # per-customer sequence number from the Customer service
address: str
class ShippingService:
"""Keeps its own copy of addresses, so it never calls the Customer service at label time."""
def __init__(self):
self.addresses: dict[str, tuple[int, str]] = {} # customer_id -> (version, address)
self._seen: set[str] = set()
def on_address_changed(self, e: CustomerAddressChanged) -> None:
if e.event_id in self._seen:
print(f" skip {e.event_id}: duplicate")
return
self._seen.add(e.event_id)
current_version = self.addresses.get(e.customer_id, (0, ""))[0]
if e.version <= current_version:
print(f" skip {e.event_id}: v{e.version} is older than v{current_version}")
return
self.addresses[e.customer_id] = (e.version, e.address)
print(f" {e.customer_id} -> {e.address} (v{e.version})")
def create_label(self, customer_id: str) -> str:
return f"label to {self.addresses[customer_id][1]}"
shipping = ShippingService()
v1 = CustomerAddressChanged("evt-1", "c-7", 1, "12 Long Street")
v2 = CustomerAddressChanged("evt-2", "c-7", 2, "3 Harbour Road")
# At-least-once delivery, no ordering guarantee: v2 arrives first, v1 arrives late, v2 arrives twice.
for event in (v2, v1, v2):
shipping.on_address_changed(event)
# The Customer service can be down now. Shipping still has what it needs.
print(shipping.create_label("c-7"))
c-7 -> 3 Harbour Road (v2)
skip evt-1: v1 is older than v2
skip evt-2: duplicate
label to 3 Harbour Road
Without the version check, the late v1 would have quietly moved the customer back to their old address, and the parcel would go to the wrong house. In this example the version check would also catch the duplicate. The event ID check matters for events that aren't state snapshots, like PaymentReceived, where applying one twice means counting money twice.
C#
var shipping = new ShippingService();
var v1 = new CustomerAddressChanged("evt-1", "c-7", 1, "12 Long Street");
var v2 = new CustomerAddressChanged("evt-2", "c-7", 2, "3 Harbour Road");
foreach (var e in new[] { v2, v1, v2 }) // out of order, and v2 delivered twice
shipping.On(e);
Console.WriteLine(shipping.CreateLabel("c-7")); // no call to the Customer service
// A past-tense fact that carries the state consumers need.
record CustomerAddressChanged(string EventId, string CustomerId, int Version, string Address);
sealed class ShippingService
{
private readonly Dictionary<string, (int Version, string Address)> _addresses = [];
private readonly HashSet<string> _seen = [];
public void On(CustomerAddressChanged e)
{
if (!_seen.Add(e.EventId)) { Console.WriteLine($" skip {e.EventId}: duplicate"); return; }
var current = _addresses.GetValueOrDefault(e.CustomerId).Version;
if (e.Version <= current) { Console.WriteLine($" skip {e.EventId}: v{e.Version} is older than v{current}"); return; }
_addresses[e.CustomerId] = (e.Version, e.Address);
Console.WriteLine($" {e.CustomerId} -> {e.Address} (v{e.Version})");
}
public string CreateLabel(string customerId) => $"label to {_addresses[customerId].Address}";
}
c-7 -> 3 Harbour Road (v2)
skip evt-1: v1 is older than v2
skip evt-2: duplicate
label to 3 Harbour Road
In production, both _seen and the addresses live in the shipping service's database. Store the processed event ID and the address update in the same transaction, so a crash can't leave you having done one without the other.
The old idea underneath. Observer again, at the scale of a whole system. Event-carried state transfer adds a replicated read cache: each consumer holds a copy of someone else's data, and accepts that it might be slightly stale.
When not to use it.
- When strong consistency is the requirement. If the user must never see a stale balance, a local copy updated "soon" is the wrong tool.
- When the flow is the point. If a business process has ten steps across five services, choreographing it purely through events means the flow exists only in your tracing tool. An orchestrated saga keeps the flow in one place.
- Before you have tracing. Debugging "why didn't shipping get the new address?" across a broker needs correlation IDs and distributed tracing. Without them, event-driven systems are hard to operate.
- Treat event schemas as public APIs. Once another team consumes
CustomerAddressChanged, you can't rename its fields freely. Add fields, don't remove them, and version when you must. Part 5 of this series, changing live systems, covers that expand-and-contract discipline.
Rate limiting
The problem. One client with a bug in a retry loop, one scraper, or one big customer running a batch job can use up capacity meant for everyone. On a pay-per-call backend (including an LLM API), it can also use up your budget.
The pattern. Cap how fast each caller can send requests, and reject the excess with HTTP 429 Too Many Requests and a Retry-After header that tells the client when to try again. The common algorithms:
- Fixed window: N requests per calendar minute. Simple, but allows a double burst across a window boundary.
- Sliding window: smooths that boundary by weighting the previous window.
- Token bucket: a bucket holds up to
capacitytokens and refills at a steady rate. Each request spends a token. It allows short bursts up to the capacity, and a steady rate after that. This is the one I'd start with.
The important design choice is the partition key. Limit per API key, per user or per tenant, not globally. A global limit lets one noisy caller spend everyone's budget.
Python
import math
import time
class TokenBucket:
"""Holds up to `capacity` tokens and refills `rate` per second. Each request spends one."""
def __init__(self, capacity: int, rate: float, clock=time.monotonic):
self.capacity, self.rate, self.clock = capacity, rate, clock
self.tokens, self.updated = float(capacity), clock()
def try_acquire(self) -> tuple[bool, int]:
now = self.clock()
self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
self.updated = now
if self.tokens >= 1:
self.tokens -= 1
return True, 0
return False, math.ceil((1 - self.tokens) / self.rate) # seconds until the next token
class RateLimiter:
"""One bucket per caller, so a noisy client can't spend everyone else's budget."""
def __init__(self, capacity: int, rate: float, clock=time.monotonic):
self._make = lambda: TokenBucket(capacity, rate, clock)
self._buckets: dict[str, TokenBucket] = {}
def check(self, client_id: str) -> tuple[int, dict]:
bucket = self._buckets.setdefault(client_id, self._make())
allowed, retry_after = bucket.try_acquire()
if allowed:
return 200, {}
return 429, {"Retry-After": str(retry_after)}
now = 0.0
limiter = RateLimiter(capacity=5, rate=1.0, clock=lambda: now)
burst = [limiter.check("app-a")[0] for _ in range(7)]
print("app-a burst of 7 at t=0: ", burst)
print("app-a 8th request: ", limiter.check("app-a"))
print("app-b at t=0: ", limiter.check("app-b")[0])
now = 2.5
print("app-a 3 requests at t=2.5:", [limiter.check("app-a")[0] for _ in range(3)])
app-a burst of 7 at t=0: [200, 200, 200, 200, 200, 429, 429]
app-a 8th request: (429, {'Retry-After': '1'})
app-b at t=0: 200
app-a 3 requests at t=2.5: [200, 200, 429]
app-a spends its burst of 5, then gets 429s with a Retry-After of one second. app-b is unaffected, because it has its own bucket. After 2.5 seconds, app-a has earned 2.5 tokens back, enough for two requests. The clock is injected so the demo doesn't have to sleep.
C#
.NET ships token bucket, fixed window, sliding window and concurrency limiters in System.Threading.RateLimiting. PartitionedRateLimiter gives you one bucket per key:
#:sdk Microsoft.NET.Sdk.Web
using System.Threading.RateLimiting;
// The same token bucket, built in: one bucket per client ID.
using var limiter = PartitionedRateLimiter.Create<string, string>(clientId =>
RateLimitPartition.GetTokenBucketLimiter(clientId, _ => new TokenBucketRateLimiterOptions
{
TokenLimit = 5, // burst size
TokensPerPeriod = 1, // refill rate...
ReplenishmentPeriod = TimeSpan.FromSeconds(1), // ...per second
QueueLimit = 0, // reject, don't queue
AutoReplenishment = true
}));
string Check(string client)
{
using var lease = limiter.AttemptAcquire(client);
if (lease.IsAcquired) return "200";
return lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter)
? $"429 (Retry-After {retryAfter.TotalSeconds:F0}s)" : "429";
}
Console.WriteLine($"app-a burst of 7: {string.Join(", ", Enumerable.Range(0, 7).Select(_ => Check("app-a")))}");
Console.WriteLine($"app-b: {Check("app-b")}");
await Task.Delay(TimeSpan.FromSeconds(2.5));
Console.WriteLine($"app-a after 2.5s: {string.Join(", ", Enumerable.Range(0, 3).Select(_ => Check("app-a")))}");
app-a burst of 7: 200, 200, 200, 200, 200, 429 (Retry-After 1s), 429 (Retry-After 1s)
app-b: 200
app-a after 2.5s: 200, 200, 429 (Retry-After 1s)
Same behavior as the Python version, using the built-in limiter and a real 2.5-second wait. The #:sdk Microsoft.NET.Sdk.Web line pulls in the ASP.NET Core shared framework, which is where these types live. In an ASP.NET Core app you'd register the same policy with AddRateLimiter, set RejectionStatusCode to 429, and attach it to endpoints with RequireRateLimiting.
The old idea underneath. A limiter is a protection Proxy: it stands in front of the real handler and decides whether the call goes through. The algorithm (token bucket, sliding window) is a Strategy you can swap without touching the proxy.
When not to use it, or not like this.
- In-memory limits on many instances. Both versions above keep buckets in process memory. With ten instances behind a load balancer, a "5 per second" limit is really about 50. For a hard limit, enforce it at the gateway or keep the counters in a shared store like Redis.
- As your only overload protection. Rate limiting stops one caller from taking too much. It doesn't help when total legitimate traffic exceeds capacity. For that you need load shedding and autoscaling.
- Without telling clients. A 429 without
Retry-Afterinvites clients to retry immediately, which makes the problem worse. On the client side, honor the header. The resilience post covers that half.
How these fit together
These aren't five separate choices. A typical request path combines them:
- The client calls its BFF, through an API gateway that checks the token and applies a rate limit per API key.
- The BFF calls a few services synchronously, with timeouts, to build the screen.
- When something changes, the service that owns it publishes an event. Other services react in their own time and keep their own copies of what they need.
The rule I'd use to pick between a call and an event: if the caller needs the answer to continue, call. If the caller is announcing something that already happened, publish.
Next in the series: data at scale, where the same "separate the copies" idea shows up as CQRS, read replicas and sharding.
Check yourself: questions and answers
1. What's the difference between an API gateway and a BFF?
A gateway is one front door for all clients, focused on routing and cross-cutting concerns like auth and rate limits. A BFF is one backend per client type, focused on shaping data for that client's screens. They're often used together: the gateway in front, a BFF per client behind it.
2. Why shouldn't a gateway forward all client headers to internal services?
Because internal services trust headers like X-User-Id that the gateway sets after validating a token. If client-supplied copies pass through, any client can claim to be any user. The gateway should build the inner request's trusted headers itself.
3. Pub/sub or a point-to-point queue?
Pub/sub when several independent consumers each need to react to the same event. A queue when exactly one worker should do each job. Brokers usually support both: a topic with several subscriptions, and each subscription can have several competing consumers.
4. What does event-carried state transfer buy you, and what does it cost?
It lets consumers keep working when the publisher is down, because they hold their own copy of the data. The cost is eventual consistency, duplicated data, and handling duplicate and out-of-order events, usually with an event ID and a version number.
5. Why limit per client instead of globally?
A global limit lets one noisy caller use up everyone's share. Per-client buckets keep the damage to the caller causing it. Pick the key that matches who you're protecting against: API key, user or tenant.
6. Your in-memory rate limiter allows 100 requests a minute and you run 8 instances. What's the real limit?
Roughly 800 a minute, depending on how the load balancer spreads requests. For a true limit, enforce it at a single point like the gateway, or store the counters somewhere shared like Redis.
Further reading
- Azure Architecture Center, Using API gateways in microservices
- Azure Architecture Center, Gateway Routing, Gateway Offloading and Gateway Aggregation patterns
- Chris Richardson, API Gateway / Backends for Frontends on microservices.io
- Microsoft Learn, YARP overview (a reverse proxy toolkit for building gateways in .NET)
- Sam Newman, Backends For Frontends
- Azure Architecture Center, Backends for Frontends pattern
- Azure Architecture Center, Publisher-Subscriber pattern
- Azure Architecture Center, Event-driven architecture style
- Martin Fowler, What do you mean by "Event-Driven"?
- Azure Architecture Center, Rate Limiting pattern and Throttling pattern
- Microsoft Learn, Rate limiting middleware in ASP.NET Core and the TokenBucketRateLimiter API
- IETF, RFC 6585 (defines HTTP 429 Too Many Requests)
- Stripe docs, Rate limits (a clear public example of how an API documents its limits and 429 responses)
- In this blog: Cloud messaging patterns (competing consumers, outbox, saga) and Cloud resilience patterns (retries, idempotency, timeouts)
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.