What is the difference between an API gateway and a backend for frontend?

An API gateway and a backend for frontend (BFF) are separate layers, not competing choices. Most systems that need a BFF still need a gateway in front of it. The useful question is which logic belongs in each.

The API gateway is a shared, client-agnostic entry point. It handles cross-cutting concerns that apply to every request regardless of caller: routing, TLS termination, authentication and coarse authorization, rate limiting, request ID injection and coarse response caching. It treats payloads as opaque, so it has no reason to change when a screen changes.

The BFF pattern puts a server-side component behind the gateway, dedicated to one client experience such as the iOS app or the web checkout. Its job is to shape data for that client.

That shaping is mostly request aggregation. One client call, such as GET /home, fans out to the profile, orders and recommendations services. The BFF merges the results and returns one payload with only the fields that screen renders. In a gateway, aggregation lives in plugins, embedded scripts or declarative composition config. In a BFF, it is ordinary application code that you can debug, unit-test and refactor with normal tools.

API gateway BFF
Responsibilities Routing, authN/authZ enforcement, rate limits, TLS, request IDs, coarse caching Aggregation, field selection, payload shaping for one client
Owner Platform team The client's product team
Change cadence Slow, and changes affect every consumer Fast, tracks UI releases
Testing Config validation, integration and load tests Unit tests plus contract tests against downstream services

How does the gateway-plus-BFF layered topology work?

In the layered topology, a request passes through three tiers, and each one owns a different concern. The client calls the gateway. The gateway handles cross-cutting work: TLS termination, rate limiting, token validation and routing by path or host. It then forwards the request to the BFF for that client type, such as mobile-bff or web-bff. The BFF fans out to domain services, combines their responses and returns a payload shaped for one UI.

Identity flow

The gateway checks the token's signature, expiry and audience, then forwards either the original token or a set of verified claims. The BFF passes that identity downstream on every call it makes, rather than using a shared service credential. This matters because each domain service still runs its own authorization: "can user 42 read order 9001?" is a question only the orders service can answer correctly.

The risky shortcut is to treat the gateway's check as the whole security model and skip authorization in the BFFs and services. That only works if nothing can reach them except through the gateway. A misconfigured network policy, a debugging port-forward or a compromised neighbouring pod breaks that assumption, and at that point any caller can set the identity headers to whatever it wants.

Caching moves inward

Gateway caching works well for responses that are the same for every client, such as public catalogue data or configuration. Aggregated BFF payloads are usually personalized. If the gateway caches one keyed only by URL, it can serve one user's data to another. If the cache key includes the user, the hit rate falls close to zero. The BFF knows which parts of its payload are shared and which are per-user, so it can cache the shared upstream calls individually and assemble the personalized parts fresh on each request.

       +-----------+             +-----------+
       |  Mobile   |             |    Web    |
       |  client   |             |  client   |
       +-----+-----+             +-----+-----+
             |  bearer token           |
             v                         v
 +------------------------------------------------+
 | API GATEWAY  (cross-cutting, client-agnostic)  |
 | TLS | rate limit | verify sig/exp/aud | route  |
 | cache: public, same-for-everyone responses     |
 +-----------+-------------------------+----------+
             | token or verified claims|
             v                         v
     +---------------+         +---------------+
     |  mobile-bff   |         |    web-bff    |
     | fan-out+shape |         | fan-out+shape |
     | cache shared  |         | cache shared  |
     | upstream calls|         | upstream calls|
     +-------+-------+         +-------+-------+
             |  identity on every call |
       +-----+-----------+-------------+---+
       v                 v                 v
 +-----------+     +-----------+     +-----------+
 |  orders   |     |  catalog  |     |   users   |
 | own authz |     | own authz |     | own authz |
 | user->obj |     | user->obj |     | user->obj |
 +-----------+     +-----------+     +-----------+
       ^
       : bypass: bad netpol, port-forward, compromised pod
       : forged identity headers -> only service authz stops it

