簡介
前端後端 (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網關結合使用