Running a BFF in Production: Deploy and Scale
On this page
Deploy on the app's origin
The cleanest production layout serves the React app and its BFF from one origin:
https://app.taskboard.dev/ -> static app (CDN or the BFF itself)
https://app.taskboard.dev/auth/* -> BFF
https://app.taskboard.dev/bff/* -> BFF
https://app.taskboard.dev/api/* -> BFF (proxied to services)A CDN or load balancer in front can serve the static files and route the three prefixes to the BFF. One origin means no CORS, __Host-Http- cookies work, and the CSRF defense from Day 8 stays simple.
Make sure the CDN never caches BFF responses. Route /auth, /bff and /api with caching disabled, and send Cache-Control: no-store on personal responses as a second guard.
Run behind a proxy correctly
Behind a load balancer, the BFF sees the proxy's address and plain HTTP, not the user's. Tell Fastify to trust the proxy headers, but only from your proxy:
const app = Fastify({ trustProxy: '10.0.0.0/8' }); // your load balancer's networkThen req.ip and req.protocol reflect the real client, which matters for rate limiting, logs and building redirect URLs. Never trust X-Forwarded-* headers from the open internet, since anyone can send them.
Build public URLs, such as the OIDC redirect_uri, from configuration (PUBLIC_URL=https://app.taskboard.dev), not from the incoming Host header, which an attacker can sometimes influence.
Configuration and secrets
A BFF holds powerful secrets: the OIDC client secret, the token encryption key and Redis credentials. Load them from a secret manager or your platform's secret store, never from the code or the image.
Check them at startup and fail fast if anything is missing or malformed:
import { z } from 'zod';
const env = z.object({
PUBLIC_URL: z.url(),
OIDC_ISSUER: z.url(),
OIDC_CLIENT_ID: z.string().min(1),
OIDC_CLIENT_SECRET: z.string().min(16),
TOKEN_KEY: z.string().refine((k) => Buffer.from(k, 'base64').length === 32, 'TOKEN_KEY must be 32 bytes, base64'),
REDIS_URL: z.url(),
TASKS_API_URL: z.url(),
}).parse(process.env);A BFF that starts with a missing secret fails on the first login, possibly hours later. One that refuses to start fails during the deploy, where you can see it.
For stronger client authentication than a shared secret, many providers support private_key_jwt, where the BFF signs a short assertion with a private key that never leaves it. openid-client supports it through oidc.PrivateKeyJwt.
Scale out
With sessions in Redis (Day 6), BFF instances are stateless, so scaling is the usual horizontal setup:
- Run at least two instances behind the load balancer. No sticky sessions needed.
- Make Redis highly available, because when Redis is down nobody can sign in or use a session. Use a managed Redis or Valkey with a replica and automatic failover.
- Add a rate limit per session and per IP, for example with
@fastify/rate-limitbacked by the same Redis, so one client can't exhaust your downstream quota. - Shut down gracefully: stop accepting connections, let in-flight requests finish, then exit. Fastify's
app.close()does this when called from aSIGTERMhandler.
Keep the BFF thin
The biggest long-term risk is not technical. Over time, teams add "just one rule" to the BFF: a price calculation, a permission check, a validation the service doesn't do. A year later the BFF holds business logic no other client shares, and the web and mobile apps disagree about prices.
Healthy rules of thumb:
- The BFF composes, the services decide. Business rules and authorization decisions belong in the services that own the data. The BFF's job is identity, aggregation, shaping and protocol translation.
- One BFF per experience. When mobile needs something different, give it its own BFF instead of growing branches inside the web one.
- The frontend team owns it. If the web team must file a ticket with another team to change the web BFF, the main benefit of the pattern is gone.
- No BFF calls another BFF. Shared needs go into a service, or into a small shared library that each BFF uses.
Capstone: ship the TaskBoard BFF
Bring the course together and check each item against your own build:
- Fastify 5 serving the React app, with
/auth,/bffand/apiroute groups, on one origin. - OpenID Connect sign-in with authorization code, PKCE,
stateandnonce, a safereturnTo, and a fresh session id after login. - Sessions in Redis with idle and absolute timeouts, encrypted tokens, and a
__Host-Http-sidcookie withHttpOnly,SecureandSameSite. - A proxy that swaps the cookie for a bearer token, single-flight token refresh, and logout through the provider's end-session endpoint.
- The custom-header CSRF check on every route, plus an
Origincheck, and no CORS. - A dashboard endpoint with per-call timeouts,
allSettled, adegradedlist, a circuit breaker on the optional dependency, and a per-user cache. - Tests with
injectandMockAgentfor every failure decision, an attacker test for CSRF, and an end-to-end login test. - Request ids and trace propagation, redacted logs, startup config validation,
trustProxylimited to your load balancer, and graceful shutdown.
When every item works, you have a BFF that follows RFC 10017's recommended pattern and holds up under real failures. The combined course later in this series adds tRPC between the React app and this BFF, and splits the frontend into micro-frontends that share one BFF session.
Check yourself
The Host header can sometimes be influenced by attackers or rewritten by proxies, and a wrong value either breaks login or sends codes somewhere unexpected. The redirect URI must also match what's registered with the provider exactly. Building it from PUBLIC_URL in configuration avoids both problems.
No. Every instance reads sessions from the same Redis, so any instance can serve any request, and the load balancer can spread traffic freely. That also means instances can be added, removed or restarted without signing anyone out.
Business logic in one BFF isn't shared with other clients, so prices can differ between web and mobile, and the rule has two owners. It belongs in the pricing service.
Fastify isn't trusting the proxy's forwarded headers, so it sees the balancer's connection, not the user's. Set trustProxy to your load balancer's network range only. Trusting X-Forwarded-* from anywhere would let any client fake its IP address.
Otherwise it starts fine and fails later, on the first login or session read, possibly hours after the deploy, when nobody is watching. Validating configuration at startup makes the deploy itself fail, where the problem is obvious and the previous version is still running.