The gateway validates tokens and caches only client-agnostic responses. Each BFF fans out with the caller's identity and caches shared upstream calls. Every domain service still enforces its own authorization, because traffic that bypasses the gateway can carry forged identity headers.

When should aggregation logic go in a BFF instead of the gateway?

The decision rule is simple: put logic in the gateway if it is identical for every client and changes rarely. Authentication, TLS termination, rate limiting and request logging fit that description. Put it in a BFF if it depends on what a particular screen or client needs, changes with product releases, or contains real business logic that deserves unit tests, fixtures and a normal code review process.

Ownership is the deciding factor more often than the technical details. A gateway is usually owned by a platform team. If client-specific aggregation lives there, every UI change that needs a new field or a different combination of calls becomes a ticket in another team's queue. All clients also share one blast radius, so a bad mobile route config can break web traffic. A BFF lets the client team change and deploy its composition logic on its own schedule. That removes most cross-team release coordination for UI-driven changes, and this is where the time savings come from.

This only works if client teams can own and operate backend code: on-call duty, dashboards, dependency upgrades. If they cannot, BFFs end up owned by a central team, and you have rebuilt the gateway bottleneck under a different name.

Concern Belongs in Reason
AuthN, TLS, rate limits Gateway Same for all clients, rarely changes
Routing, coarse request logging Gateway Infrastructure policy
Screen-specific aggregation BFF Follows the UI release cycle
Field shaping, client-specific defaults BFF Differs per client
Business rules in composition BFF Needs tests and team ownership

How do you handle partial failures in request aggregation?

A BFF that aggregates five services has five ways to fail on every request. Design for that from the start.

Set one deadline per client request and derive per-call timeouts from it. If the screen budget is 800 ms, no downstream call should receive more than the time remaining. Independent timeouts that each look reasonable can add up past what the client will wait for.

Fan out in parallel by default. Make calls sequential only when one needs a value from another, such as fetching an order and then its shipment by ID. Total latency then tracks the slowest call instead of the sum of all calls.

Mark sections as required or optional. If a required call fails, return an error. If an optional one fails (recommendations, loyalty points), return the rest with that field set to null and flagged as unavailable. The client contract has to define this state explicitly.

Don't retry inside the fan-out by default. One client request already creates N downstream calls. If the client, BFF and services each retry, a struggling dependency receives multiplied traffic exactly when it can least absorb it. Cap concurrency per dependency and use circuit breakers so a failing service is skipped quickly. Otherwise the BFF amplifies the outage instead of containing it.

The example below implements this as ordinary functions and data structures. That is the main argument for putting it in a BFF. Deadline propagation, the required/optional split and the merge rules are code a reviewer can read and a unit test can exercise with stubbed slow or failing clients. The same logic in gateway configuration or embedded scripts is difficult to test outside a running gateway.

// Injected so unit tests can pass stubs that hang, throw or respond late.
type Fetcher = (path: string, signal: AbortSignal) => Promise<unknown>;

type Section<T> = { data: T | null; available: boolean };

const optional = <T>(r: PromiseSettledResult<T>): Section<T> =>
  r.status === "fulfilled"
    ? { data: r.value, available: true }
    : { data: null, available: false };

export async function orderScreen(get: Fetcher, orderId: string, budgetMs = 800) {
  const deadline = Date.now() + budgetMs;

  // Each call gets only the time left in the request budget. No call has its own fixed timeout.
  const call = (path: string) => {
    const remaining = deadline - Date.now();
    if (remaining <= 0) return Promise.reject(new Error("deadline exceeded"));
    return get(path, AbortSignal.timeout(remaining));
  };

  // Independent calls start together, so latency tracks the slowest call, not the sum.
  const [order, recs, loyalty] = await Promise.allSettled([
    call(`/orders/${orderId}`),
    call(`/recommendations?order=${orderId}`),
    call(`/loyalty/points`),
  ]);

  // Required section: fail fast. No retry here; the client owns the retry decision.
  if (order.status === "rejected") throw order.reason;

  // Sequential only because the shipment lookup needs a value from the order.
  const { shipmentId } = order.value as { shipmentId: string };
  const [shipment] = await Promise.allSettled([call(`/shipments/${shipmentId}`)]);

  // Optional sections degrade to null plus an explicit flag the client contract defines.
  return {
    order: order.value,
    shipment: optional(shipment),
    recommendations: optional(recs),
    loyalty: optional(loyalty),
  };
}

