What is the backend for frontend pattern, and how is it different from an API gateway?

An API gateway and a backend for frontend (BFF) solve different problems, so the useful question is where each one sits in the request path. The gateway is shared infrastructure at the edge. It terminates TLS, routes requests, enforces rate limits and performs coarse authentication, such as rejecting requests without a valid token. It knows nothing about screens. The BFF is owned by one client team and exists to serve one client type. It aggregates calls to several services, shapes responses to match what a view needs, and translates protocols, for example by turning internal gRPC into JSON for a browser.

The two are layered:

Clients (web, iOS, Android) → API gateway → web BFF / mobile BFF → domain services (orders, catalog, accounts)

The gateway applies the same policy to everyone. That is why it should stay generic: if client-specific logic leaks into it, the gateway becomes a shared bottleneck that every team has to change. A BFF can change at the pace of its own frontend because no other client depends on it. Domain services stay authoritative for business rules, so neither layer above them has to re-implement those rules.

Concern Gateway BFF Domain service
TLS termination ✓
Routing and rate limiting ✓
Token presence and validity ✓
Session handling for the client ✓
Aggregating calls for a single view ✓
Response shaping and field trimming ✓
Protocol translation ✓
Fine-grained authorization ✓
Business rules and invariants ✓
+-------------+   +-------------+   +-------------+
|   Web app   |   |   iOS app   |   | Android app |
+-------------+   +-------------+   +-------------+
       |                 |                 |
       +-----------------+-----------------+
                         | HTTPS
                         v
