API gateway and backends for frontends
FTGO's mobile app would need four calls over a slow network to draw one screen, and it would break whenever an internal service changed. This chapter gives external clients a single, client-shaped entry point: the API gateway, one backend per frontend, and GraphQL.
key idea / coordinator service / good path in progress / watch out problem / failure neutral
In chapter 11 we answered queries that span services, with API composition and CQRS views, and cached the hot reads. That left one problem open: external clients such as the web app, the mobile app and partners still have to know which service to call, and still make many calls per screen.
How should clients outside FTGO's network reach dozens of services? By the end you can place an API gateway, decide what belongs in it, split it into backends for frontends, build it for speed and partial failure, choose between a product, custom code and GraphQL, and keep it apart from a service mesh.
One screen, four round trips: the API gateway
A customer on a train opens order 101 in the FTGO mobile app. The app calls Order Service, Kitchen Service, Delivery Service and Accounting one after another over a slow mobile network, then joins the answers on the phone. The screen takes seconds to appear and drains the battery. In the monolith, one call to getOrderDetails() did the job.
Latency is only the first of several problems with clients calling services directly. The app must contain the join logic. Every internal API becomes a public contract, so splitting a service means waiting until users install a new app version. And some services speak protocols that are awkward outside the firewall, such as gRPC or AMQP messaging.
Put a single entry point in front of the services, like a facade. The client makes one call over the slow network; the gateway fans out to the services over the fast internal network, in parallel where it can, and sends back one combined reply.
This is the API composition of chapter 11, placed at the edge. The gateway also hides how FTGO is split inside, so services can be split or merged without an app release.
The gateway is one more component that must be highly available, because every external request passes through it. And once it exists, every team is tempted to put more into it.
Every service checking tokens: edge functions at the gateway
A single entry point is also the natural place for the jobs every request needs.
Order, Restaurant and Consumer Service each check the caller's access token, each apply their own rate limits and each log requests in their own format. A partner that lists FTGO restaurants on its own site needs an API key and must be billed for its usage, and nobody knows where that should live.
A gateway can do five kinds of work: route each request to a service by its path, compose several calls into one, translate protocols (REST outside, gRPC inside), offer an API shaped for each type of client, and run edge functions.
Handle the request-level concerns once, at the edge: authentication, authorization, rate limiting, caching, and metrics and request logging. Services behind the gateway receive requests that are already checked and counted.
Some of these can also live in the services (caching, fine-grained authorization) or in a separate edge service in front of the gateway, at the cost of one more hop. Gateway products grew up in the "API economy", so the partner case is their home ground: check the API key, limit how often it calls, and track usage for billing.
Now the gateway holds routing, composition, translation, client APIs and edge functions, for every kind of client. Each client wants its API shaped differently, and they all queue up to change the same component.
One gateway, many clients: backends for frontends
A single gateway serves very different clients, and that is where it starts to hurt.
FTGO's mobile team wants small replies and few calls. The web team wants richer data per page and can ship daily. Partners need an API that never breaks. All three must change one gateway, run by a separate gateway team. Change requests queue up, every release risks all three clients, and the code fills with "if mobile then…" branches.
A first step is to give the gateway two layers: an API layer with one module per client (mobile, browser, public), on top of a common layer for authentication, logging and metrics. That separates the code, but not the ownership.
Split the gateway into one backend per user experience, each built for one user interface and owned by the same team as that interface. The mobile team runs the mobile API, the web team the browser API, an API team the public one. A shared library provides the common layer.
A BFF earns its keep through aggregation and filtering. It makes the calls, keeps only the fields its screen needs and sends one small reply. It can also batch: one request for ten order ids instead of ten separate lookups.
How many BFFs? Let team boundaries decide: one per user experience, and one per team that builds it. Two well-known side examples point in different directions. At realestate.com.au (REA), separate teams built the Android and iOS apps, so each got its own BFF. SoundCloud had one mobile team and used one BFF for both listener apps, though its staff said they might split it later.
BFFs for different apps end up repeating the same calls. If FTGO's Android and iOS BFFs both call Consumer, Restaurant and Order Service to build a "favorite restaurants" list, that logic can move into a new Favorites service. Wait until you are about to write it a third time before you extract it, because the wrong shared abstraction is harder to undo than a little duplication.
More deployables to run, and some duplicated code between them. Each BFF still sits on every request of its client, so it inherits the gateway's hardest job: staying fast while the services behind it are slow or failing.
On every request: designing for speed and failure
Whether it is one gateway or several BFFs, the entry point sees all external traffic, so its design decides how FTGO feels under load.
On Friday evening, the mobile BFF serves thousands of order screens. It uses one thread per connection, and each thread waits on four service calls. Threads run out, new requests queue, and when Accounting turns slow every order screen waits for it, even though the payment status is one small line on the page.
Use non-blocking I/O so a few threads can serve many connections, write the fan-out as reactive code so independent calls run concurrently and stay readable, and wrap each service call in a circuit breaker with a fallback, such as a cached value or leaving that part of the reply out.
| Design issue | Answer |
|---|---|
| Performance and scale | Non-blocking I/O on an event loop |
| Readable concurrent code | Reactive abstractions: Mono (Spring), RxJava, JavaScript Promises |
| Partial failure | A circuit breaker per service, with a cached or default fallback (see chapter 18) |
| Being a good citizen | Use service discovery to find instances, and the same logs, metrics and traces as every other service |
Reactive code is harder to write and debug than plain blocking calls. And all of this has to be built, or bought, by someone.
Buy a product or write code?
With the requirements clear, the team must pick an implementation.
FTGO's platform team compares gateway products. Most route requests and handle keys and limits well, but none of them can build the Order Status reply from four services, which is the main reason the mobile team wanted a gateway.
Use an off-the-shelf gateway when routing and edge functions are all you need. When you need composition, build on a framework that routes by configuration and lets you add custom handlers in code, such as Spring Cloud Gateway.
Every composed reply is a hand-written endpoint. Each new screen, or each client that wants a slightly different set of fields, means another endpoint to write, test and deploy.
A new endpoint for every screen: GraphQL
Hand-written endpoints fix the shape of every reply on the server. GraphQL hands that choice to the client.
The mobile Order Status screen needs only the order total, its status and the courier's name and due time. The REST endpoint returns every order field, and the delivery details need a second call. The web team wants different fields for the same order, so the BFF team writes yet another endpoint.
Publish one schema of types and queries. Each client sends a query naming exactly the fields it wants, nested across services. Resolvers behind the schema fetch each piece from the right service, and the client gets one nested response.
Naive resolvers create a new performance trap. A query for a consumer's last ten orders, each with its restaurant, calls Restaurant Service once per order: one query becomes eleven calls, the "N+1 problem". A loader such as DataLoader collects the loads requested in the same tick, sends them as one batch call, and caches repeats.
Clients now shape the load: one expensive query can be hard to spot and throttle. Responses are harder to cache than plain REST URLs, and writes fit less well than reads. And the more the edge can do, the more tempting it is to put business logic there.
Keep the edge generic: gateways, service meshes and the perimeter
Gateways are proxies, and so are service meshes. Mixing up their jobs leads to the most common gateway mistake.
To save time, an FTGO developer adds the "place order" sequence (create order, authorize card, create ticket) to the vendor gateway's configuration language. Another routes Order Service's internal calls to Accounting through the gateway, to get its logging. A year later, a core business process lives in a third-party product that only a few people can edit, and every internal call takes an extra hop.
The two tools handle two directions of traffic. An API gateway handles north-south traffic: requests entering from outside the perimeter. A service mesh handles east-west traffic: calls between services inside it.
Use the gateway as a reverse proxy with API keys, rate limits and logging, and keep its behavior generic. Send internal calls through a service mesh, not the gateway. When you need aggregation, use a BFF or GraphQL; when it is a business process, model it as a saga (chapter 9) in a service.
A service mesh puts a proxy beside every service instance, so calls stay local as far as possible. A control plane configures all the proxies. The service thinks it makes a normal network call; time-outs, retries, mutual TLS and logging happen in the proxy.
| API gateway | Service mesh | |
|---|---|---|
| Traffic | North-south: from outside | East-west: between services |
| Shape | Reverse proxy at the perimeter | Proxy beside each service, plus control plane |
| Typical jobs | API keys, rate limits, routing | Discovery, timeouts, mutual TLS, logging |
| Rule | Keep behavior generic | Keep behavior generic |
The perimeter idea also works at small scale. In the side example of FlixTube, the video app built later in this course, only a customer-facing gateway and an admin gateway have public addresses. Every other service lives inside the Kubernetes cluster, and private video storage is reachable only through the app.
kubectl listing, only the gateway service has an external IP. Every other service is a ClusterIP service, visible inside the cluster only.A gateway and a mesh are two pieces of critical infrastructure to choose, run and upgrade, and both are painful to replace. And the edge only reshapes data; the screens that show it are still one large frontend.
Patterns in this chapter
| Pattern | Problem it solves | What it costs |
|---|---|---|
| API gateway | Clients make many slow calls per screen and depend on internal service APIs | Another highly available component on every request |
| Edge functions at the gateway | Every service repeats authentication, rate limiting and logging | The gateway grows; partner features belong in a product or a BFF |
| Backend for frontend (BFF) | One shared gateway becomes a bottleneck for clients with different needs | More deployables; some duplicated code |
| Extract on the third use | The same calls are repeated in several BFFs | Tolerate duplication until the shared need is clear |
| Non-blocking, reactive gateway with circuit breakers | The gateway runs out of threads or waits on a slow service | Reactive code is harder to write and debug |
| Product for routing, code for composition | Products route well but cannot compose replies | A hand-written endpoint per composed reply |
| GraphQL gateway (with DataLoader) | A new endpoint per screen or client; over-fetching and extra calls | Heavy queries, harder caching, weaker for writes |
| Service mesh | Every service implements time-outs, mutual TLS and logging for internal calls | Critical infrastructure; hard to justify for few services |
| Generic edge, logic in services | Business processes leak into vendor gateway configuration | Aggregation must live in a BFF, GraphQL or a saga |
Recap
- External clients should call an API gateway, not services directly: one call over the slow network, with the fan-out on the fast internal one.
- A gateway routes, composes, translates protocols, offers client-specific APIs and runs edge functions such as authentication, rate limiting and logging.
- A single central gateway becomes a bottleneck, so give each user experience its own backend for frontend, owned by the team that owns that UI.
- Build the gateway with non-blocking I/O, reactive composition and circuit breakers, and choose a product for routing or code when you need composition.
- GraphQL lets each client ask for exactly the fields it needs; batch resolver calls with a loader, and watch query cost, caching and writes.
- Gateways handle north-south traffic and service meshes east-west; keep both generic and keep business logic in services.
Quick check
Show answer
It batches and caches loads with a loader such as DataLoader, so the ten lookups requested in the same tick become one batch call, for example batchFindRestaurants().
Show answer
One shared, centrally owned deployable is serving clients with different needs, so it bloats and every change queues behind one team. Split it into backends for frontends: one per user experience, owned by the team that builds that UI, with a shared library for the common layer.
Show answer
Business processes end up baked into a third-party tool that you can only configure in its own language, which makes the logic hard to test, change or move later. Use GraphQL or a BFF for aggregation, or a saga in a service if it is a real business process.
Clients now have one entry point shaped for them. But the web UI itself is still one big frontend owned by one team, and its screens show data that goes stale the moment another service changes it.