A deadline-bounded BFF handler fans out independent calls in parallel and makes a dependent call sequentially. It fails on the required section and marks optional sections unavailable. It does not retry. Per-dependency concurrency limits and circuit breakers would wrap the injected fetcher.

What does a BFF cost in latency, operations and development effort?

Illustrative estimate (assumed numbers, not a benchmark)

Assume a screen needs data from three domain services. The assumed inputs are an 80 ms client round trip over a mobile network, a 5 ms intra-cluster hop, and service processing time left out because it is the same in both designs.

  • Sequential client calls: N × RTT_client
  • BFF with parallel fan-out: RTT_client + RTT_gateway→BFF + max(RTT_BFF→service)
Scenario Assumed inputs Computed total
Client calls 3 services in sequence N = 3, RTT_client = 80 ms 240 ms
BFF in-cluster, parallel fan-out 80 + 5 + 5 ms 90 ms
BFF in another region, fan-out crosses regions 80 + 5 + 40 ms (assumed cross-region hop) 125 ms

The saving comes from paying the expensive mobile round trip once. The BFF hop still costs something. It adds serialization, a connection, and another queue under load. If the BFF runs far from the domain services, each fan-out call pays the long-distance latency, and much of the gain disappears. Deploy the BFF next to the services it calls.

Operational and development cost

Each BFF is another deployable service. It needs its own pipeline, dashboards, alerts, on-call ownership, credentials to downstream services, and dependency patching. A web BFF and a mobile BFF double that work.

Two BFFs also tend to duplicate logic such as price formatting, entitlement checks, and merge rules. Moving that code into a shared library recouples the BFFs, because a library change forces coordinated releases. Keeping the duplicates avoids the coupling but lets behavior drift, so web and mobile can show the same user different answers. Choose one approach on purpose for each piece of logic and record the choice.

When should you avoid a BFF, and how should you scope one?

A BFF is unjustified when you have one client type with simple data needs. If a single web app calls three services and the gateway can route and do light composition, a dedicated BFF only adds a network hop, a deployment pipeline and another on-call rotation. The same holds if clients can call a well-designed service API directly. Skip it also when client teams cannot run backend services. A BFF owned by a frontend team that has no capacity for monitoring, scaling or incident response will end up unowned.

Scope by client experience

Create one BFF per distinct client experience, such as web, mobile or a third-party API. Each of these has different payload sizes, auth models and release cadences. Do not create one per screen. Do not create one per team by default either, because organizational boundaries change more often than client types do.

Logic creep in both directions

Gateways drift toward business rules through scripting plugins. Each one is small, but together they form a monolith with no unit tests and no clear owner. BFFs drift the other way: they absorb domain logic because changing the BFF is faster than negotiating with the owning service.

Warning signs that a BFF has overreached:

  • It writes to domain data stores instead of calling the owning service.
  • It enforces business invariants, such as credit limits or inventory rules.
  • Several BFFs reimplement the same rule, and their versions disagree.
  • Domain teams must review BFF changes to keep them correct.

How do you migrate aggregation out of an existing API gateway?

