Skip to main content
KBY Technologies Logo

Backend-for-Frontend Patterns for API Fan-Out

How client-specific BFF layers, aggregation logic and edge deployment stop API fan-out from strangling mobile and web latency budgets.

KBY Technologies11 min read
Backend-for-Frontend Patterns for API Fan-Out

Underlined words are defined in the KBY Lexicon. Tap or click one to see what it means.

A mobile client hitting eleven downstream microservices to render a single product page is not a hypothetical. It is the default outcome of exposing fine-grained microservice directly to heterogeneous clients. Each additional round trip adds tail latency that compounds under cellular jitter, and the client ends up owning aggregation logic it has no business owning.

The Backend for Frontend pattern exists specifically to pull that aggregation, protocol translation and client-shaping logic off the device and off the shared API gateway, and into a purpose-built service tier that sits between the client and the domain services.

This is not the same problem an API gateway solves. A gateway handles cross-cutting concerns (rate limiting, termination, auth) uniformly across all consumers. The Backend for Frontend pattern handles client-specific response shaping, and conflating the two responsibilities is where most teams go wrong.

#What four direct calls cost a checkout screen

Consider a checkout screen that needs cart contents, inventory availability, shipping estimates and loyalty points.

If the mobile app calls four separate services directly, you get four TLS handshakes (or four multiplexed /2 streams at best), four sets of retry/backoff logic duplicated client-side, and four independent points of partial failure that the client has to reconcile into one coherent UI state.

On a 4G connection with 80–150ms RTT, four sequential or semi-parallel calls routinely push time-to-interactive past 1.2 seconds before rendering even starts.

Worse, every domain service now has to satisfy the lowest-common-denominator contract needed by every client type: web, iOS, Android and, increasingly, third-party partner integrations. Domain teams end up bloating their APIs with optional fields that only one client consumes, which erodes API cohesion over time.

#One BFF for each client experience

The core principle is one BFF instance per client experience, owned by the team that owns that client. A web BFF and a mobile BFF are separate deployable units with separate release cadences, even though they may call the same set of downstream services. This is the detail most implementations get wrong: sharing one “universal” BFF across web and mobile just reinvents the generic-gateway problem with extra network hops.

Three structural variants dominate in production:

Backend for Frontend pattern
  • A REST aggregation BFF is a thin Node.js or Go service that fans out to domain services with Promise.all / goroutines, merges results, and returns a client-tailored payload.
  • A GraphQL BFF uses a schema per client experience, often federated via Apollo Federation or Mercurius, letting the client request exactly the fields it needs and letting the BFF resolve fields lazily against underlying services.
  • An edge BFF pushes the aggregation logic to CDN edge compute (Cloudflare Workers, Lambda@Edge) to shave the extra hop between client and origin, at the cost of constrained execution time and cold-start variance.

The flowchart below shows the topology difference between a naive direct-call model and a BFF-mediated one.

Loading diagram...

Each BFF resolves only the fields its client actually renders, and failures in non-critical branches (loyalty points, for instance) degrade gracefully rather than failing the entire response.

#
Where the Backend for Frontend Pattern Sits Relative to the Gateway

In a layered topology, the API gateway remains the single ingress point for TLS, WAF rules and coarse-grained rate limiting. The BFF sits behind it as an internal service, invisible to the public internet, reachable only via the gateway’s routing rules. This keeps the security boundary consistent while letting the BFF focus purely on composition logic.

Teams building out architectural patterns for multi-client platforms consistently find this two-tier split easier to reason about than a monolithic gateway trying to do both jobs.

#Building one, starting from the screen

The build-out follows the same sequence whichever variant you choose:

  • Enumerate client-specific view models first, not API endpoints. Start from the screen, not the database.
  • Map each view model field to its owning domain service, and identify which fields are optional-degradable versus mandatory-blocking.
  • Implement fan-out with bounded concurrency and per-call timeouts, never a single shared timeout for the whole aggregation.
  • Cache at the granularity of individual upstream service responses and compose fresh at the BFF, rather than caching the final merged payload, to avoid cache-key explosion.
  • Instrument each downstream call independently so a slow loyalty service doesn’t get blamed on the BFF as a whole.

#
A mobile checkout route in Express

1// mobile-bff/routes/checkout.js
2const express = require('express');
3const router = express.Router();
4
5async function withTimeout(promise, ms, fallback) {
6 let timer;
7 try {
8 return await Promise.race([
9 promise,
10 new Promise((_, reject) => {
11 timer = setTimeout(() => reject(new Error('timeout')), ms);
12 })
13 ]);
14 } catch (err) {
15 return fallback;
16 } finally {
17 clearTimeout(timer);
18 }
19}
20
21router.get('/checkout/:cartId', async (req, res) => {
22 const { cartId } = req.params;
23
24 const [cart, inventory, loyalty] = await Promise.all([
25 withTimeout(cartService.get(cartId), 400, null),
26 withTimeout(inventoryService.checkAvailability(cartId), 300, { available: null, degraded: true }),
27 withTimeout(loyaltyService.getPoints(req.user.id), 250, { points: 0 })
28 ]);
29
30 if (!cart) {
31 return res.status(502).json({ error: 'cart_unavailable' });
32 }
33
34 res.json({
35 cartId,
36 items: cart.items,
37 inventoryStatus: inventory,
38 loyaltyPoints: loyalty.points,
39 renderedAt: Date.now()
40 });
41});
42
43module.exports = router;

