B07 · 後端專案共用規範 詳細 ROADMAP

計畫文件,不會被 Quartz 渲染。 回主 roadmap → backend/ROADMAP.md


章節目標

這是整套後端系列的「實戰核心章」。每個後端團隊都會慢慢累積一套「共用規範」——日誌格式 / 錯誤處理 / Repository / 中介層 / 事件匯流排 / 健康檢查等。寫成框架內建或公司內部 package 或 shared module。Proto(proto/infra/micro-service/src/shared/)就是完整的一套,本章以 proto shared 為主要範例,展開每個模組的為什麼、什麼場景要用、怎麼設計、常見踩坑

注意:這章跨 framework——就算換 NestJS / Spring Boot / Gin,這些 pattern 還是適用,只是實作不同。


🌱 基本介紹

#主題SlugStage大綱
01什麼是後端共用規範01-what-is-backend-convention🌱Shared module / internal package / in-house framework 的光譜;proto shared 作為完整範例導覽

❓ 為什麼需要

#主題SlugStage大綱
02為什麼每個專案都該有共用規範02-why-convention-matters🌱3 個 service 寫 3 種 log 格式 → 監控一團亂;每個 endpoint 各自處理錯誤 → 客戶端抓狂;onboarding 新人要學 5 套風格
03為什麼 shared module 比 copy-paste 好03-why-shared-module🌱單點修復 bug、版本控制、接口明確;避免 DRY 過頭(有些規範適合散、有些適合集中)
04為什麼共用規範應該跨 framework04-why-framework-agnostic🌱換 framework 成本太高 → 把業務邏輯留在 shared(接口抽象),framework 只是 HTTP 入口
05為什麼不直接用現成 framework 提供的05-why-not-just-use-framework-built-in🌱FastAPI / Spring / NestJS 有提供的能力 vs 團隊實際需求的距離;什麼時候該加自己的 layer

🕰️ 演進

#主題SlugStage大綱
06企業後端共用規範演進06-convention-evolution🌱早期 utility.py → 內部 npm/pip package → monorepo shared → OSS 化(例如 Netflix Hystrix、Uber Cadence)
07Proto Shared 的演進07-proto-shared-journey🌱從 copy-paste 到抽 shared、第一版到第 N 版的改動;每次壓測暴露的新需求

🧠 知識型

Proto shared 目錄結構一致:core/(認證 / 快取 / DB / 日誌 / tracing)、messaging/(事件匯流排)、middleware/(中介層)、repositories/services/schemas/models/exceptions/utils/。每小節對應 proto 實際模組。

F07-A core/ — 核心服務層

#主題SlugStageProto 模組
08結構化 Log 設計08-structured-logging🌱core/logging.py — structlog 統一 app + uvicorn + SQLAlchemy 的 JSON 格式
08-2Log 四層設計(Request / Response / Error / Query)08-2-four-layer-logging🌱對應 backend/express/generic-log 實戰;每層記什麼欄位、為什麼 Query log 要獨立、怎麼串 trace_id
09快取抽象層(CacheService)09-cache-service-abstraction🌱core/cache.py — Redis + enabled toggle + 命名 convention
10DB Session 工廠10-db-session-factory🌱core/database.pycreate_engine_and_session() + async pool
11認證核心(JWT RS256)11-auth-core🌱core/auth.py — 非對稱簽名 / 驗證、token 生命週期
12分散式追蹤整合(Tracing)12-tracing-integration🌱core/tracing.py — OpenTelemetry 入口、context propagation
12-2Enum / Constants 集中管理12-2-enums-constants🌱core/enums/constants.py — 常數集中位置、跨服務共用、避免 magic string
12-3Error Code 設計12-3-error-codes🌱core/enums/error_codes.py — 錯誤碼階層、機器可讀、跟 i18n / frontend 整合

F07-B messaging/ — 事件驅動基礎

#主題SlugStageProto 模組
13EventBus 模式13-eventbus-pattern🌱messaging/bus.py — 抽象層,底層可換 RabbitMQ / Kafka
14Event 結構與版本管理14-event-schema-versioning🌱messaging/event.py — Event 基底類別 / schema / versioning 策略
15Publisher 模式15-event-publisher🌱messaging/publisher.py — retry、outbox pattern、tx 整合
16Consumer 模式16-event-consumer🌱messaging/consumer.py — ack / nack / DLQ / idempotency

F07-C middleware/ — 中介層合集(11 個模組)

#主題SlugStageProto 模組
17Request ID / Correlation ID17-request-id🌱middleware/request_id.py — 貫穿 log / trace,debug 神器
18Access Log Middleware18-access-log🌱middleware/access_log.py — method / path / status / duration / trace_id
19Body Size Limit19-body-limit🌱middleware/body_limit.py — DoS 防禦、跟 Kong / Nginx limit 配合
20Content-Type 驗證20-content-type-check🌱middleware/content_type_check.py — 拒絕錯誤 content-type、避免 MIME confusion
21Idempotency Key21-idempotency-middleware🌱middleware/idempotency.py — 重複 POST 不重複扣款、金流必備
22Maintenance Mode22-maintenance-mode🌱middleware/maintenance.py — readonly / 503 切換、rolling deploy 配合
23Request Sanitize23-request-sanitize🌱middleware/request_sanitize.py — XSS / HTML entity 清洗;何時該 middleware 做、何時該 schema 做
24Security Headers24-security-headers🌱middleware/security_headers.py — CSP / HSTS / X-Frame-Options / Referrer-Policy
25Token Blacklist25-token-blacklist🌱middleware/token_blacklist.py — 短期 JWT 撤銷、跟 Redis 配合
26Trusted Proxy26-trusted-proxy🌱middleware/trusted_proxy.py — X-Forwarded-For 信任邊界、真 IP 取得
27Webhook Signature27-webhook-signature🌱middleware/webhook_signature.py — HMAC 驗簽、Stripe / GitHub webhook pattern

