Chuyển đến nội dung chính

Lesson 17: BFF Pattern — Backend for Frontend

BFF Pattern: each frontend has its own backend. Why BFF is suitable for Micro Frontend. Design BFF for Web vs Mobile. BFF aggregation layer. Avoid BFF becoming monolith.

🏗️ Architecture — Lesson 17 Lesson 17: BFF Pattern — Backend for Frontend

Microservices & Micro Frontend system design — From basics to Production

Part 6: API Gateway & BFF Layer

xdev.asia

Introduction

Backend for Frontend (BFF) is a pattern that places a separate backend layer for each frontend client. BFF aggregates data from multiple microservices, transforming it into a format suitable for the specific frontend.

BFF Pattern — Separate Backend for Frontend for each client


1. Why do you need a BFF?

1.1 The problem of not having a BFF

❌ Mỗi MFE gọi trực tiếp nhiều microservices:

Product MFE ──► Product Service
            ──► Review Service
            ──► Inventory Service
            ──► Pricing Service

→ 4 API calls cho 1 product page
→ Frontend phải aggregate data
→ Over-fetching (mỗi API trả về nhiều hơn cần)
→ Latency: waterfall requests

1.2 With BFF

✅ BFF aggregates cho frontend:

Product MFE ──► Web BFF ──► Product Service
                        ──► Review Service
                        ──► Inventory Service

→ 1 API call cho 1 product page
→ BFF aggregate và transform data
→ Frontend nhận đúng data cần
→ Parallel calls tại BFF layer

2. BFF Architecture

┌─────────────┐  ┌─────────────┐  ┌─────────────┐
│  Web App    │  │ Mobile App  │  │  Admin App  │
│  (MFE)     │  │  (React     │  │  (MFE)      │
│            │  │   Native)   │  │             │
└──────┬──────┘  └──────┬──────┘  └──────┬──────┘
       │                │                │
       ▼                ▼                ▼
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│   Web BFF    │ │  Mobile BFF  │ │  Admin BFF   │
│  (Node.js)   │ │  (Node.js)   │ │  (Node.js)   │
│  Full data   │ │  Compact data│ │  All CRUD    │
└──────┬───────┘ └──────┬───────┘ └──────┬───────┘
       │                │                │
       └────────────────┼────────────────┘
                        ▼
              ┌─────────────────┐
              │  Microservices  │
              │  (gRPC / REST)  │
              └─────────────────┘

3. BFF Design Principles

3.1 One BFF per Frontend Type

FrontendBFFOptimized for
Web (Desktop)Web BFFFull data, rich UI
MobileMobile BFFCompact data, bandwidth
Admin PanelAdmin BFFCRUD operations
Third-partyPublic API (not BFF)Stable, versioned

3.2 BFF Responsibilities

BFF SHOULD:
✅ Aggregate data từ multiple services
✅ Transform data cho frontend format
✅ Handle authentication (validate tokens)
✅ Caching (Redis) cho frequently accessed data
✅ Rate limiting per client

BFF SHOULD NOT:
❌ Contain business logic (belongs to services)
❌ Have its own database (stateless!)
❌ Become a "smart proxy" monolith
❌ Be shared across different frontends

4. BFF Implementation (Node.js/Fastify)

// Web BFF - Product Page Aggregation
app.get('/api/bff/product/:id', async (req, reply) => {
  const { id } = req.params;
  
  // Parallel calls to microservices
  const [product, reviews, inventory] = await Promise.all([
    productService.getProduct(id),
    reviewService.getReviews(id, { limit: 5 }),
    inventoryService.getStock(id),
  ]);
  
  // Transform for web frontend
  return {
    ...product,
    rating: reviews.averageRating,
    topReviews: reviews.items.slice(0, 3),
    inStock: inventory.quantity > 0,
    stockLevel: inventory.quantity > 10 ? 'high' : 'low',
  };
});

5. BFF vs API Gateway

FeaturesAPI GatewayBFF
PurposeCross-cutting concernsFrontend-specific aggregation
LogicRouting, auth, rate limitData transformation
Per clientOne for allOne per frontend type
Maintained byPlatform teamFrontend team

In practice, use both:

Frontend → API Gateway → BFF → Microservices
           (routing,      (aggregation,
            auth,          transformation)
            rate limit)

Summary

  • BFF = separate backend for each frontend type
  • Aggregates data, transforms format, reduces frontend complexity
  • Stateless, does not contain business logic
  • One BFF per frontend type (Web, Mobile, Admin)
  • Often combined with API Gateway

Next article: Lesson 18: API Gateway — Kong, APISIX & Envoy