跳到正文
DEV Community· Emiliano Allende·· 10 天前AI 評分38

構建適用於正式環境的後端:從模組化工作流程到 FastAPI、Clean Architecture 與 CQRS

Building a Production-Ready Backend: From Modular Workflows to FastAPI, Clean Architecture, and CQRS

AI 導讀

這套後端設計從解耦的低程式碼工作流程逐步轉向 Python,結合 FastAPI、Clean Architecture、CQRS 和 Supabase(PostgreSQL),以支援系統擴展及維護。架構要求依賴指向內層,並以 Pydantic 嚴格驗證資料、分離 DTO,以及透過 domain ports 避免業務邏輯直接依賴資料庫用戶端。

正文

Emiliano Allende

How an evolutionary architectural approach—moving from decoupled low-code workflows to a robust Python backend—ensures long-term scalability and maintainability.

As growing applications scale, combining routing logic, database queries, and business rules inside a single monolithic file or massive workflow becomes unsustainable. Scaling out requires a deliberate architectural shift: separating concerns so that systems remain maintainable, testable, and ready for future technology transitions.

This article explores how to design a robust backend using FastAPI, Clean Architecture, and CQRS, leveraging Supabase (PostgreSQL) and drawing from lessons learned in modular automation design.

1. The Evolutionary Path: Why Modularity Matters

Before scaling into a heavy backend, systems often start as modular, decoupled blocks (such as independent automation flows handling specific tasks). This approach relies on three foundational pillars:

  • Scalability & Separation of Concerns: Splitting functionality ensures that no single execution handler becomes a massive bottleneck consuming unnecessary resources. Each component handles a single, well-defined responsibility.
  • Maintainability: When an issue arises, isolated modules make it straightforward to trace the exact source of failure.
  • Frictionless Technology Transition: When migrating core logic from low-code tools to a native code stack like Python (FastAPI), having a pre-existing modular structure makes translating functions clean, incremental, and highly systematic.

2. The Layered Architecture: Inward Dependencies

Following the core principle of Clean Architecture, dependencies must always point inward. The business logic remains completely agnostic of the framework (FastAPI) or the database driver (Supabase/PostgreSQL).

A clean directory structure enforces this boundary:

app/
├── api/                   # Frameworks & Drivers (FastAPI routers & middlewares)
├── application/           # Use cases / Application orchestration (CQRS Commands & Queries)
├── domain/                # Enterprise & Business Rules (Pure core, ports, value objects)
├── infrastructure/        # External adapters (Supabase, Brevo, OpenRouter integrations)
├── agents/                # Structured LLM orchestration agents
└── shared/                # Cross-cutting concerns (Result types, logging, config)

Strict Data Validation with Pydantic

To prevent silent data coercion and guarantee type safety across boundaries:

  • Strict Frontiers: API request/response schemas inherit from BaseModel configured with model_config = ConfigDict(strict=True) (and extra="forbid" on critical payloads) to reject unexpected properties or invalid types.
  • DTO Separation: HTTP request/response models reside in api/{module}/schemas.py, while Application DTOs handle data transfer between handlers and the domain, decoupling external JSON contracts from internal logic.
  • Zero-Any Policy: The codebase enforces strict typing (supported by mypy --strict), eliminating untyped dictionaries in favor of explicitly bounded structures.

3. Implementing CQRS and Decoupling the Database

Separating read operations (Queries) from state mutations (Commands) keeps the application lightweight, testable, and maintainable.

A. Dependency Inversion via Domain Ports (domain/ports)

To prevent domain logic from coupling directly to Supabase client libraries, the system defines abstract interfaces using Python's typing.Protocol:

class ClientPort(Protocol):
    async def get_by_id(self, client_id: str) -> Client | None: ...
    async def save(self, client: Client) -> None: ...
    async def list_active(self) -> list[Client]: ...

來源:DEV Community · dev.to