Chapter 12 of 27 · Part 6: External API and UI

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

Where we are

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.

This chapter

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

Problem

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.

A mobile app calling services directly Mobile app Order svc Kitchen svc Delivery svc getOrder() getTicket() getDelivery() plus getBill() from Accounting combine on phone Four slow mobile round trips for one screen. The monolith needed one call: getOrderDetails().

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.

Why clients should not call services directly Problems with direct calls Poor UX mobile latency Complex app app does joins Battery drain every call costs Coupling slow app releases Protocols gRPC, AMQP
Solution · API gateway

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.

The same screen through an API gateway Mobile app API gateway Order svc Kitchen svc getOrderDetails() getOrder() getTicket() Delivery + Accounting in parallel order ticket one combined reply One call over the slow network. The fan-out happens on the fast internal network.

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.

Cost

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.

Problem

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.

What an API gateway does API gateway single entry point (facade) Routing path to service Composition join results Translation REST out, gRPC in Client API per client type Edge funcs auth, limits
Solution · Edge functions at the gateway

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.

Edge functions Edge functions Authentication Authorization Rate limiting Caching Metrics and request logging Where they can live Backend services caching, authorization Separate edge service central, one extra hop API gateway fewer hops, simpler

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.

API keys, rate limits and usage tracking Gateway products grew out of the API economy: keys for third parties, limits and usage tracking for billing. Client sends API key API gateway Check key who is calling Rate limit how often Track usage for charging Service
Many teams only need a simple reverse proxy for their own web and mobile clients.
Cost

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.

Problem

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.

Different clients, different needs Web apps Inside firewall fast LAN: direct is OK Browser JS Easy to update but internet latency Mobile apps Slow networks slow store releases Third parties Need stability API must not break

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.

Inside an API gateway Clients mobile, browser, third party API layer Mobile API · Browser API · Public API Common layer authentication, logging, metrics Services Order, Kitchen, Delivery, ...
Solution · Backend for frontend (BFF)

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.

BFF pattern Backend for Frontend one gateway per client Mobile API mobile team owns it Browser API web team owns it Public API API team owns it Each client team builds and runs its own API. A shared library gives the common layer.
Central gateway versus BFF One shared gateway has unclear owners and becomes a bottleneck. A BFF is single-purpose, owned with its UI. Central aggregating gateway Backend for frontend Who owns it? Often a silo team Every team edits one deployable Bloats as each client differs Built for one user interface Owned by the same team as the UI Tight coupling to the UI is fine A BFF is like the server half of the user interface.

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.

What an aggregating gateway returns The gateway makes the calls, keeps only the fields the screen needs and sends one small reply. It can also batch many ids into one request. Consumer svc full record Order svc all order fields Gateway keeps name and the 5 latest orders Phone one small reply Batching: one request for 10 order ids instead of 10 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.

How many BFFs? One experience, one BFF. REA gave each mobile app its own BFF because separate teams built them. SoundCloud used one for both listener apps. REA: two teams, two BFFs SoundCloud: one mobile team Android iOS Android BFF iOS BFF Android iOS Mobile BFF Team boundaries decide. SoundCloud staff said they might split theirs.

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.

Extract on the third use Two BFFs that repeat the same three calls can share a new Favorites service. Wait for the third use before extracting. Duplicated in each BFF Extracted service Android BFF iOS BFF Consumer Restaurant Order Android BFF iOS BFF Favorites svc makes the 3 calls Rule of thumb: build the abstraction when you are about to write it a third time.
A BFF can also front one third party, such as a partner's listing site or an in-car app. A breaking change for one partner then does not hit the others, and you avoid keeping old API versions alive for everyone.
Cost

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.

Problem

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.

Solution · Non-blocking, failure-aware gateway

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.

Performance: blocking versus non-blocking I/O Synchronous I/O Thread per connection heavy under load Async / non-blocking I/O Event loop Netty, Spring WebFlux, Node Netflix's Zuul 2 got about 25% more throughput for I/O-bound work after the switch.
Design issueAnswer
Performance and scaleNon-blocking I/O on an event loop
Readable concurrent codeReactive abstractions: Mono (Spring), RxJava, JavaScript Promises
Partial failureA circuit breaker per service, with a cached or default fallback (see chapter 18)
Being a good citizenUse service discovery to find instances, and the same logs, metrics and traces as every other service
Cost

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.

Problem

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.

Implementing a gateway Off the shelf AWS API Gateway no composition AWS ALB basic routing only Kong, Traefik you run it; no composition Build your own Netflix Zuul routes by path only Spring Cloud Gateway routes + custom handlers Composition needs code, so one common build uses Spring Cloud Gateway.
Solution · Product for routing, code for composition

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.

Cost

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.

Problem

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.