F07-D repositories/ / services/ / schemas/ / models/

#主題SlugStageProto 模組
28BaseRepository 泛型 CRUD28-base-repository-pattern🌱repositories/ — generic + soft-delete filtering + pagination
28-2Base Controller / Response Formatter28-2-base-controller🌱對應 backend/express/base-controller;統一 API 回傳格式({data, meta, error});成功 / 失敗 template;FastAPI 的 response_model vs Express 的 base class
28-3Repository + Cache 整合 Pattern28-3-repository-cache-integration🌱Cache-Aside 在 Repository 層實作;失效策略(write-through / event-driven invalidation);避免 Repository 耦合 Redis 的抽象;跟 B13 #10 patterns 連動
29Service Layer 設計29-service-layer🌱services/base.py — 商業邏輯位置、跟 Controller / Repository 的邊界
30Audit Log 系統30-audit-log🌱services/audit.py — 誰、何時、改了什麼;跟 Event-driven 配合
31Schema(Pydantic / DTO)設計31-schema-design🌱schemas/ — Request / Response / Internal 分層、不洩漏 DB 結構
32Model(ORM)設計規範32-model-conventions🌱models/ — 命名、mixin(timestamp / soft-delete)、relationship 策略

F07-E exceptions/ / utils/

#主題SlugStageProto 模組
33統一錯誤處理33-unified-error-handling🌱exceptions/ — 自訂例外階層、http status 映射、錯誤碼設計
34共用 Utils 怎麼管34-shared-utils🌱utils/ — 小工具集、DRY 陷阱(不該什麼都塞進 utils)

F07-F 健康檢查與可用性

#主題SlugStage大綱
35Liveness vs Readiness Probe35-liveness-vs-readiness🌱快速 vs dependency check、graceful shutdown 跟 readiness 的 dance、K8s probe 配置
35-2Dependency Check 實作35-2-dependency-check🌱DB / Redis / MQ 連線檢查、timeout 策略、深 vs 淺檢查
35-3Startup Probe 設計35-3-startup-probe🌱長啟動時間服務(Spring Boot / JVM JIT warmup)、跟 liveness / readiness 的分工
35-4Graceful Shutdown 完整流程35-4-graceful-shutdown-complete🌱SIGTERM → readiness 回 false → drain connections → 關 DB / MQ → 退出;跟 K8s terminationGracePeriodSeconds 配合

F07-G Request Lifecycle 完整貫穿

#主題SlugStage大綱
35-5Request Lifecycle 完整路徑35-5-request-lifecycle-complete🌱一個 HTTP request 從進來到回應的完整鏈:Middleware Stack(auth / log / rate limit / correlation ID)→ Route → Validation(schema)→ Controller → Service(business logic)→ Repository → ORM / Cache → Response Formatter → Serialization → HTTP Response;全域 error handler 貫穿所有層;每層的責任邊界 + 常見越界錯誤

🔧 小實作注意事項

#主題SlugStage大綱
36從零建 shared module(Python / TS)36-build-shared-module🌱monorepo 下 shared package、internal npm / pip、版本管理策略
37把 proto shared 翻譯成 NestJS 版37-proto-shared-to-nestjs🌱驗證「跨 framework」主張;對比實作差異

💣 Anti-pattern

#主題SlugStage大綱
38共用規範 Anti-patterns38-convention-antipatterns🌱shared 變萬能垃圾桶(什麼都塞)、breaking change 沒版控、shared 讀 application config(循環依賴)、middleware 用 shared 卻不能單元測試、shared 綁死某 framework、忽視「有些規範不該共用」(例如商業邏輯)

🧰 對應檢查工具

#主題SlugStage大綱
39共用規範品質檢查39-convention-tooling🌱自動 lint 檢查(是否用對 middleware)、SBOM 檢查 shared 版本、monorepo 工具(Nx / Turborepo / pnpm workspace)

📎 補充

#主題SlugStage大綱
S01In-house Framework vs 直接用 OSS Frameworks01-inhouse-framework🌱什麼規模值得做 in-house framework、Uber / Netflix / Shopify 的經驗
S02監控 shared module 使用度s02-monitor-shared-usage🌱知道哪個模組沒人用(可刪)、哪個被濫用(需拆)
S03從 Monolith shared 抽成獨立 packages03-extract-shared-package🌱拆服務前先抽 shared;package 跨 repo 用

章節進度統計

  • 知識主題:44 + 3 補充 = 47 項
  • 🌿 growing:0
  • 🌱 seed:47

跨系列連結

  • backend/framework/ B06(shared 要跨 framework)
  • backend/auth/ B10 #11 對應 Auth 核心
  • backend/queue/ B12 #13–16 對應 Messaging
  • backend/observability/ B17 #8 對應 Logging
  • backend/security/ B16 對應 Middleware security
  • backend/stress-testing/ B19(壓測驅動 shared 演進)
  • proto/infra/micro-service/src/shared/(實作原始碼參考)