API Gateway Patterns — System Design

An API gateway is the single entry point for routing, authentication, rate limiting, SSL termination and logging; five patterns sit on top. BFF: each kind of…

In the API Gateway lesson you met the gateway as the single entry point. This lesson covers five patterns that make it more than a request forwarder: BFF, parallel aggregation, request collapsing, the circuit breaker and versioned routing. The head waiter of a big restaurant works much the same way. Children get the small menu, adults the full one. One order is fetched from three kitchens at once. If twenty tables order the same soup in the same minute, the kitchen cooks one pot, not twenty. If the grill breaks, he stops sending orders there and offers something else. And regulars who still order by last year's menu numbers are still served.

A reminder: the gateway's basic jobs

An API gateway is the single entry point that handles what every service needs, in one place: routing to the right service, token authentication, rate limiting, SSL termination (the gateway opens the client's HTTPS connection, then passes the request on to the services over the internal network), and logging. Every pattern below builds on that.

This lesson's example is one screen: the Archipelago Concert page (event 42). Example model numbers: Budi's phone is an 80 ms round trip from the server, the gateway adds 2 ms, then the gateway calls three services: concert (concert details, 30 ms), order (Budi's tickets for this concert, 40 ms) and recommendations (similar concerts, 50 ms).

Backend for Frontend (BFF)

A generic gateway gives every client the same response. The trouble is that a web screen and a phone screen need different things. The web shows the description, every ticket category, a large image and 12 recommendations. The phone only needs the name, date, cheapest price, tickets left, a thumbnail and 3 recommendations. With one response for everybody, the phone downloads data it never uses (over-fetching), or the web has to fire extra requests (under-fetching).

BFF means each kind of client has its own gateway (or layer) that shapes the response for its screen: GET /web/v2/events/42 and GET /mobile/v2/events/42. In the Lab the web response is 973 bytes and the mobile response 306 bytes, from the same services. The price: more gateways to maintain, and usually each BFF is owned by its frontend team.

Parallel aggregation

With the aggregation pattern, the phone sends one request, and the gateway calls the services behind it and merges the results into one response. The three calls for the concert page don't depend on each other, so the gateway can make them at the same time:

The gateway calls Service work Total on Budi's phone
one after another 30 + 40 + 50 = 120 ms 80 + 2 + 120 = 202 ms
in parallel (Promise.all) the slowest, 50 ms 80 + 2 + 50 = 132 ms

When one call depends on another's result (like "My orders" in the API Gateway lesson), that part stays sequential. Also separate the essential data from the optional: if concert fails, the page means nothing, so answer with an error. If recommendations fails, send the page without recommendations (fallback []).

Request collapsing

During a ticket war, thousands of identical requests arrive at once: GET /events/42. With nothing in place, the gateway forwards them all, and concert gets hammered by 10,000 calls for exactly the same data. Request collapsing (also called single-flight): if a call for the same key is already in flight, a new request doesn't call again; it waits for that call's result.

With 10,000 requests spread evenly over 1,000 ms and a 30 ms concert call, a new call only starts each time the previous one finishes: at ms 0, 30, 60, up to 990. That's 1,000 ÷ 30 = 33.3, rounded up to 34 calls, not 10,000. The difference from a cache: collapsing keeps nothing once the call is done. The two are often used together.

A circuit breaker at the gateway

Suppose recommendations hangs: it doesn't refuse, it just doesn't answer. Every request waits for the 1,000 ms timeout, so the concert page takes 80 + 2 + 1,000 = 1,082 ms, even though concert and order are healthy. A circuit breaker stops calling a service that is broken:

State Behaviour Moves to
CLOSED call as usual, count failures in a row OPEN after 5 failures
OPEN don't call, use the fallback right away HALF_OPEN after 30 seconds
HALF_OPEN try one call CLOSED if it works, OPEN again if it fails
// TicketTune's gateway: concert page 42, parallel calls + a circuit breaker (an example model)
const RTT = 80, GW = 2, TIMEOUT = 1000; // ms
let hanging = false; // is the recommendations service hanging?
let second = 0; // virtual clock
const breaker = { state: "CLOSED", failures: 0, openUntil: 0 };

function callRecommendations() {
  let trial = "";
  if (breaker.state === "OPEN") {
    if (second < breaker.openUntil) return { ms: 0, note: "breaker OPEN, skipped, fallback []" };
    breaker.state = "HALF_OPEN"; // the cooldown is over: try one call
    trial = "half-open trial: ";
  }
  if (hanging) {
    breaker.failures += 1;
    if (breaker.state === "HALF_OPEN" || breaker.failures >= 5) {
      breaker.state = "OPEN";
      breaker.openUntil = second + 30;
    }
    return { ms: TIMEOUT, note: `${trial}timed out after ${TIMEOUT} ms, fallback []` };
  }
  breaker.state = "CLOSED";
  breaker.failures = 0;
  return { ms: 50, note: `${trial}50 ms` };
}

function send() {
  second += 1;
  const rec = callRecommendations();
  const work = Math.max(30, 40, rec.ms); // concert, order, recommendations: in parallel
  console.log(`[${second} s] ${RTT + GW + work} ms, recommendations: ${rec.note}, breaker ${breaker.state}`);
}

send();
hanging = true;
for (let i = 0; i < 6; i++) send();
second += 30;
send();

The output:

[1 s] 132 ms, recommendations: 50 ms, breaker CLOSED
[2 s] 1082 ms, recommendations: timed out after 1000 ms, fallback [], breaker CLOSED
[3 s] 1082 ms, recommendations: timed out after 1000 ms, fallback [], breaker CLOSED
[4 s] 1082 ms, recommendations: timed out after 1000 ms, fallback [], breaker CLOSED
[5 s] 1082 ms, recommendations: timed out after 1000 ms, fallback [], breaker CLOSED
[6 s] 1082 ms, recommendations: timed out after 1000 ms, fallback [], breaker OPEN
[7 s] 122 ms, recommendations: breaker OPEN, skipped, fallback [], breaker OPEN
[38 s] 1082 ms, recommendations: half-open trial: timed out after 1000 ms, fallback [], breaker OPEN

Retry with exponential backoff, bulkheads and the other details are covered in the Resilience Patterns lesson.

Versioned routing

Apps already installed on phones can't be forced to update that same day. If concert changes the price from text to a number, the old app breaks. With versioned routing, the gateway tells versions apart by path (/v1/..., /v2/...) or by header, and the old version keeps its old shape:

// GET /mobile/v1/events/42
{ "priceFrom": "$75" }
// GET /mobile/v2/events/42
{ "priceFrom": 75, "currency": "USD" }

The service keeps only its newest shape, and the gateway or the BFF translates it to v1. The old version is retired once hardly anyone uses it.

🤔 A gateway that keeps getting fatter

Every pattern adds work at the gateway. Keep the line clear: the gateway shapes, merges, protects and forwards, while the business rules (prices, quotas, who may cancel) stay in the services. A BFF that starts computing its own discounts is a sign that business logic has leaked to the wrong place.

⚠️ The right patterns, set up the wrong way

TL;DR: An API gateway is the single entry point for routing, authentication, rate limiting, SSL termination and logging; five patterns sit on top. BFF: each kind of client (web, mobile) has a gateway that shapes the response for its screen, whereas a generic gateway gives every client the same format (TicketTune: web 973 bytes, mobile 306 bytes). Aggregation: the phone sends one request and the gateway calls the services in parallel (202 ms becomes 132 ms), and optional parts may use a fallback. Request collapsing: identical requests that arrive while a call is in flight wait for the same result (10,000 requests become 34 calls). Circuit breaker: after 5 failures in a row it opens for 30 seconds, then HALF_OPEN tries one call (1,082 ms becomes 122 ms). Versioned routing: /v1 keeps serving the old app.

⚡ BFF: a response for each kind of client

Meaning: A web screen and a phone screen need different things. With BFF, each kind of client has its own gateway that shapes the response for its screen: in the Lab, the web response is 973 bytes and the mobile one 306 bytes, from the same services.

⚡ Parallel aggregation

Meaning: The concert page's three calls don't depend on each other, so the gateway makes them at the same time. The total on Budi's phone drops from 202 ms to 132 ms. Optional parts such as recommendations may use a fallback [].

⚡ Request collapsing

Guess first: 10,000 GET /events/42 requests arrive within 1 second, and one call to concert takes 30 ms. How many times is concert called?

Only 34 times. Requests that arrive while a call for the same key is still running wait for the same result.

Meaning: Never use it for private data: Budi's "My tickets" must never reach Siti.

⚡ Circuit breaker

Write:

if (breaker.state === "HALF_OPEN" || breaker.failures >= 5) {
  breaker.state = "OPEN";
  breaker.openUntil = second + 30;
}

Meaning: After 5 failures in a row, the breaker opens for 30 seconds and recommendations isn't called at all, so the page is fast again (122 ms). After that, HALF_OPEN tries one call.

What you will learn