Search Sreeni's Insights

Filter by content type
technical February 16, 2017 6 min read

Backend for Frontend (BFF) pattern for SPA and mobile

The Backend for Frontend pattern tailors API aggregation, payloads and authentication to SPA and mobile clients without duplicating business logic or turning the API into a gateway.

Share:

Backend for Frontend (BFF) pattern for SPA and mobile

A single general-purpose API is looking convenient until a SPA and a mobile application are asking for different data, authentication and release behaviour. The SPA may need a factsheet summary and price history in one screen, while the mobile application needs a small payload for a slow network. If one API is serving every experience, it is becoming a compromise for all of them.

In this article, we are going to discuss the Backend for Frontend (BFF) pattern, the difference between one general API and one BFF per experience, and how to implement the pattern with ASP.NET Core 1.1. We will also see how to avoid duplicating business logic and how BFF differs from an API gateway.

TL;DR Summary

  • A BFF is a backend owned by a front-end team for one user experience.
  • A SPA BFF and a mobile BFF can aggregate and shape data differently.
  • BFFs should contain experience orchestration, not duplicated fund business rules.
  • Token handling and client-specific security belong at the BFF boundary.
  • A BFF can reduce chatty calls, but it adds another service and operational path.
  • An API gateway provides shared front-door concerns; a BFF provides experience-specific composition.

Challenges

One payload does not fit all

A general API may return every fund field because one client needs the complete resource. The mobile application is then downloading data it does not display, and the SPA is making several calls to construct one screen.

Chatty client calls

A factsheet screen may call fund details, current price, documents and permissions separately. Network latency is adding up, especially for a mobile client. The 2016 fine-grained versus coarse-grained API article explains why a client should not be forced to make many small calls.

Client-specific authentication

The SPA and mobile application may have different token flows, refresh behaviour and device concerns. Pushing every client rule into the general API is making that API difficult to understand and test.

What is a BFF?

Backend for Frontend is a pattern where a backend service is created for and owned by one front-end experience, such as a SPA or mobile application.

In simple terms, the BFF is a translator and aggregator between the client and domain APIs. It shapes the response, handles client authentication concerns and calls the services required by one screen, while the core fund rule remains in a shared domain service.

The following diagram compares a general-purpose API with separate BFFs for SPA and mobile.

General API versus BFF
General API versus BFF

The purple path is the BFF route: each experience receives a payload designed for its screen and network constraints.

Why the BFF pattern is important?

The BFF pattern is important because it is reducing client complexity and allowing each experience to evolve without changing one general contract for every consumer. A mobile release can use a compact response while the SPA adds a new aggregation.

In our case, a factsheet SPA can receive fund facts, current unit price and document links in one response. The mobile BFF can return only the title, price and a small document summary. Both BFFs call the same application or domain services for fund rules.

General API versus BFF

ApproachProsCons
One general API+ Fewer services
+ One contract to govern
− Payload compromise
− Chatty clients or client-specific branching
BFF per experience+ Experience-specific payload
+ Aggregation close to the client
− More services to operate
− Risk of duplicated logic

BFF versus API gateway

An API gateway is a shared front door for routing, TLS, rate limiting, authentication integration and other cross-cutting controls. A BFF is an application service which understands the needs of one front-end experience.

Keep gateway rules generic. Keep BFF composition specific. A gateway should not calculate fund eligibility or decide which factsheet fields a mobile screen needs, and a BFF should not become the central place for every team’s rate rule.

ASP.NET Core 1.1 worked example

Create a small controller for the SPA BFF,

[Route("api/spa/fund-summary")]
public class FundSummaryController : Controller
{
    private readonly IFundService funds;
    private readonly IPriceService prices;
    private readonly IDocumentService documents;

    public FundSummaryController(
        IFundService funds,
        IPriceService prices,
        IDocumentService documents)
    {
        this.funds = funds;
        this.prices = prices;
        this.documents = documents;
    }

    [HttpGet("{fundId}")]
    public async Task<IActionResult> Get(string fundId)
    {
        var fund = await funds.GetAsync(fundId);
        var price = await prices.GetLatestAsync(fundId);
        var document = await documents.GetLatestFactsheetAsync(fundId);

        return Ok(new
        {
            fund.Code,
            fund.Name,
            price.Value,
            document.Url
        });
    }
}

The BFF is composing data, not calculating the price or deciding whether a fund is eligible. Put those rules in IFundService or another shared application service, so the mobile BFF does not copy them.

ASP.NET Core 1.1 can register the services in ConfigureServices,

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddScoped<IFundService, FundService>();
    services.AddScoped<IPriceService, PriceService>();
    services.AddScoped<IDocumentService, DocumentService>();
}

For independent calls such as price and document metadata, use parallel execution only when the downstream services have compatible timeout and failure rules. If the price call fails, the BFF should return the contract agreed for the screen, such as a partial response or a clear error, rather than hiding a missing value as zero.

Test the BFF at two levels. Unit tests can verify payload mapping and authorization decisions, while ASP.NET Core integration tests can verify routing, model binding and the response shape. Monitor each downstream dependency separately because one slow service can make the BFF look slow even when its own code is healthy.

Treat the BFF contract as a product contract. A front-end team should be able to change its composition without asking every domain team to add a field for one screen. At the same time, the BFF should publish which domain services it is depending on, because the aggregation is creating a real operational dependency graph.

Test the BFF at two levels. Unit tests can verify payload mapping and authorization decisions, while ASP.NET Core integration tests can verify routing, model binding and the response shape. Monitor each downstream dependency separately because one slow service can make the BFF look slow even when its own code is healthy.

Selection criteria

Choose a BFF when the client needs aggregation, payload shaping, different authentication or an independent release cycle. Keep one general API when the clients have the same resource contract and the extra service would only be forwarding calls.

Consider ownership. A BFF is healthiest when the front-end team owns its contract, tests and support. Consider latency: aggregation reduces client round trips but the BFF must handle parallel calls, timeouts and partial failure. Consider security: the BFF should forward only the claims and data needed by the client.

Must Do / Should / Don’t

Must Do

  • Must keep business rules in shared domain or application services.
  • Must define a payload contract for each experience.
  • Must handle partial dependency failure and timeouts.
  • Must protect tokens and never return data the client is not authorised to see.

Should

  • Should aggregate calls which are naturally part of one screen.
  • Should call independent services in parallel where the failure policy allows it.
  • Should test SPA and mobile contracts separately.

Don’t

  • Don’t create a BFF which only forwards every request unchanged.
  • Don’t duplicate fund eligibility or pricing logic in every BFF.
  • Don’t put all API gateway policies into one BFF.
  • Don’t assume a smaller payload removes authorization requirements.

Wrap up

In this article, we have looked at the BFF pattern, general APIs, SPA and mobile payloads, aggregation, authentication, ASP.NET Core 1.1 and the difference between BFF and API gateway responsibilities.

Thanks for reading this article. In the next article, I will walk you through API versioning strategies using URI, header and query-string approaches.

Related Posts