architecture-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Architecture Patterns

架构模式

Consolidated architecture validation and enforcement patterns covering clean architecture, backend layer separation, project structure conventions, and test standards. Each category has individual rule files in
references/
loaded on-demand.
整合了针对整洁架构、后端分层、项目结构约定及测试标准的架构验证与规范模式。每个分类在
references/
目录下都有独立的规则文件,可按需加载。

Quick Reference

快速参考

CategoryRulesImpactWhen to Use
Clean Architecture3HIGHSOLID principles, hexagonal architecture, ports & adapters, DDD
Project Structure2HIGHFolder conventions, nesting depth, import direction, barrel files
Backend Layers3HIGHRouter/service/repository separation, DI, file naming
Test Standards3MEDIUMAAA pattern, naming conventions, coverage thresholds
Right-Sizing2HIGHArchitecture tier selection, over-engineering prevention, context-aware enforcement
Total: 13 rules across 5 categories
分类规则数量影响级别适用场景
整洁架构3SOLID原则、六边形架构、端口与适配器、DDD
项目结构2目录约定、嵌套深度、导入方向、桶文件(barrel files)
后端分层3路由/服务/仓储分离、依赖注入(DI)、文件命名
测试标准3AAA模式、命名规范、覆盖率阈值
架构规模适配2架构层级选择、过度设计预防、上下文感知型规范
总计:5个分类共13条规则

Quick Start

快速开始

python
undefined
python
undefined

Clean Architecture: Dependency Inversion via Protocol

Clean Architecture: Dependency Inversion via Protocol

class IUserRepository(Protocol): async def get_by_id(self, id: str) -> User | None: ...
class UserService: def init(self, repo: IUserRepository): self._repo = repo # Depends on abstraction, not concretion
class IUserRepository(Protocol): async def get_by_id(self, id: str) -> User | None: ...
class UserService: def init(self, repo: IUserRepository): self._repo = repo # Depends on abstraction, not concretion

FastAPI DI chain: DB -> Repository -> Service

FastAPI DI chain: DB -> Repository -> Service

def get_user_service(db: AsyncSession = Depends(get_db)) -> UserService: return UserService(PostgresUserRepository(db))
undefined
def get_user_service(db: AsyncSession = Depends(get_db)) -> UserService: return UserService(PostgresUserRepository(db))
undefined

Project Structure: Unidirectional Import Architecture

Project Structure: Unidirectional Import Architecture

shared/lib -> components -> features -> app (lowest) (highest)
shared/lib -> components -> features -> app (lowest) (highest)

Backend Layers: Strict Separation

Backend Layers: Strict Separation

Routers (HTTP) -> Services (Business Logic) -> Repositories (Data Access)
undefined
Routers (HTTP) -> Services (Business Logic) -> Repositories (Data Access)
undefined

Clean Architecture

整洁架构

SOLID principles, hexagonal architecture, ports and adapters, and DDD tactical patterns for maintainable backends.
RuleFileKey Pattern
Hexagonal Architecture
references/clean-hexagonal-ports-adapters.md
Driving/driven ports, adapter implementations, layer structure
SOLID & Dependency Rule
references/clean-solid-dependency-rule.md
Protocol-based interfaces, dependency inversion, FastAPI DI
DDD Tactical Patterns
references/clean-ddd-tactical-patterns.md
Entities, value objects, aggregate roots, domain events
基于SOLID原则、六边形架构、端口与适配器以及DDD战术模式的可维护后端架构指南。
规则文件核心模式
六边形架构
references/clean-hexagonal-ports-adapters.md
驱动/被驱动端口、适配器实现、分层结构
SOLID与依赖规则
references/clean-solid-dependency-rule.md
基于Protocol的接口、依赖倒置、FastAPI依赖注入
DDD战术模式
references/clean-ddd-tactical-patterns.md
实体、值对象、聚合根、领域事件

Key Decisions

关键决策

DecisionRecommendation
Protocol vs ABCProtocol (structural typing)
Dataclass vs PydanticDataclass for domain, Pydantic for API
Repository granularityOne per aggregate root
Transaction boundaryService layer, not repository
Event publishingCollect in aggregate, publish after commit
决策项推荐方案
Protocol vs ABCProtocol(结构类型)
Dataclass vs Pydantic领域层用Dataclass,API层用Pydantic
仓储粒度每个聚合根对应一个仓储
事务边界服务层,而非仓储层
事件发布在聚合中收集,提交后发布

Project Structure

项目结构

Feature-based organization, max nesting depth, unidirectional imports, and barrel file prevention.
RuleFileKey Pattern
Folder Structure & Nesting
references/structure-folder-conventions.md
React/Next.js and FastAPI layouts, 4-level max nesting, barrel file rules
Import Direction & Location
references/structure-import-direction.md
Unidirectional imports, cross-feature prevention, component/hook placement
基于功能的组织方式、最大嵌套深度、单向导入以及禁止桶文件的规范。
规则文件核心模式
目录结构与嵌套
references/structure-folder-conventions.md
React/Next.js和FastAPI布局、最多4层嵌套、桶文件规则
导入方向与位置
references/structure-import-direction.md
单向导入、跨功能模块禁止、组件/钩子放置规则

