What is the backend for frontend pattern, and how is it different from an API gateway?
A backend for frontend (BFF) is a server-side component dedicated to one client experience: one for the web app, one for the mobile apps, one for partner integrations. The client team owns it, or works closely with the team that does. Its job is to aggregate calls to domain services, shape responses to what a specific screen needs, and translate protocols, for example turning several internal gRPC calls into one JSON payload. The reason to give each client its own backend is that clients diverge. Mobile wants small payloads and few round trips over unreliable networks. Web can afford chattier calls. Partners need stable, versioned contracts. A single shared API ends up serving all three poorly.
An API gateway solves a different problem. It handles concerns that are the same for every client:
| Concern | API gateway | BFF |
|---|---|---|
| Routing and TLS termination | Yes | No |
| Coarse authentication (token validation) | Yes | Consumes the result |
| Rate limiting, quotas | Yes | No |
| Response composition per screen | No | Yes |
| Protocol translation for one client | No | Yes |
| Release cadence | Platform team | Client team |
The usual layout puts the gateway at the edge. It forwards each request to the matching BFF, and the BFF fans out to domain services such as orders, catalog, and accounts.
Merging these roles fails in two ways. If you put client-specific composition in the gateway, it fills up with per-screen logic, and every frontend change needs a platform-team deploy. If you push edge concerns into each BFF, every client team reimplements auth checks and rate limiting differently, so security and throttling behave inconsistently across clients.
+---------------+ +---------------+ +---------------+
| Web app | | Mobile apps | | Partner apps |
+-------+-------+ +-------+-------+ +-------+-------+
| | |
+--------------------+--------------------+
|
v
+---------------------------------------------------------+
| API gateway (platform team, client-agnostic) |
| routing | TLS termination | token validation |
| rate limiting | quotas |
+-------+--------------------+--------------------+-------+
| | |
v v v
+---------------+ +---------------+ +---------------+
| Web BFF | | Mobile BFF | | Partner BFF |
| (web team) | | (mobile team) | |(partner team) |
| compose views | | small payload | | versioned API |
+-------+-------+ +-------+-------+ +-------+-------+
| | |
+--------------------+--------------------+ fan-out: any BFF
| | | may call any
v v v domain service
+---------------+ +---------------+ +---------------+
| Orders svc | | Catalog svc | | Accounts svc |
+---------------+ +---------------+ +---------------+
The API gateway handles client-agnostic edge concerns once for all traffic, then routes each request to a per-client BFF that composes and shapes responses by fanning out to shared domain services.
How does API aggregation in a BFF work, and what does it do to latency?
A BFF aggregates by fanning out. Calls that don't depend on each other go out concurrently. Calls that need an earlier result, such as recommendations keyed on a user's segment from the profile service, wait for that result. When everything returns, the BFF shapes the response: it drops internal fields, renames keys, flattens nesting and formats values so the client receives exactly the payload one screen needs.
Illustrative estimate. Assumed inputs: mobile RTT 150 ms, intra-datacenter hop 2 ms, BFF processing 5 ms. Assumed service latencies: profile 40 ms, orders 60 ms, recommendations 120 ms (depends on profile).
| Approach | Critical path | Total |
|---|---|---|
| Client, sequential | (150+40) + (150+60) + (150+120) | 670 ms |
| Client, parallel | (150+40) → (150+120), orders overlapped | 460 ms |
| BFF fan-out | 150 + (2+40) + (2+120) + 5, orders overlapped | 319 ms |
The BFF wins because the client pays the expensive mobile RTT once instead of once per dependency chain step. On a 5 ms broadband RTT the gap shrinks to a few milliseconds, and the extra hop can make the BFF approach roughly break-even.
The BFF never responds faster than its slowest required dependency. If recommendations has a 900 ms p99, the screen has at least a 900 ms p99. With fan-out, a request is slow whenever any one of its dependencies is slow. Fan-out to more services raises the chance of that happening, so the aggregate tail is worse than any single service's tail.
// BFF handler for one mobile screen: parallel + dependent fan-out, then response shaping.
const SVC = ""; // placeholder intra-datacenter base URL
async function getJson<T>(path: string): Promise<T> {
const res = await fetch(`${SVC}${path}`, { signal: AbortSignal.timeout(300) }); // bound each dependency
if (!res.ok) throw new Error(`${path} -> ${res.status}`);
return res.json() as Promise<T>;
}
type Profile = { id: string; display_name: string; segment: string; internal_flags: string[] };
type Order = { order_id: string; total_cents: number; created_at: string; warehouse_id: string };
type Rec = { sku: string; title: string; score: number };
export async function homeScreen(userId: string) {
// Dependent chain: recommendations need the segment from profile, so they wait for it.
const profileThenRecs = getJson<Profile>(`/profile/${userId}`).then(async (profile) => {
const recs = await getJson<Rec[]>(`/recs?segment=${encodeURIComponent(profile.segment)}`);
return { profile, recs };
});
// Independent call: orders starts immediately and overlaps the chain above.
const orders = getJson<Order[]>(`/orders?user=${userId}&limit=3`);
// Latency = max(profile + recs, orders): the slowest path sets the response time.
const [{ profile, recs }, recentOrders] = await Promise.all([profileThenRecs, orders]);
// Shaping: drop internal fields, rename keys, format values for this screen only.
return {
name: profile.display_name,
recentOrders: recentOrders.map((o) => ({
id: o.order_id,
total: (o.total_cents / 100).toFixed(2),
date: o.created_at.slice(0, 10),
})),
picks: recs.slice(0, 5).map((r) => ({ sku: r.sku, title: r.title })),
};
}
A TypeScript BFF handler that runs the independent orders call alongside the profile→recommendations chain, waits for both with Promise.all, and returns a payload with internal fields removed and values formatted for one screen.
How do you keep one slow service from taking down a BFF?
Start with a total deadline for the whole request, then derive each dependency's timeout from it. Do not give every downstream call its own fixed timeout. If the client gives up at 1 s, the BFF might reserve 100 ms for its own work and serialization. Calls that run in parallel can each use the remaining 900 ms. Sequential calls must split that 900 ms. Each call then gets whatever budget is left when it starts, which keeps a late dependency from using time the client will never wait for. If the client sends its own deadline, propagate it downstream so other services also stop work nobody is waiting for.
When a non-critical call times out, return a partial response instead of an error. Set that section to null and add an explicit marker, such as a degraded list naming the missing sections. The client can then render a placeholder rather than guess whether an empty array means "no data" or "failed." Decide per screen which sections are essential. If the order summary fails, the request should fail. If recommendations fail, the page should still render.
Circuit breakers and bulkheads are worth adding once a dependency's failures start affecting healthy calls. A hung service can tie up a shared connection pool or worker threads, so separate pools or concurrency limits for each dependency contain the damage. A breaker stops sending traffic to that dependency until it recovers.
Caching in the BFF cuts latency, but it has costs. Invalidation becomes your problem. Your client may also see data that differs from what the web app or another BFF shows for the same entity.
type OrderSummary = { id: string; status: string; totalCents: number };
type Recommendation = { sku: string; title: string };
const TOTAL_BUDGET_MS = 1000; // client gives up at 1 s
const RESERVED_MS = 100; // BFF's own work and serialization
type OrderPage = {
order: OrderSummary;
recommendations: Recommendation[] | null; // null means failed, [] means none
degraded: string[]; // sections to render as placeholders
};
async function fetchJson<T>(url: string, deadline: number): Promise<T> {
// Each call gets whatever budget is left when it starts, never a fixed timeout.
const remaining = deadline - Date.now();
if (remaining <= 0) throw new Error(`no budget left for ${url}`);
const res = await fetch(url, { signal: AbortSignal.timeout(remaining) });
if (!res.ok) throw new Error(`${url} returned ${res.status}`);
return (await res.json()) as T;
}
export async function getOrderPage(orderId: string): Promise<OrderPage> {
const deadline = Date.now() + TOTAL_BUDGET_MS - RESERVED_MS;
// Parallel calls share the same deadline instead of splitting it.
const [order, recs] = await Promise.allSettled([
fetchJson<OrderSummary>(` deadline),
fetchJson<Recommendation[]>(` deadline),
]);
// Essential section: if it fails, the whole request fails.
if (order.status === "rejected") throw order.reason;
// Non-critical section: degrade to null plus an explicit marker.
const degraded: string[] = [];
const recommendations = recs.status === "fulfilled" ? recs.value : null;
if (recommendations === null) degraded.push("recommendations");
return { order: order.value, recommendations, degraded };
}
A BFF handler takes per-call timeouts from one request deadline, fails if the essential order summary fails, and returns null recommendations with a degraded marker when that call times out or errors.
Should a BFF use GraphQL or REST?
A REST BFF exposes purpose-built endpoints, one per screen or use case, such as GET /home-feed or GET /order-summary/{id}. The server decides exactly what each call fetches, so its cost is known and fixed. Responses map cleanly to URLs, so HTTP caches and CDNs work without extra effort. The price is churn: every new screen or field means a BFF change and a deploy.
A GraphQL BFF instead publishes one schema shaped around the client's domain. Resolvers call downstream services to fill each field. Clients compose their own queries, so frontend teams iterate without waiting on backend releases. That flexibility moves risk to the server:
- Expensive queries. A client can nest relations several levels deep.
- Fan-out amplification. A naive resolver for a list of 50 orders, each with a customer field, issues 50 separate customer lookups (the N+1 problem).
- Weaker caching. Queries usually arrive as POST requests to a single endpoint, so URL-keyed HTTP caching mostly stops working.
The required controls are:
- Per-request batching and deduplication loaders, which collapse those 50 lookups into one bulk call.
- Query depth and cost limits, enforced before execution starts.
- Persisted or allow-listed queries, which restrict production clients to known operations.
| Dimension | REST BFF | GraphQL BFF |
|---|---|---|
| Flexibility | Low; new needs require new endpoints | High; clients select fields |
| Caching | Standard HTTP/CDN caching by URL | Needs persisted queries or app-level caching |
| Operational risk | Predictable per-endpoint cost | Requires cost/depth limits and batching |
| Contract evolution | Versioned or added endpoints | Additive fields, deprecation of old ones |
import DataLoader from 'dataloader';
type Customer = { id: string; name: string };
type Order = { id: string; customerId: string };
// Downstream client exposing a bulk lookup (one HTTP call for many ids).
interface CustomerService {
getMany(ids: readonly string[]): Promise<Customer[]>;
}
// Built once per incoming GraphQL request, so the cache never leaks
// data between users and dedupes only within this request.
export function createLoaders(customers: CustomerService) {
return {
customer: new DataLoader<string, Customer>(async (ids) => {
// DataLoader gathers every .load() made in the same tick and
// deduplicates repeated ids before calling this batch function.
const rows = await customers.getMany(ids);
const byId = new Map(rows.map((c) => [c.id, c]));
// The result must match the keys' length and order. Missing ids
// become Errors so only the affected field fails.
return ids.map((id) => byId.get(id) ?? new Error(`customer ${id} not found`));
}),
};
}
type Ctx = { loaders: ReturnType<typeof createLoaders> };
export const resolvers = {
Order: {
// Called once per order. 50 orders produce 50 .load() calls
// but only one getMany() request to the customer service.
customer: (order: Order, _args: unknown, ctx: Ctx) =>
ctx.loaders.customer.load(order.customerId),
},
};
A per-request DataLoader in a GraphQL BFF batches and deduplicates the Order.customer lookups, so a list of 50 orders triggers one bulk call to the customer service instead of 50 separate calls.
What logic belongs in a BFF, and what should stay out?
A BFF should own decisions about presentation and nothing about the business. Formatting, response composition, client-specific auth context (exchanging a session cookie for a downstream token, for example), protocol translation, and feature-flag-driven shaping all belong there. Each of these is specific to one client, and getting one wrong breaks a screen, not an invariant.
Domain rules, writes that coordinate several services, and data ownership do not belong there. Every client that needs a rule gets its own BFF copy of it. The mobile BFF calculates a discount one way, the web BFF gets a fix a sprint later, and customers see different prices depending on the device.
Orchestration tends to creep in gradually. A BFF that starts by calling three services ends up calling twelve, sequencing writes and compensating for failures. At that point it is a god service: every downstream release has to be checked against it, and teams can no longer deploy independently, which is the defining property of a distributed monolith.
The fix is to move that logic back to the service that owns the data. A checkout that reserves stock and charges a card should be a single command on an order service that manages its own saga, not a series of calls made from the BFF.
| Review question | Belongs in BFF | Push to domain service |
|---|---|---|
| Does it only reshape or rename fields? | Yes | — |
| Would another client need the same rule? | — | Yes |
| Does it write to more than one service? | — | Yes |
| Is it gated by a UI feature flag? | Yes | — |
| Does it persist state the BFF owns? | — | Yes |
Who should own and operate a BFF, and what does it cost?
A BFF saves engineering time only when the team that ships the client also deploys and operates it. The saving comes from removing a queue: a mobile team that needs a new field or a merged response changes its own BFF in the same sprint, without filing a request with the owners of the shared gateway or backend. If a separate backend team owns the BFF, the queue returns and you still carry the extra network hop.
The cost scales with client types
Each BFF is a full service. It needs code, a service identity and secrets, dependency patching, dashboards, and an on-call rotation. Adding a client type adds all of that again.
Illustrative estimate (assumed numbers, not a benchmark): monthly upkeep ≈ number of BFFs × maintenance hours per BFF. With 3 BFFs (web, iOS, Android) at an assumed 20 hours each for patching, upgrades, and incident follow-up, that is 3 × 20 = 60 engineer-hours per month before any feature work.
Required practices
- On-call: page the owning client team, because it is the only team that understands the aggregation logic.
- Distributed tracing: propagate trace context on every downstream call. Without it, you cannot tell which leg of the fan-out made a response slow.
- Contract tests: run consumer-driven tests against downstream APIs so that a breaking backend change fails in CI and not in production.
Limiting fragmentation
A platform team keeps BFFs from each inventing their own auth checks, log formats, and error shapes. It does this by publishing a service template or shared library that includes token validation, structured logging, trace propagation, default timeouts, and a standard error envelope. Client teams own the aggregation logic, and the platform team owns this shared plumbing.
When should you avoid a BFF, and what are the alternatives?
A BFF earns its operating cost only when clients genuinely diverge. If you ship a single client type, the "frontend" and the "backend for it" are the same audience, so a separate service only adds a network hop and a deploy pipeline. If your clients are thin and the existing domain APIs already return roughly what each screen needs, aggregation buys little. And if no team has capacity to own on-call, upgrades and capacity planning for another service, an unowned BFF becomes the slowest-moving dependency in every release.
Alternatives and where they fit
| Situation | Recommended approach | Why |
|---|---|---|
| One client, APIs map cleanly to screens | Call domain APIs directly | No divergence to absorb, so no extra hop |
| Several clients need the same composed view | Client-agnostic aggregation endpoint on the owning domain service | The composition belongs to the domain, not to a client |
| Only auth, routing or header shaping differs | Light composition at the gateway | Cross-cutting concerns, no business logic |
| Many clients with varied field needs, strong schema governance | Single shared GraphQL layer | Clients select fields instead of each needing its own backend |
| Clients differ in payloads, flows and release cadence | Per-client BFF | Divergence is real and owned by client teams |
Signs to merge or retire
- Near-identical BFFs across clients. If the code diffs are trivial, the clients have converged. Merge them or move the shared view into the domain service.
- BFFs that only proxy. A pass-through adds latency and failure modes and returns nothing for them. Route the traffic through the gateway instead.
- BFFs accumulating domain logic. Pricing rules or validation living in a BFF will drift between clients. Push that logic back to the owning service before you build anything else on top of it.
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.