+-------------------------------------------------+
| API gateway (shared edge, client-agnostic)      |
| TLS termination, routing, rate limiting,        |
| token presence and validity                     |
+-------------------------------------------------+
           | /web/*                     | /mobile/*
           v                          v
+----------------------+   +----------------------+
| Web BFF              |   | Mobile BFF           |
| (web team)           |   | (mobile team)        |
| session, aggregation |   | session, aggregation |
| shaping, gRPC->JSON  |   | shaping, gRPC->JSON  |
+----------------------+   +----------------------+
           |                          |
           +-------------+------------+
                         | gRPC
       +-----------------+-----------------+
       v                 v                 v
+-------------+   +-------------+   +-------------+
|   Orders    |   |   Catalog   |   |  Accounts   |
+-------------+   +-------------+   +-------------+
  domain services: business rules, fine-grained authz

Every client passes through one shared, client-agnostic gateway. The gateway routes each request to the BFF owned by that client's team, and the BFF aggregates and shapes calls to the domain services, which remain authoritative for business rules and fine-grained authorization.

When should you use a BFF, and when is a single API or GraphQL enough?

A BFF is justified when two conditions hold together. First, your clients genuinely diverge. A mobile app on a flaky network needs small payloads and one round trip per screen. A desktop web dashboard can afford rich responses. A partner integration needs a stable contract that changes rarely. Second, a frontend team can own the BFF end to end. If either condition fails, a BFF adds a hop without removing a problem.

A single general-purpose API is enough when clients render similar data and ship on similar schedules. Small differences in payload can be absorbed with sparse fieldsets or pagination parameters.

A single GraphQL layer suits clients that differ mainly in which fields they select. It does not remove complexity; it moves it. You now need query cost and depth limits so one client can't issue an expensive nested query. You need schema governance across teams. You also lose straightforward HTTP caching, because most queries arrive as POSTs to one endpoint.

Account for the operational cost of each BFF. Every one is another service to deploy, monitor, patch, secure and staff on-call. A frontend team that owns a BFF needs production skills: reading traces, handling timeouts and retries, and responding to incidents.

Option Fits when Main cost
General-purpose API Clients have similar data needs and release cadence Clients over-fetch or make multiple calls
Single GraphQL layer Clients differ mainly in field selection Query cost control, schema governance, caching
BFF per client type Payload, latency or release needs diverge sharply, and frontend teams can run services One more service each to operate and staff

Where should business logic live in a BFF architecture?

The duplication boundary follows one rule: a BFF may change how data looks, but never what it means. Business rules, validation, pricing and authorization decisions belong in the domain services that own that data. A BFF composes responses from several services, filters out fields a client doesn't need, renames fields to match the frontend's vocabulary, and formats values for display.

The code example below shows two handlers. The first calls the pricing service, takes the returned total, and formats it as a localized currency string for a mobile screen. The second fetches raw line items and a discount table, then calculates the total itself. Both handlers produce the same JSON shape. Only the first one is safe.

The second handler causes problems once you have more than one BFF. If the web BFF and the mobile BFF each compute order totals, they will drift apart. One rounds per line item and the other rounds at the end. One applies a new promotion rule this sprint and the other picks it up next quarter. Customers then see different prices on different devices, and no single service owns the error.

A subtler risk is that a BFF can mask a poorly designed downstream API. When a domain service returns awkward shapes or forces five calls to answer one question, it is tempting to patch over that in the BFF. Every workaround makes the downstream problem harder to see. The technical debt stays in place and spreads into every BFF that needs the same data. Fix those problems in the domain service instead.

// Good: the BFF shapes data. The pricing service owns the total.
app.get('/mobile/orders/:id/summary', async (req, res) => {
  const [order, quote] = await Promise.all([
    ordersClient.getOrder(req.params.id),
    pricingClient.getQuote(req.params.id), // authoritative total
  ]);
  res.json({
    orderNumber: order.id,                 // rename for the client
    itemCount: order.lineItems.length,     // compose, no business rule
    total: new Intl.NumberFormat(req.locale, {
      style: 'currency',
      currency: quote.currency,
    }).format(quote.totalMinorUnits / 100), // format for display only
  });
});

// Bad: the BFF re-derives pricing. Same JSON shape, different meaning.
app.get('/web/orders/:id/summary', async (req, res) => {
  const order = await ordersClient.getOrder(req.params.id);
  const discounts = await promotionsClient.getActiveDiscounts();
  // Business rule copied into the BFF: rounding and promo logic now
  // live here AND in the pricing service, and will drift apart.
  const total = order.lineItems.reduce((sum, item) => {
    const pct = discounts[item.sku] ?? 0;
    return sum + Math.round(item.unitPrice * item.qty * (1 - pct));
  }, 0);
  res.json({
    orderNumber: order.id,
    itemCount: order.lineItems.length,
    total: (total / 100).toFixed(2), // locale and currency ignored too
  });
});

Two Express-style BFF handlers that return the same shape: the first formats a total supplied by the pricing service, while the second computes pricing in the BFF and duplicates a business rule that will drift between BFFs.

How does frontend aggregation work inside a BFF?

A BFF earns its keep by turning several dependent client calls into one. Fire independent downstream requests concurrently, give each its own timeout, and treat the slowest call as the deciding factor for latency. When a non-critical call fails or times out, return the response with that field set to null and a flag such as degraded: ["recommendations"] so the client can hide the widget instead of failing the screen. Required data, such as the order itself, should still fail the request. Avoid sequential chains: if call B needs an ID from call A, check whether a downstream service can accept a batch or a joined query rather than chaining three hops.

Illustrative estimate. Assume a 150 ms mobile round trip, 5 ms between the BFF and services, and 40 ms of service time. Suppose a screen needs one call, then three parallel calls that depend on it.

  • Client-side fan-out: two mobile round trips of 150 + 40 ms each, about 380 ms.
  • BFF-side aggregation: one mobile round trip (150 ms) plus two internal stages (about 45 ms each), about 240 ms.

The extra hop adds only a few milliseconds.

Caching. Cache entity data downstream or in a shared cache, where every BFF benefits. Reserve the BFF response cache for composed, non-personalized views.

Retries and timeouts. Retries stack. If the gateway, the BFF and each service all retry three times, one user request can become 27 calls to a struggling dependency. Retry at one layer only, cap retries with a budget (for example, retries may not exceed 10% of requests), and propagate a deadline downstream. Each hop then gets the remaining time minus its own overhead, and a call that has already run out of time is not attempted.

const DEFAULT_BUDGET_MS = 800; // whole-request deadline if the caller sent none
const HOP_OVERHEAD_MS = 5;    // reserve time for our own processing

// One downstream call: its timeout is the smaller of its own cap and the remaining deadline.
async function getJson(url: string, deadline: number, capMs: number): Promise<any> {
  const remaining = deadline - Date.now() - HOP_OVERHEAD_MS;
  if (remaining <= 0) throw new Error(`deadline exceeded before calling ${url}`); // don't start doomed work
  const res = await fetch(url, {
    signal: AbortSignal.timeout(Math.min(capMs, remaining)),
    headers: { "x-request-deadline": String(deadline) }, // propagate the absolute deadline downstream
  });
  if (!res.ok) throw new Error(`${url} -> ${res.status}`);
  return res.json(); // no retries here: retries happen at one layer only
}

export async function orderScreen(orderId: string, incomingDeadline?: number) {
  const deadline = incomingDeadline ?? Date.now() + DEFAULT_BUDGET_MS;

  // Stage 1: required data. If this fails, the whole request fails.
  const order = await getJson(` deadline, 300);

  // Stage 2: independent calls fan out concurrently, each with its own timeout.
  const [customer, shipping, recs] = await Promise.allSettled([
    getJson(` deadline, 250),
    getJson(` deadline, 250),
    getJson(` deadline, 150),
  ]);

  if (customer.status === "rejected") throw customer.reason; // required field

  // Optional fields degrade to null and are named so the client can hide those widgets.
  const degraded: string[] = [];
  const optional = (r: PromiseSettledResult<any>, name: string) =>
    r.status === "fulfilled" ? r.value : (degraded.push(name), null);

  return {
    order,
    customer: customer.value,
    shipping: optional(shipping, "shipping"),
    recommendations: optional(recs, "recommendations"),
    degraded,
  };
}

A BFF handler that fetches the required order first, then fans out three dependent calls in parallel with per-call timeouts bounded by a propagated deadline, failing on required data and returning null plus a degraded list for optional fields.

How do you secure browser clients with a BFF?

The browser should never hold an access or refresh token. Anything JavaScript can read, an XSS payload can read and send off the page. In the session-holding model, the BFF acts as a confidential OAuth client. It runs the authorization code flow, receives the tokens, and stores them server-side against a session ID. The browser only gets that session ID in a cookie marked HttpOnly, Secure, and SameSite=Lax or Strict. Script can't read the cookie, it never travels over plain HTTP, and most cross-site requests won't carry it. For state-changing endpoints, still add CSRF protection, such as a custom request header or a synchronizer token, because SameSite depends on browser behavior and on how your domains are laid out.

When the BFF calls downstream services, it attaches a token from the session rather than a cookie. Avoid forwarding the user's broad token unchanged. Use OAuth 2.0 Token Exchange to swap it for a short-lived token scoped to the target service's audience. A leaked token is then useful against one service for a few minutes, not across your whole estate. The exchanged token still carries the user's subject and claims, so identity reaches every hop.

Each downstream service must validate that token's signature, issuer, audience, and expiry, and then make its own authorization decision. Checks in the BFF exist to shape the UI and reject obvious misuse early. They are not a security boundary. Other BFFs, batch jobs, and internal callers reach the same services without passing through this BFF, and a misconfigured route can skip its checks entirely.

How can you share code across BFFs without coupling them?

Duplicating a little code across BFFs is usually cheaper than sharing the wrong abstraction. Share only what changes slowly and should behave the same for every client.

Approach What it shares Coupling cost Use when
Generated thin clients Request/response types and transport calls, generated from each service's contract Low, if each BFF pins and regenerates on its own schedule Several BFFs call the same downstream services
Shared middleware Trace context, auth token propagation, timeouts Medium: a security fix can force every BFF to upgrade at once The concern is truly cross-cutting and has no client-specific behaviour
Composition service A reusable aggregation, run as its own service High: a new runtime dependency, owner and failure mode Two or more BFFs build the same view with the same rules

The main risk is lockstep upgrades. A generated client stays cheap until someone adds retry policy, caching or field mapping to it. At that point, changing the library forces every BFF to redeploy together, and you lose the independent releases that justified separate BFFs. Keep generated clients free of logic. Keep middleware small and backward compatible. Promote an aggregation to a composition service only when the duplication is real, not when you expect it.

Ownership follows the same split. The frontend team owns its BFF: the routes, the response shapes and the release cadence. The platform team supplies paved-road templates with tracing and auth middleware already wired in, default dashboards, and a deployment pipeline. A new BFF then starts from working infrastructure instead of rebuilding it. Engineering time goes into client-specific code, and the cross-cutting parts are maintained once rather than separately in every BFF.

What are the signs a BFF has drifted into a duplicated mini-monolith?

Shared infrastructure keeps the plumbing consistent, but it does not stop business rules from leaking into BFFs over time. That drift is gradual and easy to miss in individual code reviews, so it helps to check for it on purpose. Each sign below means a BFF has started owning something that belongs to a domain service.

Warning sign Why it's a problem Refactoring path
One feature requires the same logic change in several BFFs (pricing rules, eligibility checks, status mapping) The rule now has multiple owners. Copies diverge, and clients show different answers for the same data. Move the rule into the domain service that owns the data. BFFs call it and only shape the result for their client.
BFFs call each other (the mobile BFF calls the web BFF to reuse an aggregation) The web BFF's response shape becomes a contract for another backend. Web-driven changes then break mobile, and deployments become coupled. Extract the shared aggregation into a composition service with its own versioned API. Both BFFs call that service.
A BFF writes to a database, either its own tables holding domain state or another service's tables The BFF has become a system of record. Invariants are enforced in two places, and the domain service no longer sees every write. Hand data ownership back to the domain service. Replace direct writes with calls to its API. Keep only disposable caches or session data in the BFF.

Run this table as a checklist during design reviews for new BFF endpoints. Checking at that point is cheaper than untangling a BFF after other clients depend on what it does.

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 backend for frontend pattern, 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.
  • Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.

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.
  • Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
  • 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.