Systemsfor Aravinda
0 / 78 core
Week 7 · Architecture

Gateways and service mesh

1.5 hours · core path

Read first: API design, Rate limiting, Load balancing

In one sitting

The gateway is the front door. It terminates TLS, checks that a caller is authenticated, applies an abuse limit, and routes to a service. The business rule stays in the service that owns the data, libraries next to that service own timeouts and retries, and that pairing is the design to defend.

Every request from outside should meet one front door. That door checks that the caller is authenticated, applies a limit, and chooses a service. Then it gets out of the way. The rule that says whether this coupon applies, or whether this refund is larger than the order, stays in the service that holds the rows. Put that rule in the door and every product change becomes a release of the entire edge.

Core concepts

An API gateway is a layer-7 reverse proxy with opinions. Load balancing distinguishes L4, which forwards TCP or UDP without reading the HTTP, from L7, which can route on path, host, and header and can terminate TLS. A gateway is the L7 end of that idea, placed at the edge, with three jobs it owns and one job it refuses.

It owns authentication in the narrow sense: this credential parses, the signature checks out or the session exists, and the credential has not expired. It owns a rate limit aimed at abuse, because the edge is where you can say no before a flood reaches the fleet. It owns routing: this host and path go to this service. It refuses the business rule. Pricing, inventory truth, and who may refund this specific order are decisions that need the service’s data. A gateway that computes them becomes a second copy of every service, deployed on the critical path of all of them.

Rate limiting still applies twice in an honest design, in two different places. At the edge, you stop a single token or a single network from overwhelming the front door. A token bucket there spends a burst and then refills. Inside the service, you limit calls to a scarce dependency, such as a database pool or a payment provider. A distributed limiter, one counter in a shared store, is correct and adds a round trip. A local limiter is fast and approximate. Many systems run a local limit in front of a coarser shared one. The gateway is the right home for the abuse limit. It is the wrong home for “only three refunds per order,” because that rule is the product.

Routing stays dumb on purpose. Path and host are enough for a first design. Header routing earns its place when you are shifting a fraction of traffic to a new revision. The gateway is a natural canary control for that fraction. It is not the place that decides the fraction by reading the request body and applying a pricing experiment. Experiments that change behavior belong with the service, behind a flag, so a bad flag rolls back without touching the router.

What the service still does: authorization against the actual resource, the business write, and the client behavior on its own outbound calls. A gateway plus libraries is the design to defend. Libraries are how a small system gets timeouts, bounded retries, and a circuit breaker without operating a second network product. A retry in that library belongs only on a call that is idempotent or carries an idempotency key, with backoff and a budget that fits the caller’s deadline. Those rules are the retries and circuit breakers page. The gateway should not invent a second retry policy that ignores them. A gateway that blindly retries a POST will double-charge the moment the first attempt succeeded and the response was lost.

Identity forwarding is the subtle job. If the credential is a signed token, every service can check the signature locally. That check is CPU, not a network round trip, and it means a caller who bypasses the gateway cannot invent a header that says who they are. If the credential is an opaque session, resolving it is a lookup. Do that lookup once, at the gateway, and forward a result the services will trust only on a path the rest of the network cannot use. Trusting a user-id header from any caller is the bug. The header is a claim. The signature, or the private path, is why you believe it.

The published Netflix architecture of the open-source years is the picture to keep, with the caveat that it is the architecture they wrote about then. An edge gateway in the Zuul era, client-side load balancing, and Hystrix circuit breakers living in the process. Hystrix is in maintenance. Do not say it is what they run now. The split to steal is the one on this page: the edge owns the front door, and a library in the client owns the behavior when a dependency is sick. How Netflix streams separates that control path from the video bytes. The bytes do not go through the same door.

The gateway process itself should be stateless. More than one instance sits behind a load balancer. Sticky sessions at this layer hide a bug in that statelessness and then pin a hot client to a dead instance. Health checks need to mean “this instance can serve,” and connection draining needs to finish in-flight requests before a deploy kills the process. Those are load-balancing basics, and the gateway is where a design review will ask you to apply them.

A worked example

Six services on the checkout path each “added rate limiting” after an incident, in six repositories. Cart copied a fixed window of 100 requests per minute. Pricing built a token bucket at 20 per second with a burst of 40. Inventory shipped nothing. Tax keeps a counter in process memory, and tax runs eight instances. Payment put a counter in a shared store after a processor cut them off. Order forked cart’s window from last year, boundary bug included.

An abusive key sends 2,000 requests in 10 seconds. That lump is an assumption about the shape of abuse, not a measured attack. A polite reading of one million requests a day is the wrong picture of the same key.