Solution · GraphQL-based gateway

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.

A GraphQL query replaces several REST calls With REST the client gets every field and makes a second call for delivery. A GraphQL query asks for exactly the fields it wants, and resolvers fetch them. REST GraphQL GET order: every field GET delivery: a second call order(id: 123) { total status delivery { company driver duedate } } Resolvers call the right services To add or drop a field, change the query, not the server. New types or fields still need a server change.
A GraphQL-based gateway Client query only fields it needs GraphQL schema types + queries Resolvers fetch from services One response nested result One flexible API serves very different clients.

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.

Batching and caching in GraphQL Without batching 10 orders → 10 calls to Restaurant svc The N+1 problem With DataLoader Loads in one tick are batched 10 orders → 1 batch call Cache skips repeat loads
GraphQL: strengths and cautions It shines at the edge for GUIs and external APIs. Watch query load, caching and writes, and do not treat services as thin database wrappers. Heavy queries Clients shape queries. Hard to throttle. Caching Harder than REST. CDNs help less. Writes Fit less well than reads. Many teams use REST. Best at the edge: mobile and GUI clients, and external APIs such as GitHub Not a database API: keep each service's own logic behind the query
A GraphQL server can act as a BFF. Keep one per team boundary, because new types and fields still need server changes. Use it at the edge, not for service-to-service calls.
Cost

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.

Problem

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.

North-south and east-west traffic An API gateway handles traffic entering from outside the perimeter. A service mesh handles calls between services inside it. Clients API gateway north-south Inside the perimeter Order svc Accounting svc mesh east-west: service mesh one outside call, many inside
Solution · Generic gateway and mesh, logic in services

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.

Using a gateway well and badly Keep the gateway generic. When aggregation or protocol rewriting creeps in, business logic ends up in a vendor product. Good uses Misuse Reverse proxy to inside services API keys and rate limits Logging and usage tracking Call aggregation grows into logic Protocol rewriting Routing internal calls through it Need aggregation? Use GraphQL or a BFF. If it is a business process, model it as a saga.

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.

How a service mesh works A proxy runs beside every service, so calls stay local as far as possible. A control plane sets their behavior, such as timeouts and certificates. Control plane Pod A Pod B Order svc Local proxy Local proxy Accounting svc network Order Service thinks it makes a normal network call. Timeouts, retries, mutual TLS and logging live in the proxy, not in each service.
API gatewayService mesh
TrafficNorth-south: from outsideEast-west: between services
ShapeReverse proxy at the perimeterProxy beside each service, plus control plane
Typical jobsAPI keys, rate limits, routingDiscovery, timeouts, mutual TLS, logging
RuleKeep behavior genericKeep behavior generic
A mesh pays off with many services, several languages and Kubernetes. With five microservices it is hard to justify, and switching meshes later is painful. Treat the choice like choosing a broker or a cloud: it is on the critical path.

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.

Only the gateway is public In one video app the customer-facing gateway and an admin gateway are the entry points. Other services live inside the cluster. Browser Frontend gateway public address Admin gateway separate entry Kubernetes cluster: internal only video-streaming video-upload history metadata rabbit db
Private video storage is reachable only through the app, never straight from the internet.
In FlixTube's kubectl listing, only the gateway service has an external IP. Every other service is a ClusterIP service, visible inside the cluster only.
Cost

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

PatternProblem it solvesWhat it costs
API gatewayClients make many slow calls per screen and depend on internal service APIsAnother highly available component on every request
Edge functions at the gatewayEvery service repeats authentication, rate limiting and loggingThe 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 needsMore deployables; some duplicated code
Extract on the third useThe same calls are repeated in several BFFsTolerate duplication until the shared need is clear
Non-blocking, reactive gateway with circuit breakersThe gateway runs out of threads or waits on a slow serviceReactive code is harder to write and debug
Product for routing, code for compositionProducts route well but cannot compose repliesA hand-written endpoint per composed reply
GraphQL gateway (with DataLoader)A new endpoint per screen or client; over-fetching and extra callsHeavy queries, harder caching, weaker for writes
Service meshEvery service implements time-outs, mutual TLS and logging for internal callsCritical infrastructure; hard to justify for few services
Generic edge, logic in servicesBusiness processes leak into vendor gateway configurationAggregation must live in a BFF, GraphQL or a saga

Recap

Quick check

How does a GraphQL gateway avoid ten calls to Restaurant Service for ten orders?
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().

FTGO's mobile, web and partner teams all change one central gateway owned by a platform team. Releases slow down and the code fills with client-specific branches. What is going wrong, and which pattern fixes it?
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.

Why is it risky to do call aggregation inside a vendor API gateway product?
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.

Still open

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.

Next: 13 UI patterns: micro frontends and live updates →