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

第 17 課:BFF 模式 — 前端的後端

BFF 模式:每個前端都有自己的後端。為什麼BFF適合微前端。為 Web 與行動裝置設計 BFF。 BFF 聚合層。避免 BFF 成為龐然大物。

🏗️ 建築 — 第 17 課 第 17 課:BFF 模式 — 前端的後端

微服務與微前端系統設計-從基礎到生產

第 6 部分:API 閘道和 BFF 層

亞洲開發網

簡介

前端後端 (BFF) 是一種為每個前端客戶端放置單獨的後端層的模式。 BFF 聚合來自多個微服務的數據,將其轉換為適合特定前端的格式。

BFF 模式-為每個客戶端提供單獨的後端和前端


1. 為什麼你需要一個最好的朋友?

1.1 沒有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 與最好的朋友

✅ 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 架構

┌─────────────┐  ┌─────────────┐  ┌─────────────┐
│  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設計原則

3.1 每種前端類型一個 BFF

前端最好的朋友優化為
網路(桌面)網路好友資料全,UI豐富
手機行動好友緊湊的數據、頻寬
管理面板管理員好友CRUD 操作
第三方公共 API(非 BFF)穩定,版本化

3.2 BFF 職責

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 實作 (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 與 API 網關

特點API網關最好的朋友
目的跨領域關注點特定於前端的聚合
邏輯路由、驗證、速率限制資料轉換
每位顧客為所有人合一每種前端類型一個
維護者平台團隊前端團隊

在實踐中,同時使用:

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

總結

  • BFF = 每個前端類型的單獨後端
  • 聚合資料、轉換格式、降低前端複雜性
  • 無狀態,不含業務邏輯
  • 每種前端類型(Web、行動、管理員)一名 BFF
  • 通常與API網關結合使用

下一篇文章: 第 18 課:API 閘道 — Kong、APISIX 與 Envoy