Skip to content

API gateway and backends for frontends

Once an application is a set of services, a client such as a phone has a problem. The Azure Architecture Center lists what happens if it talks to the services directly: client code that must track many endpoints, coupling to how the backend is split, several network round trips for one operation, every public service repeating authentication, TLS and client rate limits, a choice of protocols limited to what a browser can speak, and a larger attack surface from all those public endpoints.

An API gateway answers this with one entry point. It acts as a reverse proxy: clients call the gateway, and it routes each request to the right service.

Mental model. A gateway is the reception desk of a building. Visitors do not wander the corridors looking for a department. The desk checks who they are, sends them to the right floor, and turns away anyone who has been coming too often. It does not do the work of the departments.

The Azure Architecture Center describes three patterns that a gateway can serve, and they make a useful list of its jobs.

Job What it does Example
Routing Sends a request to a service by path, host or header, at layer 7, behind one endpoint /orders/* to the order service, /search/* to search
Offloading Does a cross-cutting task once, so that each service does not TLS termination, checking a token, rate limiting each client, logging, response caching
Aggregation Takes one request from the client, calls several services, combines the answers A home screen built from profile, orders and recommendations

The first two are why a gateway is useful, and the third is where it starts to be dangerous. Routing and offloading are generic: a gateway can do them without knowing what an order is. Aggregation knows which services make up a screen. The Azure Architecture Center advises that if aggregation has different resource needs from the other jobs, it is better in a service behind the gateway than inside it.

Each of the offloaded jobs has a lesson of its own. A per-client limit belongs at the edge before load reaches the services, as the where to enforce limits lesson argues. Checking that a token is valid belongs there too, as described in the authentication and authorization lesson. But checking that a customer may cancel this order is the order service’s decision, since it owns the order. A gateway that authenticated the caller has not made the network behind it safe: the zero trust lesson says that a request is not trusted because of where it came from.

What does not belong in a gateway is business logic. A discount rule in the gateway means every team must change the gateway to change its own rules, and the gateway becomes a new monolith, a point that Sam Newman makes about the general-purpose API backend: a piece of smart middleware that is not focused on any business domain.

The Azure Architecture Center’s reason for aggregation is chattiness. A phone on a mobile network has a high round-trip time, and each separate request to a service is a new chance to be slow or to fail.

Say the home screen needs data from four services. The profile comes first, because the others need the user id. Then the orders, the recommendations and the notifications, which can go in parallel. The phone is on a network with a round trip of 80 ms. Called directly, that is two rounds of 80 ms, so 160 ms plus the services’ own time, and 4 requests, each on its own connection. Through a gateway or backend that does the aggregation, the phone makes one request and waits 80 ms, and the aggregator makes the same two rounds inside the data centre, where a round trip is, say, 2 ms: 4 ms. The total is 84 ms for the network part, against 160 ms. These figures are made up, but the structure is real: the slow link is crossed once, the fast links many times.

The saving only exists when the client is far from the services. The Azure Architecture Center says the pattern may not suit a client that is near the backend, where latency is not a significant factor.

Check your understanding: gateway and BFF

This quiz needs JavaScript to check your answers.

Question 1 of 3

All traffic enters through one API gateway that is available 99.9% of the time. Each service behind it is available 99.95% of the time. They fail independently.

What is the availability of a request to one service through the gateway?

Enter a number and choose its unit.

percent
Question 2 of 3

The mobile app needs a screen that combines data from four services, and the web app needs a much larger version of it. One shared API service keeps receiving conflicting requests from both teams.

What does a backend for each client change?

Choose one answer.

Question 3 of 3

The peak is 18,000 requests a second and one gateway instance handles 5,000. The gateway must still carry the peak when one instance is lost.

How many gateway instances does it need?

Enter a number and choose its unit.

instances

A gateway serves every client alike. But a phone, a desktop browser and a partner’s integration do not want the same thing. Sam Newman describes the problem: the mobile device has less screen, so it shows less data. Opening many connections drains the battery and the data plan. And what the mobile app does is different, not only smaller, so it wants different calls. A single general-purpose backend is asked by every client for its changes, they conflict, and a team grows around it to referee. Newman notes that this backend can also become the bottleneck for releases, as so many changes are being made to one deployable.

The backend for frontend, BFF, is the answer he wrote up after seeing it used at REA and SoundCloud: one backend for each user experience. Think of a user-facing application as two parts, a client outside your perimeter and a server-side part, the BFF, inside it. The BFF is tightly coupled to one interface and is usually maintained by the same team as that interface, so releases of the client and the server part line up. It is small because it does one thing.

How many? Newman’s preference is one BFF for each type of client, so iOS and Android would have one each. He has also seen one BFF shared by both mobile platforms of a single application, which works when the same team owns the apps and the BFF, and which he sees as more likely to grow into a catch-all as more clients share it. Conway’s law applies: the structure of the teams decides which is better.

The Azure Architecture Center adds the costs. Each BFF is another service with its own life cycle, deployment and security. It adds a network hop between the client and the services. Some code is duplicated across BFFs. And it says that a BFF should only handle client-specific logic: monitoring, authorization and the like are cross-cutting and belong elsewhere. It also names cases where a BFF may not be worth it: when all interfaces make the same or similar requests, when only one interface uses the backend, and when an API gateway in front of microservices is already enough. A GraphQL layer in which clients choose their own fields can also remove the need.

In practice the two combine. A gateway at the edge does routing and offloading for everything, and behind it, one BFF per client type does the aggregation and shaping for its client and calls the services.

Everything that goes through the gateway depends on it. Say the gateway is available 99.9% of the time, and each service behind it 99.95%. A request to one service passes through both, so the availabilities multiply: 0.999 × 0.9995 is 0.9985, which is 99.85%. The gateway’s own 0.1% is added to the unavailability of every service in the system at once. Over a 30-day month, 0.1% is 43.2 minutes during which every request fails, however healthy the services are.

The Azure Architecture Center says so directly: a gateway may introduce a single point of failure, so make sure it meets your availability requirements, and it may become a bottleneck, so make sure it can carry the load and scale, and test it with load. Both lead to the same answer, which is several instances.

Capacity. Say the peak is 18,000 requests a second and one instance handles 5,000. 18,000 / 5,000 is 3.6, so you need 4. One more makes it 5, so that losing an instance leaves 4 × 5,000, which is 20,000, above the peak. Without the spare, the loss of one instance leaves 15,000 against 18,000.

Availability. Two instances that each work 99.9% of the time and fail independently are both down with probability 0.001 × 0.001, so the pair is available 99.9999% of the time. Do not believe it. A bad configuration is pushed to both instances, or both depend on the same service for their keys, or the same bug is in the same release. Failures of that kind are not independent, and they are the common ones. Redundancy removes the failure of one machine and does nothing for a failure of the shared parts.

Gateway and BFF are not options of the explorer, but the same framework applies to both. For the gateway:

  • Decision. One entry point for all clients, which routes requests to services and does the cross-cutting tasks once.
  • Why? Clients do not need to know how the backend is split, services do not repeat authentication and TLS, and one operation does not need several round trips.
  • Benefits. Simpler clients. Backend structure that can change behind a stable address. Cross-cutting tasks in one place. A smaller attack surface.
  • Costs. One more hop and one more component to run. Every team’s routes pass through it, so changes to it must be managed.
  • Failure modes. The gateway down means everything is down. A slow service ties up the gateway’s threads or connections for every route. Business logic creeps in until it is a monolith.
  • Scaling limitations. All traffic goes through it, so it must carry the peak and scale out. Aggregation adds work that differs from routing.
  • Alternative. A BFF for each client type, which shapes the calls to the services for one client, or direct calls from clients when there are few services and one kind of client.

What happens if the gateway goes down, or one service is slow?

Section titled “What happens if the gateway goes down, or one service is slow?”

If the gateway goes down, the clients can reach nothing, and a dashboard that watches the services shows all of them green. This is the case that a health check on the path through the gateway, rather than on each service alone, is meant to catch.

A slow service does damage in a quieter way. Say the gateway has 1,000 worker connections shared by all its routes. A reporting service that normally answers in 50 ms starts taking 5 s, at 200 requests a second. By Little’s Law the gateway holds 200 × 5, or 1,000 connections for it, which is all of them within five seconds, and the routes to every other service start to fail with nothing wrong behind them. A timeout of 500 ms brings it to 200 × 0.5, which is 100. A limit on connections for each route, a bulkhead, keeps the damage in that one route. The bulkheads and timeouts lessons have the details, and the rule is the same as for any caller: a shared resource lets the slowest dependency set the pace for all.

  • A gateway is one entry point that routes by path, offloads cross-cutting jobs (TLS, token checks, per-client limits, logging) and can aggregate calls. Business rules and per-resource authorisation stay in the services.
  • Aggregation saves round trips over a slow link: two rounds of 80 ms are 160 ms, against 80 ms plus two rounds of 2 ms (84 ms) through an aggregating backend.
  • A BFF is a backend for one kind of client, kept by the team that owns that client. It costs a service, a hop and some duplicated code, and it should hold only client-specific logic.
  • The gateway multiplies into every availability: 99.9% × 99.95% is 99.85%, and 0.1% is 43.2 minutes a month with everything down. 18,000 requests a second at 5,000 an instance need 4 instances, and 5 to survive losing one.
  • A slow service can use up the gateway for every route: 200 requests a second held 5 s is 1,000 connections, and a 500 ms timeout makes it 100.

Next: recap of the module, a checklist for choosing a style, and a quiz.

Your progress

Built by GhaziAlibi.

© ShardCraft. All rights reserved.