Treat the migration as a refactor with a fixed external contract. Clients should not notice it happened.

  1. Inventory routes. List every gateway route and tag each as pass-through (auth, rate limiting, routing only) or composed (scripts that fan out, merge, or reshape payloads). Of the composed routes, mark the ones serving a single client. Those are your BFF candidates. Composed routes shared by several clients may belong in a domain service instead.
  2. Stand up the BFF behind the gateway. The gateway keeps TLS, authentication, and rate limiting. The BFF receives already-authenticated requests, so you avoid duplicating security logic during the transition.
  3. Pin the current response shape with contract tests. Record what the client actually reads, not the full payload. For example, a test for GET /mobile/home might assert that user.displayName is a non-empty string, orders is an array of at most five items each carrying id, status, and total, and that recommendations is an empty array rather than null when that upstream times out. Run the same suite against the gateway and the BFF. When both pass, you have parity on the behavior that matters, including the degraded paths that ad hoc gateway scripts often handle inconsistently.
  4. Shift traffic route by route. Switch one route at a time, starting with a small share of requests if your gateway supports weighted routing. Compare error rates and latency, then cut over fully. Keep the old script until you have seen a full release cycle without problems, so rollback is a config change.
  5. Strip the gateway. Delete the migrated scripts. If you leave them in place, someone will patch the wrong copy.
# Contract test for GET /mobile/home, run unchanged against the gateway and the BFF.
# Usage: GATEWAY_URL=... BFF_URL=... TEST_USER_TOKEN=... pytest test_mobile_home_contract.py
import os

import pytest
import requests

TARGETS = {
    "gateway": os.environ.get("GATEWAY_URL", ""),
    "bff": os.environ.get("BFF_URL", ""),
}
TOKEN = os.environ.get("TEST_USER_TOKEN", "placeholder-test-token")


@pytest.fixture(params=sorted(TARGETS))
def home(request):
    # Parametrizing on target means a parity gap shows up as one failing test ID.
    resp = requests.get(
        f"{TARGETS[request.param]}/mobile/home",
        headers={"Authorization": f"Bearer {TOKEN}"},
        timeout=5,
    )
    assert resp.status_code == 200
    return resp.json()


def test_display_name(home):
    # Pin only fields the app reads. Other fields can change without breaking the contract.
    name = home["user"]["displayName"]
    assert isinstance(name, str) and name.strip()


def test_orders_shape(home):
    orders = home["orders"]
    assert isinstance(orders, list) and len(orders) <= 5
    for order in orders:
        assert {"id", "status", "total"} <= order.keys()


def test_recommendations_never_null(home):
    # Degraded path: rerun with the recommendations stub forced to time out.
    # The client expects [] in that case, never null.
    assert isinstance(home["recommendations"], list)

A pytest contract suite that pins the fields the mobile client reads from GET /mobile/home and runs the same assertions against both the gateway and the new BFF, so parity can be checked before cutover.

What are the alternatives to the BFF pattern for aggregation?

A BFF is one way to place aggregation. Three other mechanisms are common, and each changes how you compose responses without changing who should own the composition.

GraphQL as an aggregation layer. A schema with resolvers that call domain services can serve as a single shared graph or be deployed per client as a BFF. A shared graph moves ownership to whoever curates the schema. That team becomes the coordination point for every client's changes. A per-client graph keeps BFF ownership and adds field selection, so clients stop over-fetching.

Declarative composition in the gateway. Some gateways can merge responses from several upstreams through configuration. This works for client-agnostic cases with no conditional logic, such as a fixed join of two resources. Once you need per-client shaping or fallbacks, you are writing code in config again.

Clients call domain APIs directly. This means no aggregation tier. It is acceptable for server-to-server consumers on low-latency networks. It is costly for mobile clients, because the client pays the fan-out over high-latency links and every client reimplements the same joins.

Option Who owns the logic Change cadence fit Failure handling expressiveness Operational overhead
Shared GraphQL graph Schema/platform team Shared, coordinated Per-field nulls and errors High: one critical service
Per-client GraphQL BFF Client team Matches client releases Per-field nulls and errors Medium per client
Gateway composition Gateway/platform team Gateway release cycle Limited to configured defaults Low
Direct client calls Each client Independent Fully client-side None server-side; high client cost

The mechanism you choose does not settle the underlying decisions. You still have to decide who owns the logic, which deployments become coupled, how partial failures are surfaced, and where fan-out cost lands.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to api gateway vs backend for frontend, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.