Backends For Frontends
We discuss about the need of BFF Layer - A layer between the frontend and the backend microservices, on how it can help in simplifying complicated applications with multiple frontends.
Assume a scenario
We have an application with multiple Frontends supported by a microservice architecture -
An e-commerce platform with the following frontends:
-
Consumer/Buyer Frontend:
- Functionality: User can view all the products, add them to cart, create orders and track them.
- Data Scope: View only access to products. CRUD on Cart. Create Orders and View orders.
- Access Control: No special rule based access control.
-
Seller Frontend:
- Functionality: User can create their products, manage inventory, view and track orders
- Data Scope: CRUD access to only their products and their invertory. View orders for only their products.
- Access Control: Rule based access control for different department of seller's organization based on Master Product List management, Price Manager, Inventory Manager and Order Fulfillment Manager
-
3rd Party Logistics Vendor Frontend:
- Functionality: User can update orders, view orders assigned to them. Chat with customer who has made the order
- Data Scope: Access to orders allocated to them and user information.
- Access Control: Rule based access control for types of users like Dispatch Manager, Delivery Agent, etc
-
Customer Support/Admin Frontend:
- Functionality: User can manage all the entities to solve the customer queries
- Data Scope: Everything except sensitive individual user information.
- Access Control: Rule based access control for different types of support agent - Order Fulfillment, Refunds, Product Listing, etc.
Lets assume the architecture to be:
In this scenario we face the following challenges:
-
Frontend Orchestration of requests
- Multiple network calls over unstable/unreliable connection.
- Client side Data Massaging.
- Transmission of unwanted attributes.
- Service level configuration for complex rule based access and data filtering.
Introducing the BFF Layer
BFF Layer is the layer between the Frontend (Presentation Layer) and the Backend - designed with what would have been Frontend specific orchestration and data processing responsibilities. An application can have multiple BFF supporting dedicated frontends.
Lets introduce the BFF Layer in our architecture:
Addressing the challenges:
1. Frontend Orchestration
1.1 Multiple network calls over unstable/unreliable connection.
Scenario implementing a product page
Let’s assume we need to show 3 primary information on the product page:
- Product Information - Name, Dimensions, Directions to Use, etc. from product cluster.
- Product Price - Current Product price from the product cluster.
- User's order history of the product - List the orders placed by the user along with date of order from the order and fulfilment cluster.
Lets compare how the approach would differ for request orchestration without the BFF and with the BFF layer.
|
|
The non-BFF Layer way
|
The BFF Layer way |
|---|---|
|
|
|
|
|
1.2 Client Side Data Massaging
Lets assume a scenario where we want to display the User’s orders on the Order’s page.
We need to combine the data from 2 sources -
- The order API which will return the orders with product Ids.
- The product API which will return the product details based on the product id supplied above.
Without the BFF layer frontend will have to do the following:
- An API call to the gateway will be made to fetch the Order Records
- Iterate over the orders to fetch the product ids
- Make API call to the gateway to fetch the product details from the product ids
- Map the product details to the respective orders and render.
Disadvantages
1. Performance and Efficiency Issues-
Multiple Network Round-Trips (The N+1 Problem):
The frontend has to make at least two separate HTTP requests to the gateway/backend: one for orders and one for product details.
This is known as the $N+1$ problem in some contexts (though here it's $1+1$, it scales poorly). Each request adds network latency and overhead.
If the product details weren't available via a bulk API, the frontend would have to make $1 + N$ requests (1 for orders, $N$ for each distinct product), which is extremely slow.
- Increased Latency: The total time to render the page is the sum of: (Order API response time) + (Frontend processing/iteration time) + (Product API response time) + (Frontend data mapping/rendering time). The sequential nature of the calls significantly increases the overall latency the user experiences.
- Over-fetching/Under-fetching: The Order API might return more data than needed for the order summary page, or the Product API might not provide everything, forcing the frontend to make yet another request, leading to inefficient data transfer.
- Data Aggregation Logic in the Client: The crucial business logic of combining data from independent services (orders and products) resides in the frontend. This logic is complicated to write, difficult to test, and needs to be maintained across different client types (web, iOS, Android).
- Client-Specific API Contracts: Any change in the upstream service (e.g., the Product API changes its field names or structure) requires changes and redeployment across all affected frontend applications.
- Error Handling Complexity: The frontend needs robust logic to handle failures in either the Order API or the Product API call, as well as handle partial data scenarios, making the UI code much more verbose.
- Slower Time-to-Render: Due to the compounded network latency, the user has to wait longer to see the complete, meaningful content (orders with product names).
- Jank/Flicker During Loading: The frontend might first render the orders with just product IDs, and then, after the second API call completes, dynamically update the page with the product names, leading to a jarring visual experience.
- Increased Client-Side Processing: The frontend has to dedicate CPU cycles to iterating through the orders, extracting IDs, making the second request, and then mapping the results back. On low-powered devices, this can noticeably slow down the application.
Request:
// GET /orders
// host: api-gateway
Response:
{
"orders": [
"id": "a712d092-1b37-489f-91b5-f8fa99d9c82a",
"userId": "084b45ed-2772-4c04-bf28-2f859051d807",
"couponApplied": false,
"discounts": []
"orderItems": [
{
"productId": "efcb7cbe-858a-49d1-853e-c7bcd03cec56",
"cost": 500,
"currency": "INR"
},
{
"productId": "8d798b77-d382-4ade-8959-f11506782cdb",
"cost": 1000,
"currency": "INR"
},
],
"cost": 1500,
"currency": "INR"
]
}
Request:
// POST /bulk-products
// host: api-gateway
// {
// "ids": [
// "efcb7cbe-858a-49d1-853e-c7bcd03cec56"
// "8d798b77-d382-4ade-8959-f11506782cdb",
// ]
// }
Response:
{
"efcb7cbe-858a-49d1-853e-c7bcd03cec56": {
"name": "Product 1",
"brand": "Brand A",
"description": "..."
}
"8d798b77-d382-4ade-8959-f11506782cdb": {
"name": "Product 2",
"brand": "Brand A",
"description": "..."
}
}
With the BFF
With a BFF layer, the complexity of calling multiple backend services is handled on the server side, creating a single, optimized data retrieval step for the client.
- An API call is made from the frontend to the BFF's dedicated endpoint (e.g.,GET /current-user-orders-for-display).
- The BFF internally makes the first API call to the Order Service (GET /orders) to fetch the order records and product IDs.
- The BFF iterates over the returned orders to extract the product IDs.
- The BFF makes a second internal API call to the Product Service (POST /bulk-products) using the gathered IDs.
- The BFF maps the product details to the respective orders, creating a combined, aggregated data structure tailored specifically for the Order Page.
- The BFF sends this single, rich, aggregated response back to the frontend.
- The Frontend receives the complete, ready-to-display data in one response and renders the order page.
Advantages
1. Improved Performance and Efficiency- Single Network Round-Trip: The frontend only makes one API call to the BFF. The BFF handles the multiple, sequential internal calls to the backend services (Order API and Product API) in a fast, reliable internal network, dramatically reducing the end-user's perceived latency.
- Optimized Data Payload: The BFF transforms and aggregates the raw data from the upstream services into a single response that contains exactly the data structure the Order page needs. This eliminates over-fetching (sending unnecessary fields) and reduces the total data size transferred over the public internet.
- Offloading Client-Side Processing: The resource-intensive tasks of iteration, data extraction, and mapping/joining are performed by the powerful, scalable backend infrastructure (the BFF), instead of the client's potentially limited CPU.
- Decoupling Client and Services: The frontend is now completely decoupled from the backend service architecture. Changes to the internal Product API or Order API (like field renaming or service splitting) only require updates to the BFF, not to every frontend application (Web, iOS, Android).
- Simplified Client-Side Code: The frontend's responsibility shrinks to making a single call and rendering the pre-processed data. This makes the client code smaller, easier to test, and faster to develop.
- Client-Specific API Contracts: The BFF can be tailored to the specific needs of a particular client (e.g., a "Mobile BFF" and a "Web BFF"). This prevents the mobile app from receiving unnecessary data intended only for the web interface.
- Enhanced Security: The BFF acts as a single point of entry and control. It can manage complex authorization logic, apply rate limiting, and ensure that only relevant data is exposed, shielding the underlying microservices from direct public exposure.
- Consistent and Fast UX: The client receives the complete data required to render the page in one go, eliminating the "jank" or flickering that occurs when data is loaded in stages. This results in a faster and more consistent Time-to-Render.
- Centralized Error Handling: The BFF can handle internal service failures, apply fallback logic, or format error messages consistently before sending them to the client, simplifying the frontend's error presentation logic.
Request:
// GET /current-user-orders-for-display
// host: consumer-app-bff
Response:
{
"orders": [
"id": "a712d092-1b37-489f-91b5-f8fa99d9c82a",
"userId": "084b45ed-2772-4c04-bf28-2f859051d807",
"couponApplied": false,
"discounts": []
"orderItems": [
{
"productId": "efcb7cbe-858a-49d1-853e-c7bcd03cec56",
"product": {
"name": "Product 1",
"brand": "Brand A",
"description": "..."
}
"cost": 500,
"currency": "INR"
},
{
"productId": "8d798b77-d382-4ade-8959-f11506782cdb",
"product": {
"name": "Product 2",
"brand": "Brand A",
"description": "..."
}
"cost": 1000,
"currency": "INR"
},
],
"cost": 1500,
"currency": "INR"
]
}
1.3 Data Customization and Prevention of Unwanted Attribute Transmission
In a multi-client platform, different types of users accessing the same underlying data record often require different views or levels of access to that record's attributes. Failing to restrict these attributes can lead to data over-exposure or security/privacy issues.
Consider the User Record example:
- Consumer-Facing Frontend: When displaying user feedback, this frontend needs access to the user's display name and profile photo. Crucially, for user privacy, the record must not expose contact details (phone number, email).
- 3rd-Party Logistics (3-PL) Frontend: The delivery team using this frontend needs the user's contact information (phone number, address) to complete the order. It may not need the profile photo.
The dedicated Backend for Frontend (BFF) layer excels here because it allows for the customization of the Data Transfer Objects (DTOs). The BFF acts as a filter and translator:
- It calls the core User Service to get the complete, sensitive record.
- It creates a custom DTO tailored for the specific client (e.g.,
ConsumerUserDTOor3PLUserDTO). - It only maps the required, non-sensitive fields to that client-specific DTO, effectively pruning or masking the unnecessary attributes before the data leaves the server-side environment.
2. Service level configuration for complex rule based access and data filtering
When dealing with a diverse ecosystem of users—ranging from individual Buyers and Sellers to Logistics Agents and Admin Support—managing security directly at the microservice or frontend level becomes a nightmare. A BFF (Backend for Frontend) layer acts as a sophisticated "security filter" tailored to each specific user journey.
2.1 Fine-Grained Data Filtering
In your scenario, the Product Service holds the master data for all products. However, the data needs to be "pruned" differently for each frontend to ensure security and relevance:
- Consumer BFF: Filters the response to show only "Active" and "In-Stock" products, hiding internal seller IDs or wholesale pricing.
- Seller BFF: Strictly filters the Product List to only return records where
sellerId == currentUserId. It prevents a seller from accidentally (or maliciously) accessing a competitor's inventory. - Admin BFF: Provides a high-level summary but masks sensitive fields like the product's raw manufacturing cost unless the user has "Financial Admin" privileges.
2.2 Implementing Role-Specific Business Rules
Instead of cluttering your core microservices with "if-else" logic for every possible frontend role, the BFF handles role-based logic locally. This keeps your core services generic and reusable.
| Frontend | Role Example | BFF Logic / Rule Implementation |
|---|---|---|
| Logistics | Delivery Agent | Allows PATCH updates only to the orderStatus field. Blocks updates to orderPrice. |
| Seller | Price Manager | Allows updates to price and discount fields but denies access to inventoryQuantity. |
| Admin | Refund Agent | Can view full transaction history but cannot edit the Product Description. |
2.3 Benefits of this Approach
- Reduction of "Leaky Abstractions": Without a BFF, you might accidentally send the Buyer's phone number to a Seller who doesn't need it. The BFF ensures only the 3PL Vendor BFF receives contact details, maintaining strict privacy compliance.
-
Simplified Frontend Logic: The frontend doesn't need complex
if(user.role === 'Admin')blocks to hide buttons or fields. It simply receives a data model from the BFF that contains only what the user is allowed to see and do. - Security in Depth: Even if a malicious user bypasses the UI and hits an API directly, the BFF Layer validates their role and filters the data before it ever reaches the network, providing an essential secondary layer of defense.
3. Miscellaneous
While the benefits of a BFF are clear, implementing one in a production environment requires thinking about how the layer handles change, failure, and infrastructure costs.
4.1 Versioning and Mobile App Compatibility
One of the biggest challenges in mobile development is that you cannot force users to update their apps. This means your BFF must often support multiple versions of the frontend simultaneously.
- BFF Versioning: Unlike a web frontend that updates on a refresh, a "Seller Mobile App v1.0" might exist alongside "v2.0" for months. The BFF allows you to maintain legacy API contracts (v1 endpoints) while the core microservices move forward.
- Graceful Deprecation: You can use the BFF to inject "Update Required" flags into the data response, prompting users to update their app when a version becomes too old to support.
4.2 Resiliency and the "Circuit Breaker" Pattern
Because the BFF aggregates data from multiple services, it is susceptible to cascading failures. If the "Product Service" is down, should the entire "Order Page" fail to load?
- Partial Degradation: The BFF can be programmed to handle errors gracefully. If the Product API fails, the BFF can still return the Order list with a placeholder like "Product details temporarily unavailable" instead of a 500 Error.
- Circuit Breakers: Implementing patterns like Circuit Breakers at the BFF level prevents the layer from repeatedly calling a struggling service, allowing the backend to recover while providing a cached or fallback response to the user.
4.3 The "BFF Tax": Infrastructure and Latency
It is important to be transparent about the trade-offs. Adding a BFF adds a "hop" in your network architecture.
- Internal Latency: While the user sees one request, the BFF is making several. To minimize this, the BFF should be hosted in the same region/data center as the core microservices to keep "internal" latency under 10-20ms.
- Resource Overhead: You are essentially adding another microservice to your stack. This means more CI/CD pipelines, more monitoring, and more compute costs. For small teams, this "BFF Tax" is a key factor in deciding whether to use a generic API Gateway or a dedicated BFF.
4.5 A/B Testing and Feature Toggling via the BFF
One of the most powerful "hidden" features of a BFF is its ability to act as a Traffic Experimentation Engine. Instead of the frontend deciding which version of a feature to show, the BFF makes that decision before the data ever reaches the client.
4.5.a Server-Side Experimentation
In a traditional setup, A/B testing logic often lives in the frontend. This leads to "flickering" (where the UI changes after the page loads) and heavy client-side scripts. With a BFF:
- Unified Logic: The BFF checks the user's ID or session against an Experimentation Service. It then decides whether to send "Version A" or "Version B" of a UI component's data.
- Zero-Flicker UX: Because the data is already "decided" when it arrives at the frontend, the UI renders the correct version immediately.
- Cross-Platform Consistency: If you are testing a new discount algorithm, the BFF ensures that the user sees the exact same test version whether they are on the Web, iOS, or Android app.
4.5.b Targeted Feature Rollouts (Canary Releases)
The BFF can also control Feature Flags. For example, if you are launching a new "Buy Now Pay Later" feature for only 10% of users in India:
- The Frontend asks for the "Checkout Configuration."
- The BFF checks the user's location and segment.
- If the user qualifies, the BFF includes the
isPayLaterEnabled: trueflag and the relevant metadata in the JSON response. - If not, the field is omitted, and the frontend simply doesn't render that button.