API Integration Patterns (API Design #11)
Your monolith becomes four services: users, orders, payments, inventory. The mobile app, which used to make one call, now makes five — and it needs auth tokens from users, totals from orders, card status from payments, all to render one screen. On a bad network that’s 3 s of waterfall. Then someone asks the obvious question: who composes all this back into something a client can use?
Integration patterns are the answers to that question — how clients and services talk when there are many services. This chapter covers API gateways, the BFF pattern, microservices contracts, event-driven architecture with Kafka and RabbitMQ, batch as the unglamorous workhorse, and the resilience trio — timeouts, retries, circuit breakers — that keeps partial failures from becoming total ones.
By the end you will be able to sketch the request path of a real system, choose between sync composition and event flows, and write a retry policy that doesn’t take your own system down.
Sync vs async: the first fork
Every integration decision starts here. Synchronous calls (REST, gRPC) couple the caller’s availability to the callee’s: if payments is down, checkout is down. Asynchronous flows (queues, events, webhooks) decouple them: checkout enqueues “charge card” and moves on. The trade table:
| Synchronous | Asynchronous | |
|---|---|---|
| answer when? | now | eventually |
| failure mode | caller sees it immediately | failure surfaces later, elsewhere |
| coupling | temporal — both up together | loose — either can be down |
| debugging | one stack trace | distributed, needs tracing (Ch. 13) |
| fit | queries, user-facing reads | commands, side effects, fan-out |
Queries stay sync; side effects graduate to async. “Get my cart” is a query. “Charge the card, email the receipt, update inventory, notify the warehouse” is four side effects that should not all block checkout.
The sync chain has a second, sharper cost: availability multiplies. If checkout depends synchronously on \(k\) services with availabilities \(a_1, \dots, a_k\), then
\[ a_{\text{chain}} = \prod_{i=1}^{k} a_i \]
— four 99.9% dependencies in series cap you at \(0.999^4 \approx 99.6\%\), over three hours of extra monthly downtime, and that’s before their latencies stack. Every dependency you move behind an event removes one factor from the product.
The API gateway: one front door
An API gateway is a reverse proxy that owns the edge: TLS termination, authentication verification, rate limiting, request routing, and response aggregation. Every cross-cutting concern from Chapters 5–10 lives here once, instead of being re-implemented per service:
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=4pt, minimum width=2.0cm, minimum height=0.7cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=blue!10] (m) at (0,0.8) {mobile};
\node[b, fill=blue!10] (w) at (0,-0.8) {web};
\node[b, fill=orange!20, minimum width=2.6cm] (g) at (3.2,0) {API gateway\\auth · quota · route};
\node[b, fill=green!10] (u) at (6.8,1.2) {users};
\node[b, fill=green!10] (o) at (6.8,0) {orders};
\node[b, fill=green!10] (p) at (6.8,-1.2) {payments};
\draw[a] (m) -- (g); \draw[a] (w) -- (g);
\draw[a] (g) -- (u); \draw[a] (g) -- (o); \draw[a] (g) -- (p);
\end{tikzpicture}
The gateway is also where external shape meets internal reality: outside clients see /orders/42; inside, that fans out to three services. The danger is gravity — business logic slowly migrating into gateway config until the proxy is a monolith in YAML. Keep the gateway to edge concerns (auth, quota, routing, header munging); domain logic belongs in services.
BFF: a backend per frontend
Mobile and web have genuinely different needs: the watch wants three fields, the desktop dashboard wants three hundred. Backend-for-Frontend gives each client class its own API layer, shaped to its screens:
- the mobile BFF returns compact, denormalized payloads (one call per screen, few KB);
- the web BFF returns rich aggregates and long-poll/stream support;
- each BFF owns its client’s auth flow, caching, and field selection — a per-client GraphQL server (Chapter 2) is a common implementation.
The payoff is independence: the mobile team ships payload changes without negotiating with web. The cost is duplication: two BFFs reimplementing “order with items” drift unless shared logic lives in a common service beneath them.
Microservices and the contracts between them
Microservices split by domain so teams deploy independently — which works only if the APIs between services are treated as seriously as public ones. Every internal API gets the full treatment from this course: an explicit contract (OpenAPI or proto), versioning discipline (Chapter 3), object-level authz (service A asking “user 77’s orders” must prove it acts for user 77 — not merely “I am service A”), and contract tests (Chapter 12). The distributed-monolith smell is shared databases: two services writing one schema are one service with network latency added.
Event-driven architecture: Kafka vs RabbitMQ
EDA replaces “A calls B” with “A publishes OrderCreated; whoever cares, subscribes.” Producers don’t know consumers exist, so adding a fraud service requires zero changes to checkout:
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=4pt, minimum width=2.2cm, minimum height=0.68cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=blue!10] (o) at (0,0) {orders svc};
\node[b, fill=orange!20] (t) at (3.6,0) {topic:\\order.created};
\node[b, fill=green!10] (e) at (7.4,1.2) {email};
\node[b, fill=green!10] (i) at (7.4,0) {inventory};
\node[b, fill=green!10] (a) at (7.4,-1.2) {analytics};
\draw[a] (o) -- node[above, font=\rmfamily\scriptsize] {publish once} (t);
\draw[a] (t) -- (e); \draw[a] (t) -- (i); \draw[a] (t) -- (a);
\end{tikzpicture}
The two workhorses embody different philosophies:
| RabbitMQ (message broker) | Kafka (event log) | |
|---|---|---|
| model | smart broker, dumb consumers | dumb log, smart consumers |
| message life | deleted after ack | retained (hours–forever), replayable |
| ordering | per-queue | per-partition |
| throughput | ~10⁴–10⁵ msg/s | ~10⁶+ events/s |
| best for | task queues, routing (work distribution) | event streams, replay, analytics, CDC |
The superpower of the log is replay: deploy a new recommendation service, point it at the orders topic from six months ago, and it bootstraps its models from history. A queue can’t do that — the message is gone once consumed. Choose RabbitMQ-style brokers for “do this task”; Kafka-style logs for “this happened.”
One rule applies to both: delivery is at-least-once, so consumers must be idempotent. A redelivered OrderCreated — after a consumer crash mid-processing, or a rebalance — must not reserve inventory twice. Deduplicate on the event id, or make the handler naturally idempotent (“set hold for order 42” rather than “increment holds”). This is Chapter 14’s idempotency principle wearing a different transport; the bug it prevents is the same double-apply, and it is the most common EDA production incident.
The producer side has its own classic bug: writing the database row and then publishing the event is two operations, and a crash between them loses the event. The outbox pattern closes the gap — write the row and an outbox record in one transaction, and let a relay publish from the outbox. Database and broker never disagree because only one of them is authoritative for “did it happen.”
Batch: the pattern nobody brags about
Nightly batch — “export all transactions to the warehouse at 02:00” — is unfashionable and irreplaceable. Events give you freshness; batch gives you efficiency and completeness: one scan, one file, exactly-once semantics, trivially re-runnable. Reconciliation between systems (Chapter 4’s webhook gap-healing is a form of it), billing runs, warehouse loads: these are batch jobs, and designing them as events-first usually means re-deriving batch on top of events anyway.
Resilience: timeouts, retries, circuit breakers
In a distributed system, every call has four outcomes — success, failure, slow, and silent — and the last two are the killers. The discipline:
- Always set a timeout. A call without one is a thread leaked forever. Default: a few seconds, sized from the callee’s p99.
- Retry with exponential backoff and jitter. Attempt \(n\) waits \(t_n = \min(b \cdot 2^n, t_{\max}) + \text{rand}(0, j)\) — backoff gives the callee room to recover; jitter stops 10,000 clients from retrying in lockstep (the thundering herd):
import random, time
def with_retries(fn, attempts=5, base=0.2, cap=5.0):
for n in range(attempts):
try:
return fn()
except TransientError:
if n == attempts - 1:
raise
time.sleep(min(base * 2 ** n, cap) + random.uniform(0, 0.1 * base * 2 ** n))
- Only retry the retryable.
422will fail forever; retrying it is abuse. And only retry what is idempotent — Chapter 14’s idempotency keys makePOST /paymentssafe to retry; without them, a retry can double-charge. - Circuit breaker. When a dependency’s failure rate crosses a threshold, the breaker opens and calls fail fast for a cooldown — no waiting on timeouts, no adding load to a struggling service — then half-opens to probe recovery. One failing dependency without a breaker cascades: its slow responses exhaust your thread pool, and soon your API is the one paging someone.
Pitfalls
- Sync chains five deep. Checkout → orders → payments → fraud → provider, each with its own p99 — latency stacks and availability multiplies: five 99.9% services in series give \(0.999^5 \approx 99.5\%\). Break chains with events and caches.
- Retry storms. Immediate, unjittered retries from thousands of clients arrive as a synchronized hammer on a service that’s already down. Backoff + jitter + a breaker.
- Business logic in the gateway. Validation rules and pricing calculations creep into proxy config until nobody can deploy without touching it. Edge concerns only.
- Retrying non-idempotent POSTs. A timed-out
POST /paymentsretried naively charges twice. Idempotency keys first, retries second. - Events as hidden coupling. “Loosely coupled” services that all depend on the exact shape of
OrderCreatedhave coupled via the schema instead of the endpoint. Version your event schemas like APIs. - No timeouts, ever. The default in most HTTP clients is “wait forever.” Every call, every time, explicit timeout.
Your checkout depends synchronously on four 99.9%-available services — what’s the ceiling on checkout availability, and which pattern raises it? Why does jitter matter as much as backoff in a retry policy? When do you pick Kafka over RabbitMQ?
ASolution
In series, availability multiplies: \(0.999^4 \approx 99.6\%\) — about 3.5 hours more downtime per month than a single dependency — and each hop adds latency. Move side effects (email, inventory, analytics) onto events so checkout depends on fewer synchronous services, and cache reads so queries survive a down dependency. Backoff without jitter still synchronizes: every client that failed at \(t\) retries at the same \(t + 2^n\), arriving as a coordinated burst exactly when the service is weakest; random jitter spreads retries across the window. Pick Kafka when the event stream is the product — replay for new consumers, analytics, high throughput, retention; pick RabbitMQ when you need task distribution and routing where each message is consumed once and gone.
Next: API Testing (API Design #12) — from unit tests to contract tests and load tests, and why the pyramid keeps you honest.