1 day = 86,400 seconds
1,000,000 / 86,400 ≈ 11.6 per second average
the incident is the lump, not the average

fixed window, 100 per minute
100 at the end of minute 1, 100 at the start of minute 2
= 200 in about 2 seconds
intended average = 100 / 60 ≈ 1.7 per second
boundary burst = 100 per second
100 / (100/60) = 60
about 60 times the rate the window was meant to express

token bucket at the gateway, a cap you choose and state
burst 100, refill 50 per second, bucket starts full
2,000 requests over 10 seconds
accepted ≈ 100 + 50 * 10 = 600
rejected ≈ 1,400

tax, local cap assumed at 100 per second per process
8 instances * 100 = 800 per second
the team believes the cap is 100 per second

Inventory accepts all 2,000, because it never says no, and its database takes the burst the other services thought they had covered. There is no single number you can call this key’s rate. A token bucket on the gateway, one per key, is that number. The lump dies at the door. Payment still keeps its own limit for the processor, a scarce dependency the gateway should not pretend to know. Edge for abuse. Service for the scarce thing. A library is how the other five stop inventing a sixth algorithm. A local limiter is fast and approximate, and the approximation is the outage when you needed a hard cap.

The lump was one key. The next figures size the whole door, and they are a separate assumption.

A shop peaks at 2,000 requests per second at the edge. That is an assumption you say out loud, not a measured figure from a named company. Average traffic is lower. One million requests a day is only about 12 per second, because a day has 86,400 seconds and the interview shortcut is about 100,000 seconds. 2,000 per second is a peak you assumed for a sale, on the order of a hundred times that calm day, and you design the door for the peak.

Each user is allowed 10 requests per second at the edge, another assumption, enforced with a token bucket so a short burst can pass. A single abusive caller then contributes 10, not 2,000. The rest of the capacity stays for everyone else. The orders service applies a second limit: 50 concurrent calls to the payment provider, because that provider is the scarce dependency and the edge limit does not know about it.

Session lookups are the cost of doing the door’s job in the wrong place. Assume an opaque session and a 1 ms lookup, same-region, as an assumption. Dean’s same-datacenter round trip is 0.5 ms, so 1 ms is a planning figure for a lookup that does a little more than the network. Six services on the checkout path each do the lookup themselves:

one day                                      86,400 seconds
calm-day rate, 1,000,000 requests            about 12 per second
peak at the edge, assumption                 2,000 requests per second
session lookup, assumption                   1 ms
lookups if only the gateway resolves it      2,000 per second
lookups if six services each resolve it      6 * 2,000 = 12,000 per second
added latency on a serial chain              6 * 1 ms = 6 ms
chances for the session store to fail the call  6 instead of 1

Six milliseconds will not dominate a checkout by itself. Twelve thousand lookups per second on a store you sized for two thousand will. The failure shows up as a session store that was fine in the diagram and hot in production, and as a checkout that fails when that store blips even though five of the six services had no local reason to be down. Resolve the opaque session once. Pass a signed, short-lived result downstream, or do the work on a private path those services already trust. If the token is already signed, skip the shared lookup and let each service verify locally. Local verification does not multiply through the session store.

The business-rule failure is a coupon. Someone puts “twenty percent off if the header says the campaign” in the gateway, because the gateway already sees the header. The sale changes the rule. You deploy the gateway. The new process fails its health check. Every route, including login and search, goes with it. The symptom is an incident whose trigger is a pricing change and whose blast radius is the front door. The coupon rule belongs in the pricing service. The gateway continues to route /pricing to that service while you roll the rule back.

A second numeric cut of the same idea. Suppose the gateway also retries every failed call once, with no regard for the method. At 2,000 requests per second, a downstream that is timing out on 20 percent of calls produces 400 retries per second of extra load, aimed at the dependency that is already late. If those calls are creates, a fraction of the 400 are double applies. The library in the order service, which knows the idempotency key and the remaining deadline, is the place that may retry. The door’s job during that incident is to shed, not to multiply. A bounded queue and a 503 are cheaper than a second copy of a sick call.

flowchart LR
  client[Client]
  door[API gateway]
  orders[Orders service]
  pay[Payment provider]
  client --> door --> orders --> pay

The client meets the door. The door routes. The order service talks to the payment provider through a library that knows the call is idempotent and knows how much time is left. The coupon table is not in the door.

Tradeoffs

