Backend for Frontend
A Backend for Frontend is a thin API layer built and owned for one specific client—web, mobile, or a partner integration—that aggregates and reshapes calls to backend services into exactly what that client needs. This guide connects the programming model to production decisions, failure modes, security, testing, performance, deployment, and operations.
Overview
Instead of one general-purpose API serving every client's differing needs with optional fields and version branches, each frontend gets its own BFF: composing multiple backend calls into one response, hiding backend topology, and evolving independently of other clients' needs. The tradeoff is more services to own and keep consistent, so BFFs work best when client needs have genuinely diverged, not as a default for every project. The central design goal is a client-specific backend that composes downstream capabilities, protects browser credentials, and shapes contracts around one user experience. A BFF owns client orchestration and presentation-shaped contracts; domain rules and source-of-truth data remain in downstream services. Teams should begin with a concrete user outcome and quality-attribute scenario, choose the smallest architecture that satisfies it, and record the operational owner. An oversized BFF becomes a second monolith, duplicates business logic, fans out without deadlines, or exposes cookies and tokens through weak browser controls. A production design therefore needs explicit limits, identity, cancellation, telemetry, evaluation, recovery, and a safe change path. The dedicated sample keeps external infrastructure optional so readers can inspect the governing mechanics locally, then maps those mechanics to the hosted services and controls required in a real environment.
What you will learn
- Explain the purpose and boundaries of Backend for Frontend without confusing the tool with the whole architecture.
- Decide when Backend for Frontend is appropriate and when a simpler design is safer.
- Design the core contracts, ownership, data flow, and failure behavior for a client-specific backend that composes downstream capabilities, protects browser credentials, and shapes contracts around one user experience.
- Apply authentication, authorization, validation, privacy, and least privilege at every trust boundary.
- Test normal behavior, negative paths, dependency failure, recovery, and operational signals.
- Deploy incrementally with observable acceptance criteria, rollback, and accountable ownership.
- Run and extend the dedicated BFF Dashboard Composition sample.
Prerequisites
- .NET 10, C# async programming, dependency injection, configuration, and structured logging.
- The domain and platform fundamentals referenced by Backend for Frontend.
- Basic security, testing, observability, and continuous-delivery concepts.
- A .NET 10 SDK to run BFF Dashboard Composition; no paid cloud account is required for its default path.
When to use Backend for Frontend
Good fit
- Use Backend for Frontend when a client-specific backend that composes downstream capabilities, protects browser credentials, and shapes contracts around one user experience directly addresses a measured product or operational need.
- Use it when a named team can own the contracts, data, deployment, telemetry, cost, and incident response.
- Introduce it behind a narrow boundary and prove the riskiest assumption with a production-shaped experiment.
Choose another approach when
- Avoid Backend for Frontend when the same outcome is available through a smaller in-process or managed capability.
- Do not adopt it only for résumé value, diagram symmetry, or a vendor checklist.
- Do not proceed without a threat model, failure policy, observability, and an exit or rollback path.
Key concepts
A BFF composes calls to multiple backend services into the single shaped response its one client actually needs.
Moving aggregation, retries, and field shaping into the BFF keeps client code focused on presentation instead of backend orchestration.
Each BFF can change its contract and pace of release without coordinating with unrelated frontends sharing the same backend.
Clients depend on their BFF's contract, not on the internal service boundaries behind it, so backend services can be refactored without breaking clients.
Client-shaped composition is a first-class design concern for a client-specific backend that composes downstream capabilities, protects browser credentials, and shapes contracts around one user experience.
Token and cookie boundary is a first-class design concern for a client-specific backend that composes downstream capabilities, protects browser credentials, and shapes contracts around one user experience.
Architecture
A frontend calls its own BFF, which aggregates and reshapes calls to shared backend services into that client's specific response shape.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
Build the critical path deliberately, then verify its observable behavior.
- 01
- 02
- 03
- 04
- 05
- 06
- 07
Code example
A BFF endpoint composes two backend calls into the single shape the web client actually renders.
app.MapGet("/bff/order-summary/{orderId:guid}", async (
Guid orderId, IOrdersClient orders, ICustomersClient customers, CancellationToken ct) =>
{
var order = await orders.GetAsync(orderId, ct);
var customer = await customers.GetAsync(order.CustomerId, ct);
return Results.Ok(new OrderSummaryResponse(
order.Id, order.Total, order.Status, customer.DisplayName));
});Testing strategy
Test Backend for Frontend as a behavior and operational boundary, not only as a library call.
- Unit-test deterministic policy, validation, mapping, and error classification.
- Use contract tests for provider, protocol, platform, and downstream boundaries.
- Run integration tests with realistic serialization, configuration, identity, cancellation, and dependency behavior.
- Exercise the primary failure: An oversized BFF becomes a second monolith, duplicates business logic, fans out without deadlines, or exposes cookies and tokens through weak browser controls.
- Load-test representative and adversarial inputs while observing latency, errors, saturation, and cost.
- Keep a versioned acceptance suite that protects behavior during dependency and configuration changes.
Security considerations
Treat Backend for Frontend input, dependencies, credentials, output, and administrative controls as separate trust boundaries.
- Authenticate the caller and workload; authorize the operation and resource at the system that performs it.
- Validate type, size, count, format, tenant, and allowed values before expensive or consequential work.
- Use short-lived identity and least privilege; keep secrets out of source, logs, prompts, packages, and client storage.
- Classify data, minimize collection and retention, redact telemetry, encrypt in transit and at rest, and support deletion policy.
- Require explicit approval and idempotency for external side effects; audit actor, intent, policy decision, and outcome.
- Patch and inventory dependencies, pin trusted sources, scan artifacts, and restrict outbound destinations.
Performance and scalability
Optimize the end-to-end user outcome within downstream capacity and cost limits.
- Measure p50, p95, p99, throughput, failures, saturation, queue time, payload size, and cost together.
- Set end-to-end deadlines and propagate cancellation instead of stacking independent timeouts.
- Bound concurrency, queues, retries, payloads, fan-out, and caches so overload cannot grow without limit.
- Cache only when identity, freshness, privacy, invalidation, and failure semantics are explicit.
- Batch or stream only when the workload and user latency target justify the complexity.
- Capacity-test dependency degradation and recovery because retry and replay traffic often dominate peak load.
Deployment and operations
Promote an immutable, observable change through environments with compatibility and rollback evidence.
- Keep environment configuration external, validated at startup, and free of long-lived credentials.
- Provision dependencies, identity, network policy, dashboards, alerts, and budgets through reviewed automation.
- Use additive contracts and mixed-version compatibility before removing old behavior.
- Deploy with canary or staged exposure, health gates, graceful shutdown, and automated rollback signals.
- Record version and configuration in telemetry; retain runbooks, ownership, recovery targets, and escalation paths.
- Rehearse dependency loss, restore, credential rotation, region or device failure, and data recovery where applicable.
Common problems and fixes
The local sample works but production behavior differs
Likely cause: Provider, identity, network, limits, data, or configuration assumptions were hidden.
Fix: Compare effective configuration and correlated dependency telemetry, then reproduce the smallest differing boundary.
Latency rises sharply under load
Likely cause: Concurrency, fan-out, retries, queues, or a downstream quota is unbounded.
Fix: Inspect saturation and queue time, stop retry amplification, apply backpressure, and reduce work per request.
A request succeeds twice or creates duplicate effects
Likely cause: The caller retried after an ambiguous result and the operation was not idempotent.
Fix: Use a stable operation ID, persist the outcome with the effect, and return the recorded result on replay.
Sensitive information appears in telemetry
Likely cause: Raw inputs, outputs, headers, or exceptions were logged without classification and redaction.
Fix: Stop the leak, restrict and rotate access as needed, redact by default, and test the telemetry schema.
A dependency upgrade changes behavior
Likely cause: Application semantics depended on provider-specific defaults or an untested protocol detail.
Fix: Pin or roll back, compare release notes and contract traces, then update the acceptance suite before retrying.
Operators cannot explain a failed user outcome
Likely cause: Logs, metrics, traces, version, and business identifiers are not correlated.
Fix: Add end-to-end correlation and a dashboard that links the user journey to dependency and deployment signals.
Best practices
- Create a new BFF only once a client's needs have genuinely diverged from others, not preemptively for every frontend.
- Keep a BFF thin—composition and shaping, not business logic that belongs in the backend services it calls.
- Own each BFF with the team that owns its frontend, so contract changes don't require cross-team coordination.
- Apply the same resilience patterns—timeouts, retries, circuit breakers—to a BFF's outbound calls as any other service-to-service call.
- Use one BFF when a client has distinct composition, security, or release needs; do not create one per screen.
- Propagate cancellation and deadlines, bound fan-out, cache only safe user-scoped results, and return partial data deliberately.
Production checklist
- The need for Backend for Frontend, alternatives, owner, constraints, and exit criteria are recorded.
- Contracts, data ownership, trust boundaries, limits, and compatibility policy are explicit.
- Identity, least privilege, validation, privacy, redaction, audit, and side-effect approval are enforced.
- Timeout, cancellation, retry, backpressure, idempotency, fallback, and recovery behavior are tested.
- Logs, metrics, traces, cost, quality, business outcomes, dashboards, alerts, and runbooks identify version and owner.
- Capacity, dependency failure, restore, rollback, credential rotation, and incident response are rehearsed.
- Lifecycle, deprecation, data retention, dependency patching, and operational cost have named owners.
Common interview questions
How is a BFF different from an API gateway?
A gateway is typically one shared entry point applying cross-cutting concerns like routing, auth, and rate limiting for many clients; a BFF is dedicated to one client, aggregating and shaping backend calls into that client's specific needs—the two are often used together, gateway in front of multiple BFFs.
What problem does a BFF solve that a single shared API doesn't?
A shared API serving very different clients accumulates optional fields, version branches, and client-specific logic to satisfy everyone; a BFF lets each client's API evolve and be shaped independently, avoiding that shared complexity.
What's the main cost of adopting the BFF pattern?
More services to build, deploy, and keep consistent—logic like authorization or validation can end up duplicated across BFFs unless it's deliberately kept in shared backend services instead.
Why can a browser BFF reduce token exposure?
The browser can hold a protected same-site session cookie while the server-side BFF stores or exchanges access tokens away from JavaScript.
Where should business rules live?
In domain services or application modules. The BFF should compose and reshape outcomes, not become another source of truth.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
BFF Dashboard Composition
A .NET 10 dashboard composer with parallel bounded calls, user-scoped caching, partial-failure reporting, and a presentation-specific response.
- Run
dotnet run --project src/BffDashboardComposition- Test
dotnet run --project src/BffDashboardComposition -- --self-test