Note the asymmetric timeouts and fallback defaults. Cart data is mandatory and blocking, loyalty degrades to a safe default, while inventory degrades to an explicit unknown state (available: null) that the client must not treat as in stock, for example by blocking or re-verifying at order placement. This is the single most important discipline in any Backend for Frontend pattern implementation: classify every upstream call as blocking or degradable before writing the aggregation code.

#
GraphQL Federation Configuration

Rover composes the supergraph from a supergraph.yaml:

1federation_version: =2.5.0
2subgraphs:
3  cart:
4    routing_url: http://cart-service.internal:4001/graphql
5    schema:
6      file: ./cart.graphql
7  inventory:
8    routing_url: http://inventory-service.internal:4002/graphql
9    schema:
10      file: ./inventory.graphql
11  loyalty:
12    routing_url: http://loyalty-service.internal:4003/graphql
13    schema:
14      file: ./loyalty.graphql

Runtime settings belong in a separate Apollo Router router.yaml:

1supergraph:
2  introspection: false
3cors:
4  policies:
5    - origins:
6        - https://app.example.com

The supergraph composition step happens at build time via the Apollo Rover CLI, which validates that field ownership doesn’t collide across subgraphs before the schema is published. See the Apollo Federation documentation for the composition rules governing entity resolution and @key directives.

Backend-for-Frontend Patterns for API Fan-Out architecture diagram 2

#Choosing between the variants

VariantLatency ProfileTeam Ownership ClarityDuplication RiskBest Fit
REST Aggregation BFFLow: direct fan-out, minimal parsing overheadHigh: one team, one deployableModerate: logic duplicated across client BFFsSmall to mid-size client fleets
GraphQL FederationModerate: query planning adds ~5-15msModerate: shared schema governance requiredLow: single source of field resolutionLarge orgs with many client teams
Edge BFFLowest for cache hits, variable on cold startLow: deployment tied to CDN vendor toolingHigh: logic often duplicated from origin BFFRead-heavy, cache-friendly views
Generic API Gateway transformsLow but inflexiblePoor: shared config owned by platform teamHigh: transform rules sprawl per clientLegacy migration bridge only

#How BFF deployments go wrong

The most common failure in a mature Backend for Frontend pattern deployment is the “distributed monolith” anti-pattern: BFFs that started thin but accumulated business logic that should live in the domain services. When three different BFFs independently reimplement discount calculation, a pricing bug fix requires three coordinated deployments instead of one. The fix is a strict architectural rule: BFFs orchestrate and shape, they never own business rules.

Cascading failure is the second major risk. If every BFF calls a shared inventory service and that service degrades, all client experiences degrade simultaneously, defeating the isolation the pattern was meant to provide. Circuit breakers per downstream dependency (via something like Hystrix-style bulkheading or its modern equivalents such as resilience4j) are non-negotiable, not optional hardening.

Cache-key explosion is a subtler edge case in aggregation-heavy BFFs. Caching the composed response by user ID plus fifteen query parameters produces a cache hit rate near zero under real traffic. Cache at the granularity of the upstream service response where possible, and compose fresh at the BFF layer, rather than caching the final merged payload.

Schema drift between the BFF’s view model and the underlying domain model is the third recurring issue. When a domain service renames or restructures a field, every BFF consuming it breaks without warning unless contract tests are running in CI against a Pact broker or an OpenAPI diff gate.

#What the pattern costs in scaling and security

  • Deployment cadence vs consistency: independent BFF deploy cycles let mobile ship faster than web, but this means the same backend bug can exist unpatched in one client’s BFF long after another team fixes it.
  • Attack surface: each BFF is an additional internal service with its own auth token handling; a compromised BFF has direct network access to every domain service it aggregates, so per-BFF service accounts with scoped permissions are required rather than a shared internal API key.
  • Horizontal scaling cost: BFFs are typically I/O-bound and scale cheaply on CPU, but connection pool exhaustion against downstream services becomes the real ceiling; size connection pools per BFF instance against each downstream’s actual concurrency budget, not against the BFF’s own request rate.
  • Observability overhead: distributed tracing becomes mandatory once you have more than two BFFs, since a slow checkout screen could originate in any of five services; propagate a single trace context header through every fan-out call.
  • Team coupling: the pattern only pays off when the client team also owns the BFF; if a central platform team owns all BFFs on behalf of client teams, you have rebuilt the shared-gateway bottleneck under a different name.

None of this justifies applying the Backend for Frontend pattern indiscriminately. A platform with two client types and four domain services rarely needs it; a well-designed API gateway with response shaping middleware covers that case with far less operational surface. The pattern earns its complexity budget once you have divergent client requirements, independent release trains, and enough domain services that direct client-to-service calls have become the actual bottleneck rather than a theoretical one.

Evidence trail

Sources and verification

Primary documentation and external technical references used in this article.

  1. 01Apollo Federation documentationapollographql.com
  2. 02Hystrix-style bulkheadinggithub.com

About this page

Credited to

Dates

Published

Last updated

Corrections

  • : Corrected during a review of published articles. Details
  • : Corrected during a review of published articles. Details

Found this useful? Follow KBY for more like it.

Reader Interaction

Comments

Add a thoughtful note on Backend-for-Frontend Patterns for API Fan-Out. Comments are checked for spam and held for moderation before appearing.

Loading comments...

More from KBY that goes with this article.

Was this useful?

Reports go to the site owner and are used to correct pages. Corrections are listed at /corrections.

Engineering insights, direct to you.

Receive the latest Systems Engineering tutorials, production guides, Engineering Labs and operational best practices.