Choice What you gain What you spend
Authenticate and limit at the gateway One place that says no before the fleet, one session lookup A front door you must run as a fleet, and a failure domain in front of every route
Authorize in the service that owns the row The decision sees the order and the caller Every service learns how to read an identity and check it
Abuse limit at the edge, scarce-dependency limit in the service Each limit sits where the cost is paid Two policies to explain, instead of one number that is wrong for both
Local JWT verification in every service A bypass of the gateway cannot forge a user by writing a header CPU on each request, and key distribution when you rotate
Opaque session resolved once at the edge The session store sees one lookup per request Downstream must trust the forwarded identity, so the network path has to deserve that trust
Retry inside a library that sees the idempotency key Retries stay on calls that can tolerate them, inside the deadline Each client carries a library you have to keep current
Business rule in the gateway A short path for a rule someone wanted this week Every rule change deploys the front door, and a bad rule takes every route with it

Stateless gateway instances are the availability plan for the door itself. Two instances behind a load balancer, drained on deploy, beat a single clever process. The moment the door stores sessions in local memory, you have invented stickiness. Shared session storage, or a signed token the instance does not store, keeps the door replaceable.

Pitfalls

  • A coupon, a tax table, or a refund cap implemented in the gateway. The symptom is a pricing deploy that logs users out, because the door and the rule shared a release.
  • Trusting a user-id header from any source. The symptom is a caller who reaches a service directly and sends the header of someone else.
  • Every service resolving an opaque session. The symptom is a session store scaled to a multiple of the real request rate, and a chain that fails when that store fails.
  • The gateway retrying unsafe methods. The symptom is duplicate orders during a partial timeout, aimed at the dependency that was already in trouble.
  • An abuse limit that is also trying to be the database pool limit. The symptom is either a database that still gets crushed, or legitimate users who get told no because a global number was set for the wrong resource.
  • Sticky sessions on the gateway. The symptom is a deploy that never quite drains, and a hot client that dies with one instance.
  • Health checks that always pass while the process cannot reach its config. The symptom is the load balancer sending traffic to a door that returns errors for every route.
  • Opening on hop-by-hop machinery before the door is clear. The symptom is an interview spent on certificate rotation instead of on the request path.

In the interview

Draw the client, the gateway, and one service. Say the three jobs the door owns: authenticate, limit, route. Say the job it refuses: the business rule, with the coupon as the example. Say outbound timeouts and retries live in a library next to the code that knows whether the call is idempotent. Mention that the door is stateless and that you run more than one instance.

Skip product names. If they ask how services identify each other on the hop, give the advanced answer on this page, then come back to the door. The question that usually follows is “where do you rate limit?” Answer with both places. Abuse at the edge, the scarce dependency inside the service, and a shared counter only where being wrong by a few percent is unacceptable. Put the 2,000-to-12,000 lookup arithmetic on the board if they suggest every service should call the session store.

Check yourself

A teammate implements the coupon discount in the gateway because the gateway already reads request headers. What breaks when the coupon rule has a bad deploy?

The front door is now coupled to a pricing change. A failed gateway deploy takes login, search, and checkout down together with the discount. The rule belongs in the pricing service, which owns the data and can roll back without taking the router with it. The gateway keeps routing to that service.

The edge peaks at an assumed 2,000 requests per second and six services each do a 1 ms session lookup. What load does the session store see, compared with resolving the session once?

Six times 2,000 is 12,000 lookups per second, against 2,000 if the gateway resolves the opaque session once. The serial chain also adds about 6 ms and six chances to fail. A signed token verified locally does not hit the session store at all. The lookup is the expensive shape, and it belongs once on the door.

Why is a gateway plus libraries the design you defend for a new-grad system?

The gateway already owns authentication, the abuse limit, and routing. Libraries next to the service own timeouts, bounded retries of idempotent calls, and circuit breakers, which need the idempotency key and the deadline the service can see. That split is enough to defend. Heavier hop-by-hop machinery is the advanced note on this page, and it is not the opening answer.

The gateway retries every failed downstream call once, including creates. What do you expect during a partial timeout?

Extra load on the dependency that is already late, and duplicate creates wherever the first attempt succeeded and the response was lost. At an assumed 2,000 requests per second and a 20 percent timeout rate, that is about 400 extra attempts per second. Retries belong in the client that holds the idempotency key and the remaining budget. The door should shed with a 503 instead of multiplying an unsafe call.

A service trusts a user-id header and is reachable from more than the gateway. What is the failure?

Anyone who can open a connection to the service can claim to be any user by writing the header. The header is a claim, not a proof. Either the service checks a signature itself, which is local CPU, or it accepts the header only on a path that other callers cannot use. Authentication at the door does not survive a bypass.

Based on: Marc Brooker and the AWS Builders' Library; Google SRE book; Netflix published architecture, Zuul era.