2026-09-27 · 11 min
API Gateway Pattern and BFF (Backend for Frontend): Architecture That Actually Scales in 2026
Your mobile app makes seven API calls to render a single screen. Each call hits a different microservice. The user sitting in a food court near Pasar Modern BSD waits two seconds watching a spinner — and your gateway logs show every upstream service responded in under 100ms.
The latency is in the round trips, not the services. This is the problem BFF solves.
What the pattern actually does
API Gateway + BFF is a two-layer architecture. The API Gateway sits at the edge: it handles TLS termination, auth token verification, rate limiting, request logging, and routing to the correct downstream service. It knows nothing about specific client needs.
Behind the gateway, a BFF (Backend for Frontend) handles the client-specific contract. The web BFF knows that the dashboard page needs data from three services and returns it as one aggregated response. The mobile BFF knows the same dashboard needs only 40% of those fields, and that iOS clients expect ISO dates while the Android team somehow negotiated Unix timestamps in a previous life.
Two separate concerns, two separate layers.
Client (Web / Mobile / Third-party)
│
▼
┌─────────────────────┐
│ API Gateway │ ← auth, rate limit, routing, logging
└─────────────────────┘
│ │
▼ ▼
┌──────────┐ ┌──────────┐
│ Web BFF │ │ Mobile │ ← aggregation, transformation,
│ │ │ BFF │ client-specific contracts
└──────────┘ └──────────┘
│ │
└──────┬───────┘
▼
┌─────────────────────────────────┐
│ Upstream Microservices │
│ (user-svc, order-svc, etc.) │
└─────────────────────────────────┘
Building the API Gateway layer
For a gateway that handles auth and routing at moderate scale, I use a combination of NGINX (or Caddy) for the edge proxy and a lightweight Node.js service for dynamic routing rules that need application logic.
Here is the NGINX config for the gateway layer:
# /etc/nginx/conf.d/api-gateway.conf
upstream web_bff {
server web-bff:3001;
keepalive 64;
}
upstream mobile_bff {
server mobile-bff:3002;
keepalive 64;
}
server {
listen 443 ssl;
server_name api.yourapp.com;
# Rate limiting — define zones at http block level
limit_req zone=api_limit burst=20 nodelay;
# Auth verification via internal subrequest
location /v1/ {
auth_request /auth/verify;
auth_request_set $user_id $upstream_http_x_user_id;
auth_request_set $tenant_id $upstream_http_x_tenant_id;
proxy_set_header X-User-Id $user_id;
proxy_set_header X-Tenant-Id $tenant_id;
proxy_set_header X-Real-IP $remote_addr;
# Route by client type header
if ($http_x_client_type = "mobile") {
proxy_pass http://mobile_bff;
break;
}
proxy_pass http://web_bff;
}
location /auth/verify {
internal;
proxy_pass http://auth-service:3000/verify;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header X-Original-URI $request_uri;
}
}
The auth_request directive calls your auth service for every inbound request. The auth service returns 200 with X-User-Id and X-Tenant-Id headers that NGINX captures and forwards downstream. By the time a request reaches any BFF, auth is already done.
For the auth service itself, keep it thin. It should validate the JWT, return the extracted claims as headers, and nothing else.
// auth-service/src/verify.ts
import { FastifyPluginAsync } from "fastify";
import { verifyJwt } from "./jwt";
export const verifyRoute: FastifyPluginAsync = async (app) => {
app.get("/verify", async (request, reply) => {
const authHeader = request.headers.authorization;
if (!authHeader?.startsWith("Bearer ")) {
return reply.status(401).send();
}
const token = authHeader.slice(7);
const payload = await verifyJwt(token).catch(() => null);
if (!payload) {
return reply.status(401).send();
}
// Gateway captures these as $upstream_http_x_user_id etc.
reply.header("X-User-Id", payload.sub);
reply.header("X-Tenant-Id", payload.tenantId);
reply.status(200).send();
});
};
Building the Web BFF
The BFF’s job is aggregation. One client request, multiple upstream calls, one shaped response. Here is a realistic example: the dashboard endpoint that pulls from user-service, order-service, and notification-service in parallel.
// web-bff/src/routes/dashboard.ts
import { FastifyPluginAsync } from "fastify";
import { userService, orderService, notificationService } from "../upstream";
import type { DashboardResponse } from "../types";
export const dashboardRoute: FastifyPluginAsync = async (app) => {
app.get<{ Reply: DashboardResponse }>("/v1/dashboard", async (request, reply) => {
const userId = request.headers["x-user-id"] as string;
const tenantId = request.headers["x-tenant-id"] as string;
if (!userId || !tenantId) {
// Gateway should have blocked this, but defensive check
return reply.status(401).send();
}
// Fan-out to upstream services in parallel
const [user, recentOrders, unreadCount] = await Promise.all([
userService.getProfile(userId, tenantId),
orderService.getRecent(userId, { limit: 5 }),
notificationService.getUnreadCount(userId),
]);
// Shape the response for what the web app actually needs
return reply.send({
user: {
id: user.id,
name: user.displayName,
avatarUrl: user.profilePicture?.url ?? null,
},
orders: recentOrders.items.map((o) => ({
id: o.id,
status: o.status,
total: o.totalAmount,
currency: o.currency,
createdAt: o.createdAt,
})),
notifications: {
unread: unreadCount,
},
});
});
};
This endpoint makes three upstream calls and returns one response. Seven round trips from the client becomes one.
Handling partial failures in the BFF
The dashboard will survive if notifications are temporarily down. Orders failing is more serious. You need to decide, per field, what constitutes a hard failure vs. a degraded response.
// Separate critical from non-critical upstream calls
const [user, recentOrders] = await Promise.all([
userService.getProfile(userId, tenantId),
orderService.getRecent(userId, { limit: 5 }),
]);
// Non-critical — degrade gracefully
const unreadCount = await notificationService
.getUnreadCount(userId)
.catch(() => 0); // fallback to 0 if notifications are down
return reply.send({
user: { ... },
orders: [...],
notifications: { unread: unreadCount },
_degraded: unreadCount === 0, // tell client something was unavailable
});
The _degraded field is optional but I always include it. The web app can show a subtle “some data may be unavailable” badge instead of hiding the issue entirely.
The Mobile BFF — where shape differences matter
Mobile clients almost always need smaller payloads. The same dashboard on mobile drops the order history (shown on a separate screen) and compresses user data.
// mobile-bff/src/routes/dashboard.ts
app.get("/v1/dashboard", async (request, reply) => {
const userId = request.headers["x-user-id"] as string;
const [user, unreadCount] = await Promise.all([
userService.getProfile(userId),
notificationService.getUnreadCount(userId).catch(() => 0),
]);
// Deliberately smaller response — no orders
return reply.send({
user: {
id: user.id,
name: user.displayName,
// No avatarUrl — mobile loads it lazily from a separate endpoint
},
notifications: { unread: unreadCount },
});
});
Two fewer upstream calls. Smaller payload. Mobile client renders in one request with no spinner for lazy-loaded content.
This is the concrete reason you want separate BFFs: the mobile team can change their contract without touching web, and neither team is blocked waiting for the other.
Deployment: one gateway, BFFs as separate services
In Kubernetes, each BFF is a separate Deployment. The gateway routes by header or path prefix.
# k8s/web-bff-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-bff
labels:
app: web-bff
spec:
replicas: 3
selector:
matchLabels:
app: web-bff
template:
metadata:
labels:
app: web-bff
spec:
containers:
- name: web-bff
image: registry.yourcompany.com/web-bff:latest
ports:
- containerPort: 3001
env:
- name: USER_SERVICE_URL
valueFrom:
secretKeyRef:
name: upstream-urls
key: user-service-url
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "500m"
memory: "256Mi"
Scale BFFs independently based on client traffic patterns. Web BFF and mobile BFF will have different peak hours and different throughput characteristics — treat them as separate services from day one.
What to avoid
Do not put business logic in the BFF. The BFF aggregates and reshapes; it does not compute, validate business rules, or own any data. If you find the BFF calculating discount amounts or checking inventory rules, that logic belongs in an upstream service. BFF is a translation layer, not a business layer.
Do not share a database between a BFF and any upstream service. BFF is a read-only aggregator at the HTTP level. The moment it starts writing directly to a database that a microservice also owns, you have a distributed monolith, not microservices.
Timeouts matter more here than anywhere. A BFF making three parallel upstream calls will be as slow as its slowest dependency. Set per-call timeouts aggressively — 500ms for internal services is reasonable — and decide what the fallback is before the call goes out.
When this architecture earns its complexity
I ran this pattern for a fintech platform serving both a React web app and two mobile apps (iOS and Android). The web team was shipping three times a week; the mobile team was on a two-week release cycle constrained by app store review. Without separate BFFs, every API change required coordination across three teams and a release calendar negotiation.
With separate BFFs, each team owned their contract. Web BFF changed on every deploy. Mobile BFF changed on the mobile team’s schedule. Upstream microservices were independent of both.
The gateway handled auth centrally. Each BFF handled its client’s specific needs. Upstream services remained clean — they returned complete domain objects and did not need to know which client was calling.
That separation is what makes this pattern worth the operational overhead. If you are running a single team with one web client and direct control over your backend, a simpler architecture almost certainly serves you better. But at the point where multiple client types are making divergent demands on the same upstream services, this pattern stops being overhead and starts being load-bearing.
The food court spinner problem disappears. And the coordination problem between teams disappears with it.
Ditulis oleh Reza Pradipta