Blocking Rules

阻断性规则

RuleCheck
Max NestingMax 4 levels from src/ or app/
No Barrel FilesNo index.ts re-exports (tree-shaking issues)
Component LocationReact components in components/ or features/ only
Hook LocationCustom hooks in hooks/ or features/*/hooks/ only
Import DirectionUnidirectional: shared -> components -> features -> app
规则检查项
最大嵌套深度从src/或app/开始最多4层
禁止桶文件禁止index.ts重导出(存在tree-shaking问题)
组件位置React组件仅可放在components/或features/目录下
钩子位置自定义钩子仅可放在hooks/或features/*/hooks/目录下
导入方向单向导入:shared -> components -> features -> app

Backend Layers

后端分层

FastAPI Clean Architecture with router/service/repository layer separation and blocking validation.
RuleFileKey Pattern
Layer Separation
references/backend-layer-separation.md
Router/service/repository boundaries, forbidden patterns, async rules
Dependency Injection
references/backend-dependency-injection.md
Depends() chains, auth patterns, testing with DI overrides
File Naming & Exceptions
references/backend-naming-exceptions.md
Naming conventions, domain exceptions, violation detection
基于FastAPI的整洁架构,包含路由/服务/仓储分层分离及强制验证。
规则文件核心模式
分层分离
references/backend-layer-separation.md
路由/服务/仓储边界、禁止模式、异步规则
依赖注入
references/backend-dependency-injection.md
Depends()链、认证模式、依赖注入覆盖测试
文件命名与异常
references/backend-naming-exceptions.md
命名规范、领域异常、违规检测

Layer Boundaries

分层边界

LayerResponsibilityForbidden
RoutersHTTP concerns, request parsing, auth checksDatabase operations, business logic
ServicesBusiness logic, validation, orchestrationHTTPException, Request objects
RepositoriesData access, queries, persistenceHTTP concerns, business logic
层级职责禁止操作
路由层HTTP相关处理、请求解析、认证检查数据库操作、业务逻辑
服务层业务逻辑、验证、编排HTTPException、Request对象
仓储层数据访问、查询、持久化HTTP相关处理、业务逻辑

Test Standards

测试标准

Testing best practices with AAA pattern, naming conventions, isolation, and coverage thresholds.
RuleFileKey Pattern
AAA Pattern & Isolation
references/testing-aaa-isolation.md
Arrange-Act-Assert, test isolation, parameterized tests
Naming Conventions
references/testing-naming-conventions.md
Descriptive behavior-focused names for Python and TypeScript
Coverage & Location
references/testing-coverage-location.md
Coverage thresholds, fixture scopes, test file placement rules
包含AAA模式、命名规范、隔离性以及覆盖率阈值的测试最佳实践。
规则文件核心模式
AAA模式与隔离性
references/testing-aaa-isolation.md
Arrange-Act-Assert、测试隔离、参数化测试
命名规范
references/testing-naming-conventions.md
Python和TypeScript的行为描述型命名
覆盖率与位置
references/testing-coverage-location.md
覆盖率阈值、夹具作用域、测试文件放置规则

Coverage Requirements

覆盖率要求

AreaMinimumTarget
Overall80%90%
Business Logic90%100%
Critical Paths95%100%
New Code100%100%
范围最低要求目标值
整体80%90%
业务逻辑90%100%
关键路径95%100%
新代码100%100%

Right-Sizing

架构规模适配

Context-aware backend architecture enforcement. Rules adjust strictness based on project tier detected by
scope-appropriate-architecture
.
Enforcement procedure:
  1. Read project tier from
    scope-appropriate-architecture
    context (set during brainstorming/implement Step 0)
  2. If no tier set, auto-detect using signals in
    rules/right-sizing-tiers.md
  3. Apply tier-based enforcement matrix — skip rules marked OFF for detected tier
  4. Security rules are tier-independent — always enforce SQL parameterization, input validation, auth checks
RuleFileKey Pattern
Architecture Sizing Tiers
rules/right-sizing-tiers.md
Interview/MVP/production/enterprise sizing matrix, LOC estimates, detection signals
Right-Sizing Decision Guide
rules/right-sizing-decision.md
ORM, auth, error handling, testing recommendations per tier, over-engineering tax
上下文感知型后端架构规范。规则会根据
scope-appropriate-architecture
检测到的项目层级调整严格程度。
实施流程:
  1. scope-appropriate-architecture
    上下文读取项目层级(在头脑风暴/实施第0步时设置)
  2. 若未设置层级,使用
    rules/right-sizing-tiers.md
    中的信号自动检测
  3. 应用基于层级的实施矩阵 — 跳过标记为OFF的规则
  4. 安全规则与层级无关 — 始终强制SQL参数化、输入验证、认证检查
