Load balancing, gateways and discovery
Why Dabba runs thirty servers where twenty would do, how the balancer picks one, what the gateway checks first, and how a health check can remove a healthy fleet.
The API contract says what a request looks like. This chapter is about where it goes. Between the customer’s phone and Dabba’s order code sit a few boxes that most teams configure once and then forget: a load balancer, an API gateway, and whatever tells them which servers exist right now. They are easy to forget because they usually work. When they fail, they fail for every request at once.
We will size Dabba’s API tier from the brief, then follow the decisions the boxes in front of it make: what they can see of a request, how they pick a server, how they decide a server is unhealthy, what happens to requests in flight during a deploy, and which jobs belong in the gateway.
How many servers, and why thirty
The brief set a design target of 10,000 API requests a second at the dinner peak. Suppose a typical request costs about 5 ms of CPU time once caching is in place (the reads chapter earns that number). A server with 4 cores can then do at most 4 × 1,000 / 5 = 800 requests a second at full CPU. Nobody runs servers at full CPU, because queueing delay rises steeply as utilisation approaches 100%, so we plan for about 60%, or roughly 500 requests a second each. That gives 10,000 / 500 = 20 servers.
Twenty is the number needed when everything is up. Dabba runs in three availability zones in Mumbai, and a zone can fail as a unit: a power or network problem takes out every server in it. To survive that at peak, the other two zones must carry the full load, so they need 20 servers between them, 10 per zone. Three zones of 10 is 30 servers. A third of the fleet is idle on a normal evening, and that is the price of surviving a zone loss at 8:30 pm. The same arithmetic applies to every tier.
Thirty servers only help if requests are spread across them sensibly, and only if the servers hold no state that ties a customer to one of them. Dabba’s API servers keep no session data in memory; anything that must survive a request lives in the database or the cache. So any server can handle any request, a server can be removed at any time, and adding capacity means starting more copies.
What the balancer can see decides what it can do
Load balancers come in two broad kinds, named after the network layer they work at. A layer 4 balancer sees TCP connections: source and destination addresses and ports. It chooses a server when a connection opens and then forwards bytes without reading them. That makes it fast and simple, and blind to everything inside the connection. A layer 7 balancer terminates TLS, parses HTTP, and chooses a server for each request. It can route /v1/orders to the order service and /v1/restaurants to the catalogue service, retry a failed GET on another server, and record the status code and latency of every request. It pays for that with CPU and with holding the TLS keys.
The difference matters most with long-lived connections. Dabba’s app keeps one HTTP/2 connection open for a whole session and sends all its requests over it. Behind a layer 4 balancer, every one of those requests goes to whichever server the connection landed on. The same happens inside the data centre, where Dabba’s services call each other over gRPC, which also uses long-lived HTTP/2 connections. Suppose the menu service calls the pricing service through a connection-level balancer. Each menu server opens one connection and keeps it for hours, so all its calls go to one pricing server. When the pricing service is scaled from 6 servers to 12 for the evening, the new 6 receive almost nothing, because no menu server has opened a new connection. The fleet looks doubled on the dashboard and behaves as if it were not.
Dabba therefore uses layer 7 balancing wherever connections are long-lived: a managed HTTP load balancer at the front of the region, and request-level balancing for service-to-service gRPC (either the client library balancing across all servers, or a proxy that balances per request). A layer 4 balancer is still a good fit in front of the layer 7 tier itself, where its job is to spread connections across a handful of proxy machines that each handle thousands of them.
Picking a server when requests are not alike
Round robin, sending each request to the next server in turn, is the default in many balancers. It assumes every request costs the same and every server is equally fast. Neither is true at Dabba. A cached menu read takes a few milliseconds; placing an order waits on the database and the payment provider for hundreds. And servers are not identical in practice: one shares a physical host with a noisy neighbour, another is in a long garbage collection pause, a third is warming its local cache after a restart.
Thirty servers share 10,000 requests a second by round robin, about 333 each, while each can handle about 800 a second at full CPU. One server slows down so that each request takes three times as much CPU. What happens to that server, and to Dabba’s p99?
Show the worked answer
The slow server can now handle about 800 / 3 ≈ 267 requests a second, but round robin still sends it 333. Arrivals exceed capacity, so its queue grows without limit for as long as the slowdown lasts. Requests sent to it wait longer and longer, and soon they time out.
It receives 1 in 30 requests, which is 3.3% of all traffic. Since more than 1% of requests are now very slow or failing, Dabba’s overall p99 latency is set by the single bad server. Twenty-nine healthy servers cannot help, because round robin never looks at how busy a server is.
The remedy is to send work to servers that are keeping up. A balancer that tracks how many requests each server currently has in flight can send each new request to the one with the fewest. A slow server accumulates in-flight requests, so it stops being chosen until it drains, and its share falls to what it can actually handle. This policy is called least outstanding requests, and it is a sturdy default for request-level balancing.
Choosing the single least loaded server has a weakness when there are several balancers, each with a slightly stale view of the counts. They all pick the same apparently idle server at the same moment, overload it, then all move to the next one. The common fix is surprisingly simple: pick two servers at random and send the request to whichever has fewer requests in flight. This “power of two choices” avoids the herd, because different balancers pick different pairs, and it still keeps load close to even. Envoy’s least-request policy works this way by default.
Session affinity, sending one customer’s requests to the same server each time, is the opposite trade. It helps when servers hold useful per-customer state in memory, and it hurts everything else: a popular customer cannot be spread, a server’s death loses whatever it held, and the balancer can no longer route around a slow server. Dabba’s API servers hold no such state, so they do not use affinity. The realtime chapter will meet a case where connections are inherently tied to a server, and we will handle it there.
The health check that took the whole fleet out
A balancer needs to know which servers to avoid, so it asks each one regularly whether it is healthy. What the server checks before answering “yes” turns out to be a significant design decision. Here is how it went wrong for a team that made the natural choice.
The API servers’ /health endpoint checks that the process is running, that it can query Postgres, and that it can reach Redis. The reasoning is sound on its face: a server that cannot reach its data cannot serve requests. At 8:40 pm, Redis fails over from its primary to a replica, which takes about 20 seconds. During those 20 seconds every API server’s health check fails, because every server uses the same Redis. The balancer is configured to remove a server after three failed checks five seconds apart. Fifteen seconds in, it has removed all 30. It now returns errors for every request: menus, orders, order tracking, everything.
Most of those requests did not need Redis. Menu reads could have gone to Postgres at higher cost, order placement does not touch Redis at all, and the failover would have finished five seconds later. A 20-second blip in one shared dependency became a full outage because the health check tested something every server shared. When all servers fail a check together, the check is reporting a dependency problem, and removing servers cannot fix a dependency problem.
The fix separates two questions. Liveness asks whether this process is broken in a way a restart would fix: deadlocked, out of memory, stuck. Readiness asks whether this particular server should receive traffic right now: still starting up, warming its cache, or shutting down. Neither should depend on shared databases or caches. Problems with shared dependencies are handled in the request path, with timeouts and fallbacks of the kind the first chapter introduced, where the code can decide request by request what it can still do.
Two balancer settings act as a further safety net. Outlier detection removes servers based on their real traffic, for example a server whose error rate is far above its peers, and caps how much of the fleet can be removed this way (Envoy’s default cap is 10%). A panic threshold makes the balancer give up on health information when too few servers look healthy: Envoy, by default, spreads traffic across all servers once fewer than half look healthy, and AWS’s application load balancer routes to all targets when all of them fail their checks. Both encode the same judgement: when the whole fleet looks sick, the health signal is more likely wrong than the fleet.
These fixes have a cost. A server with a real local fault, such as a broken network interface or a corrupted local cache, now stays in rotation a little longer, until outlier detection notices its errors. Dabba accepts slightly slower removal of one bad server in exchange for never removing all good ones.
Deploys without dropped orders
Dabba deploys the order service several times a week, replacing servers a few at a time. Each server being replaced has requests in flight. At 150 orders a second with each order request taking about half a second on average, Little’s law gives 150 × 0.5 = 75 order requests in progress across 30 servers, about 2 or 3 per server. Kill a server abruptly and those requests fail, some after the order was written and before the response was sent. Over a rolling deploy of 30 servers, that is around 75 order attempts that fail, and some of those customers do not know whether they ordered.
The idempotency keys from the previous chapter make the retries safe, but it is better not to need them. A clean shutdown, usually called draining, goes in order. When the server is told to stop, it first starts failing its readiness check so the balancer stops sending new requests. It keeps accepting for a few more seconds, because the balancer’s view updates asynchronously; on Kubernetes, a pod can still receive new requests for several seconds after it has been asked to stop, which is why a short pause before shutdown is a common practice. Then it stops accepting, finishes the requests it has, closes idle keep-alive connections, and exits. A 30-second limit on the whole process covers the slowest order request comfortably.
What belongs in the gateway
An API gateway is a layer 7 proxy that does the jobs every request needs regardless of which service handles it. Because every request passes through it, putting a job there means writing it once instead of in every service. For the same reason, anything in the gateway is something every request depends on, and a mistake in it is a mistake for all traffic.
| Job | In Dabba’s gateway? | Reasoning |
|---|---|---|
| Verify the login token’s signature and expiry | yes | same for every request; needs no data beyond a public key |
| Rate limits per customer and per IP address | yes | must run before expensive work; covered in the rate limiting chapter |
| Route by path to the right service | yes | the gateway’s main reason to exist |
| Request IDs, access logs, latency metrics | yes | one consistent record of every request |
| Timeouts | yes | bounded waits at the edge protect everything behind it |
| Retries | only for GET and keyed POSTs | retrying an unkeyed POST can duplicate the action |
| Can this customer see order 9001? | no | needs order data; the order service decides |
| Free delivery above ₹199 | no | business logic; belongs to pricing, deployed and tested with it |
| Composing the home screen | no | a separate backend-for-frontend service, deployed on its own |
The pattern in the table: the gateway authenticates (who is this?) and the service authorises (may they do this to this order?). The gateway applies policy that is the same for every request; anything that depends on business data or changes with the product lives in a service that can be deployed and rolled back on its own.
Timeouts deserve one more look, because they interact with the idempotency design. Dabba’s app waits 10 seconds for an order response. The gateway waits 8, the order service gives itself 7 overall, and its call to the payment provider gets 5. Each layer’s limit sits inside the one above it, so an inner layer gives up and returns a meaningful error before the outer one gives up and returns a generic timeout. If the order were reversed, with the gateway at 5 seconds and the order service still working for 7, the gateway would return a timeout while the order service went on to create the order. The customer would retry, and only the idempotency key would stand between her and a second order. Passing the remaining time along with each call (gRPC does this with its deadline; HTTP services can use a header) lets every layer stop work that nobody is waiting for.
Finding servers that keep moving
At 7 pm Dabba’s autoscaler adds servers to the menu service, and at 11 pm it removes them. Deploys replace servers several times a week. So the list of servers behind each service is always changing, and something must keep the balancers’ view current. This is service discovery: a registry of which servers exist for each service and which are ready, updated as servers start, pass readiness, and stop.
On Kubernetes, the registry is built in: each service has a list of endpoints, filled from pods that pass readiness. Callers find it in one of two ways. With server-side discovery, the caller sends requests to a stable address and a proxy or balancer behind it looks up the current servers. With client-side discovery, the caller’s own library subscribes to the list and balances requests itself, which removes a hop and gives per-request balancing for gRPC. A service mesh places a proxy next to every server and does client-side balancing, retries, timeouts and encrypted connections in that proxy, configured centrally. It is the same set of jobs, run on every machine, with the operational cost of running the mesh itself.
DNS is the oldest discovery mechanism and has a known trap. Some runtimes and HTTP client libraries cache DNS answers far longer than the record’s time-to-live, or keep connections open to an address indefinitely. When servers are replaced, such clients keep sending to addresses that no longer exist. Whichever mechanism Dabba uses, one system must own the truth about which servers exist, and every caller must be checked to see that it actually follows that truth.
When to keep it simpler
Dabba at this stage has about fifteen services and one region. A managed HTTP load balancer at the front, Kubernetes service discovery, and gRPC clients that balance per request are enough. A service mesh earns its place when there are many teams and many services, when encryption and identity between every pair of services become a requirement, or when traffic rules per route change often enough that changing them in each service is a burden. None of that is true yet.
We should revisit the setup when one of those becomes true, when a second region arrives (routing between regions is a different problem, covered in the multi-region chapter), or when the gateway starts accumulating business rules, which is a sign that a backend-for-frontend or a proper service is missing.
Requests now reach a server that can handle them. The next chapter, Scaling reads, looks at what that server does for the most common request after the home screen: the menu page, read sixteen times for every order placed, and how to make it cheap without showing customers prices or dishes that no longer exist.