规则文件核心模式
架构规模层级
rules/right-sizing-tiers.md
面试/MVP/生产/企业级规模矩阵、代码行数估算、检测信号
规模适配决策指南
rules/right-sizing-decision.md
各层级下ORM、认证、错误处理、测试的推荐方案、过度设计成本

Tier-Based Rule Enforcement

基于层级的规则实施

RuleInterviewMVPProductionEnterprise
Layer separationOFFWARNBLOCKBLOCK
Repository patternOFFOFFWARNBLOCK
Domain exceptionsOFFOFFBLOCKBLOCK
Dependency injectionOFFWARNBLOCKBLOCK
OpenAPI documentationOFFOFFWARNBLOCK
Manual override: User can set tier explicitly to bypass auto-detection (e.g., "I want enterprise patterns for this take-home to demonstrate skill").
规则面试项目MVP生产环境企业级
分层分离关闭警告阻断阻断
仓储模式关闭关闭警告阻断
领域异常关闭关闭阻断阻断
依赖注入关闭警告阻断阻断
OpenAPI文档关闭关闭警告阻断
手动覆盖: 用户可显式设置层级以绕过自动检测(例如:“我希望这个带回家的项目使用企业级模式来展示技能”)。

Decision Flowchart

决策流程图

Is this a take-home or hackathon?
  YES --> Flat architecture. Single file or 3-5 files. Done.
  NO  -->

Is this a prototype or MVP with < 3 months runway?
  YES --> Simple layered. Routes + services + models. No abstractions.
  NO  -->

Do you have > 5 engineers or complex domain rules?
  YES --> Clean architecture with ports/adapters.
  NO  --> Layered architecture. Add abstractions only when pain appears.
Is this a take-home or hackathon?
  YES --> Flat architecture. Single file or 3-5 files. Done.
  NO  -->

Is this a prototype or MVP with < 3 months runway?
  YES --> Simple layered. Routes + services + models. No abstractions.
  NO  -->

Do you have > 5 engineers or complex domain rules?
  YES --> Clean architecture with ports/adapters.
  NO  --> Layered architecture. Add abstractions only when pain appears.

Anti-Patterns (FORBIDDEN)

反模式(禁止)

python
undefined
python
undefined

CLEAN ARCHITECTURE

CLEAN ARCHITECTURE

NEVER import infrastructure in domain layer

NEVER import infrastructure in domain layer

from app.infrastructure.database import engine # In domain layer!
from app.infrastructure.database import engine # In domain layer!

NEVER leak ORM models to API layer

NEVER leak ORM models to API layer

@router.get("/users/{id}") async def get_user(id: str, db: Session) -> UserModel: # Returns ORM model!
@router.get("/users/{id}") async def get_user(id: str, db: Session) -> UserModel: # Returns ORM model!

NEVER have domain depend on framework

NEVER have domain depend on framework

from fastapi import HTTPException class UserService: def get(self, id: str): raise HTTPException(404) # Framework in domain!
from fastapi import HTTPException class UserService: def get(self, id: str): raise HTTPException(404) # Framework in domain!

PROJECT STRUCTURE

PROJECT STRUCTURE

NEVER create files deeper than 4 levels from src/

NEVER create files deeper than 4 levels from src/

NEVER create barrel files (index.ts re-exports)

NEVER create barrel files (index.ts re-exports)

NEVER import from higher layers (features importing from app)

NEVER import from higher layers (features importing from app)

NEVER import across features (use shared/ for common code)

NEVER import across features (use shared/ for common code)

BACKEND LAYERS

BACKEND LAYERS

NEVER use database operations in routers

NEVER use database operations in routers

NEVER raise HTTPException in services

NEVER raise HTTPException in services

NEVER instantiate services without Depends()

NEVER instantiate services without Depends()

TEST STANDARDS

TEST STANDARDS

NEVER mix test files with source code

NEVER mix test files with source code

NEVER use non-descriptive test names (test1, test, works)

NEVER use non-descriptive test names (test1, test, works)

NEVER share mutable state between tests without reset

NEVER share mutable state between tests without reset

undefined
undefined

Related Skills

相关技能

  • scope-appropriate-architecture
    - Project tier detection that drives right-sizing enforcement
  • quality-gates
    - YAGNI gate uses tier context to validate complexity
  • distributed-systems
    - Distributed locking, resilience, idempotency patterns
  • api-design
    - REST API design, versioning, error handling
  • testing-patterns
    - Comprehensive testing patterns and strategies
  • python-backend
    - FastAPI, SQLAlchemy, asyncio patterns
  • database-patterns
    - Schema design, query optimization, migrations
  • scope-appropriate-architecture
    - 驱动规模适配实施的项目层级检测技能
  • quality-gates
    - YAGNI检查门使用层级上下文验证复杂度
  • distributed-systems
    - 分布式锁、弹性设计、幂等性模式
  • api-design
    - REST API设计、版本化、错误处理
  • testing-patterns
    - 全面的测试模式与策略
  • python-backend
    - FastAPI、SQLAlchemy、asyncio模式
  • database-patterns
    - schema设计、查询优化、迁移