architecture-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseArchitecture Patterns
架构模式
Overview
概述
Architecture exists to support functionality. Every architectural decision should trace back to a functionality requirement.
Core principle: Design architecture FROM functionality, not TO functionality.
架构的存在是为了支撑功能。每一个架构决策都应追溯到功能需求。
核心原则: 从功能出发设计架构,而非为了功能设计架构。
Focus Areas (Reference Pattern)
重点领域(参考模式)
- RESTful API design with proper versioning and error handling
- Service boundary definition and inter-service communication
- Database schema design (normalization, indexes, sharding)
- Caching strategies and performance optimization
- Basic security patterns (auth, rate limiting)
- 带版本控制和错误处理的RESTful API设计
- 服务边界定义与服务间通信
- 数据库 schema 设计(规范化、索引、分片)
- 缓存策略与性能优化
- 基础安全模式(认证、限流)
The Iron Law
铁律
NO ARCHITECTURE DESIGN BEFORE FUNCTIONALITY FLOWS ARE MAPPEDIf you haven't documented user flows, admin flows, and system flows, you cannot design architecture.
NO ARCHITECTURE DESIGN BEFORE FUNCTIONALITY FLOWS ARE MAPPED如果尚未记录用户流程、管理员流程和系统流程,就无法进行架构设计。
Intake Routing
需求路由
First, determine what kind of architectural work is needed:
| Request Type | Route To |
|---|---|
| "Design API endpoints" | API Design section |
| "Plan system architecture" | Full Architecture Design |
| "Design data models" | Data Model section |
| "Plan integrations" | Integration Patterns section |
| "Make decisions" | Decision Framework section |
首先,确定所需的架构工作类型:
| 请求类型 | 路由至 |
|---|---|
| "设计API端点" | API设计板块 |
| "规划系统架构" | 完整架构设计 |
| "设计数据模型" | 数据模型板块 |
| "规划集成方案" | 集成模式板块 |
| "制定决策" | 决策框架板块 |
Universal Questions (Answer First)
通用问题(需先回答)
ALWAYS answer before designing:
- What functionality are we building? - User stories, not technical features
- Who are the actors? - Users, admins, external systems
- What are the user flows? - Step-by-step user actions
- What are the system flows? - Internal processing steps
- What integrations exist? - External dependencies
- What are the constraints? - Performance, security, compliance
- What observability is needed? - Logging, metrics, monitoring, alerting
设计前必须先回答以下问题:
- 我们要构建什么功能? - 用户故事,而非技术特性
- 参与者是谁? - 用户、管理员、外部系统
- 用户流程是什么? - 分步的用户操作流程
- 系统流程是什么? - 内部处理步骤
- 存在哪些集成依赖? - 外部依赖项
- 有哪些约束条件? - 性能、安全、合规要求
- 需要哪些可观测性能力? - 日志、指标、监控、告警
Functionality-First Design Process
功能优先的设计流程
Phase 1: Map Functionality Flows
阶段1:梳理功能流程
Before any architecture:
User Flow (example):
1. User opens upload page
2. User selects file
3. System validates file type/size
4. System uploads to storage
5. System shows success message
Admin Flow (example):
1. Admin opens dashboard
2. Admin views all uploads
3. Admin can delete uploads
4. System logs admin action
System Flow (example):
1. Request received at API
2. Auth middleware validates token
3. Service processes request
4. Database stores data
5. Response returned在任何架构设计之前:
用户流程(示例):
1. 用户打开上传页面
2. 用户选择文件
3. 系统验证文件类型/大小
4. 系统将文件上传至存储服务
5. 系统显示成功提示
管理员流程(示例):
1. 管理员打开控制台
2. 管理员查看所有上传记录
3. 管理员可删除上传记录
4. 系统记录管理员操作
系统流程(示例):
1. API接收到请求
2. 认证中间件验证令牌
3. 服务处理请求
4. 数据库存储数据
5. 返回响应Phase 2: Map to Architecture
阶段2:映射到架构
Each flow maps to components:
| Flow Step | Architecture Component |
|---|---|
| User opens page | Frontend route + component |
| User submits data | API endpoint |
| System validates | Validation service |
| System processes | Business logic service |
| System stores | Database + repository |
| System integrates | External client/adapter |
每个流程步骤对应到架构组件:
| 流程步骤 | 架构组件 |
|---|---|
| 用户打开页面 | 前端路由 + 组件 |
| 用户提交数据 | API端点 |
| 系统验证 | 验证服务 |
| 系统处理 | 业务逻辑服务 |
| 系统存储 | 数据库 + 数据访问层 |
| 系统集成 | 外部客户端/适配器 |
Phase 3: Design Components
阶段3:组件设计
For each component, define:
- Purpose: What functionality it supports
- Inputs: What data it receives
- Outputs: What data it returns
- Dependencies: What it needs
- Error handling: What can fail
针对每个组件,需定义:
- 用途:支撑哪些功能
- 输入:接收哪些数据
- 输出:返回哪些数据
- 依赖项:需要哪些其他组件
- 错误处理:可能出现哪些故障及处理方式
Architecture Views
架构视图
System Context (C4 Level 1)
系统上下文(C4 第1层)
┌─────────────────────────────────────────────┐
│ SYSTEM │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ Web │ │ API │ │Database │ │
│ │ App │──│ Service │──│ │ │
│ └─────────┘ └─────────┘ └─────────┘ │
└─────────────────────────────────────────────┘
│ │ │
┌──┴──┐ ┌──┴──┐ ┌──┴──┐
│User │ │Admin│ │ Ext │
└─────┘ └─────┘ └─────┘┌─────────────────────────────────────────────┐
│ SYSTEM │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ Web │ │ API │ │Database │ │
│ │ App │──│ Service │──│ │ │
│ └─────────┘ └─────────┘ └─────────┘ │
└─────────────────────────────────────────────┘
│ │ │
┌──┴──┐ ┌──┴──┐ ┌──┴──┐
│User │ │Admin│ │ Ext │
└─────┘ └─────┘ └─────┘Container View (C4 Level 2)
容器视图(C4 第2层)
- Web App: React/Vue/Angular frontend
- API Service: REST/GraphQL backend
- Database: PostgreSQL/MongoDB/etc
- Cache: Redis/Memcached
- Queue: RabbitMQ/SQS for async
- Web App:React/Vue/Angular 前端
- API Service:REST/GraphQL 后端
- Database:PostgreSQL/MongoDB等
- Cache:Redis/Memcached
- Queue:RabbitMQ/SQS(用于异步处理)
Component View (C4 Level 3)
组件视图(C4 第3层)
- Controllers: Handle HTTP requests
- Services: Business logic
- Repositories: Data access
- Clients: External integrations
- Models: Data structures
- Controllers:处理HTTP请求
- Services:业务逻辑实现
- Repositories:数据访问操作
- Clients:外部集成客户端
- Models:数据结构定义
LSP-Powered Architecture Analysis
基于LSP的架构分析
Use LSP to map actual code dependencies:
| Architecture Task | LSP Tool | Output |
|---|---|---|
| Map component dependencies | | What each component uses |
| Find all consumers of a service | | Impact analysis |
| Verify interface implementations | | All implementers |
| Trace data flow | Chain | Full flow map |
Mapping Actual Architecture:
1. localSearchCode("ServiceName") → find entry points
2. lspCallHierarchy(outgoing) → map dependencies
3. For each dependency: repeat step 2
4. Build dependency graph from resultsUse LSP BEFORE drawing architecture diagrams - verify assumptions with code.
CRITICAL: Always get lineHint from localSearchCode first. Never guess line numbers.
使用LSP映射实际代码依赖:
| 架构任务 | LSP工具 | 输出结果 |
|---|---|---|
| 映射组件依赖 | | 每个组件的依赖项 |
| 查找服务的所有调用方 | | 影响范围分析 |
| 验证接口实现 | | 所有实现类 |
| 追踪数据流 | 链式调用 | 完整数据流映射 |
映射实际架构的步骤:
1. localSearchCode("ServiceName") → 找到入口点
2. lspCallHierarchy(outgoing) → 映射依赖关系
3. 对每个依赖项:重复步骤2
4. 根据结果构建依赖关系图绘制架构图之前务必使用LSP——用代码验证假设。
关键: 始终先从localSearchCode获取lineHint。切勿猜测行号。
API Design (Functionality-Aligned)
(功能对齐的)API设计
Map user flows to endpoints:
User Flow: Upload file
→ POST /api/files
Request: { file: binary, metadata: {...} }
Response: { id: string, url: string }
Errors: 400 (invalid), 413 (too large), 500 (storage failed)
User Flow: View file
→ GET /api/files/:id
Response: { id, url, metadata, createdAt }
Errors: 404 (not found), 403 (not authorized)
Admin Flow: Delete file
→ DELETE /api/files/:id
Response: { success: true }
Errors: 404, 403API Design Checklist:
- Each endpoint maps to a user/admin flow
- Request schema matches flow inputs
- Response schema matches flow outputs
- Errors cover all failure modes
- Auth/authz requirements documented
将用户流程映射到API端点:
用户流程:上传文件
→ POST /api/files
请求:{ file: binary, metadata: {...} }
响应:{ id: string, url: string }
错误:400(无效请求), 413(文件过大), 500(存储失败)
用户流程:查看文件
→ GET /api/files/:id
响应:{ id, url, metadata, createdAt }
错误:404(未找到), 403(无权限)
管理员流程:删除文件
→ DELETE /api/files/:id
响应:{ success: true }
错误:404, 403API设计检查清单:
- 每个端点都对应一个用户/管理员流程
- 请求 schema 匹配流程输入
- 响应 schema 匹配流程输出
- 错误覆盖所有可能的故障场景
- 已记录认证/授权要求
Integration Patterns
集成模式
Map integration requirements to patterns:
| Requirement | Pattern |
|---|---|
| Flaky external service | Retry with exponential backoff |
| Slow external service | Circuit breaker + timeout |
| Async processing needed | Message queue |
| Real-time updates needed | WebSocket/SSE |
| Data sync needed | Event sourcing |
For each integration:
markdown
undefined将集成需求映射到对应模式:
| 需求 | 模式 |
|---|---|
| 不稳定的外部服务 | 指数退避重试 |
| 响应缓慢的外部服务 | 断路器 + 超时 |
| 需要异步处理 | 消息队列 |
| 需要实时更新 | WebSocket/SSE |
| 需要数据同步 | 事件溯源 |
针对每个集成,需包含:
markdown
undefined[Integration Name]
[集成名称]
Functionality: What user flow depends on this?
Pattern: [Retry/Circuit breaker/Queue/etc]
Error handling: What happens when it fails?
Fallback: What's the degraded experience?
undefined功能:哪些用户流程依赖此集成?
模式:[重试/断路器/队列等]
错误处理:失败时如何处理?
降级方案:降级后的体验是什么?
undefinedObservability Design
可观测性设计
For each component, define:
| Aspect | Questions |
|---|---|
| Logging | What events? What level? Structured format? |
| Metrics | What to measure? Counters, gauges, histograms? |
| Alerts | What thresholds? Who gets notified? |
| Tracing | Span boundaries? Correlation IDs? |
Minimum observability:
- Request/response logging at boundaries
- Error rates and latencies
- Health check endpoint
- Correlation ID propagation
针对每个组件,需定义:
| 维度 | 需明确的问题 |
|---|---|
| 日志 | 需要记录哪些事件?日志级别?是否采用结构化格式? |
| 指标 | 需要衡量哪些指标?计数器、仪表盘、直方图? |
| 告警 | 阈值是多少?通知对象是谁? |
| 链路追踪 | 跨度边界?关联ID? |
最低可观测性要求:
- 边界处的请求/响应日志
- 错误率与延迟指标
- 健康检查端点
- 关联ID传递
Decision Framework
决策框架
For each architectural decision:
markdown
undefined针对每个架构决策,需包含:
markdown
undefinedDecision: [Title]
决策:[标题]
Context: What functionality requirement drives this?
Options:
- [Option A] - [Brief description]
- [Option B] - [Brief description]
- [Option C] - [Brief description]
Trade-offs:
| Criterion | Option A | Option B | Option C |
|---|---|---|---|
| Performance | Good | Better | Best |
| Complexity | Low | Medium | High |
| Cost | Low | Medium | High |
Decision: [Option chosen]
Rationale: [Why this option best supports functionality]
undefined背景:是什么功能需求驱动了这个决策?
选项:
- [选项A] - [简要描述]
- [选项B] - [简要描述]
- [选项C] - [简要描述]
权衡:
| 评估标准 | 选项A | 选项B | 选项C |
|---|---|---|---|
| 性能 | 良好 | 较好 | 最佳 |
| 复杂度 | 低 | 中 | 高 |
| 成本 | 低 | 中 | 高 |
决策:[所选选项]
理由:[为何该选项最能支持功能需求]
undefinedRed Flags - STOP and Redesign
危险信号——立即停止并重新设计
If you find yourself:
- Designing architecture before mapping flows
- Adding components without clear functionality
- Choosing patterns because "it's best practice"
- Over-engineering for hypothetical scale
- Ignoring existing architecture patterns
- Making decisions without documenting trade-offs
STOP. Go back to functionality flows.
如果你发现自己出现以下情况:
- 在梳理流程前就设计架构
- 添加没有明确功能对应关系的组件
- 只因“是最佳实践”就选择某种模式
- 为假设的规模过度设计
- 忽略已有的架构模式
- 未记录权衡就做出决策
立即停止。回到功能流程梳理环节。
Keep It Simple (Reference Pattern)
保持简洁(参考模式)
Approach for backend architecture:
- Start with clear service boundaries
- Design APIs contract-first
- Consider data consistency requirements
- Plan for horizontal scaling from day one
- Keep it simple - avoid premature optimization
Architecture Output Checklist:
- API endpoint definitions with example requests/responses
- Service architecture diagram (mermaid or ASCII)
- Database schema with key relationships
- Technology recommendations with brief rationale
- Potential bottlenecks and scaling considerations
Always provide concrete examples. Focus on practical implementation over theory.
后端架构方法:
- 从清晰的服务边界开始
- 采用契约优先的方式设计API
- 考虑数据一致性要求
- 从第一天就规划水平扩展
- 保持简洁——避免过早优化
架构输出检查清单:
- 带示例请求/响应的API端点定义
- 服务架构图(mermaid或ASCII格式)
- 带关键关系的数据库schema
- 带简要理由的技术选型建议
- 潜在瓶颈与扩展考量
始终提供具体示例。聚焦实际实现而非理论。
Rationalization Prevention
避免合理化借口
| Excuse | Reality |
|---|---|
| "This pattern is industry standard" | Does it support THIS functionality? |
| "We might need it later" | YAGNI. Design for now. |
| "Microservices are better" | For this functionality? Justify it. |
| "Everyone uses this" | That's not a trade-off analysis. |
| "It's more flexible" | Flexibility without need = complexity. |
| 借口 | 实际情况 |
|---|---|
| “这个模式是行业标准” | 它是否支持当前的功能需求? |
| “我们以后可能需要” | YAGNI(你不会需要它)。为当下设计即可。 |
| “微服务更好” | 对当前功能而言是否必要?请给出理由。 |
| “大家都在用这个” | 这不是权衡分析。 |
| “它更灵活” | 无需求的灵活性等于复杂度。 |
Output Format
输出格式
markdown
undefinedmarkdown
undefinedArchitecture Design: [Feature/System Name]
架构设计:[功能/系统名称]
Functionality Summary
功能概述
[What this architecture supports - trace to user value]
[该架构支持的内容——关联到用户价值]
Flows Mapped
已梳理的流程
User Flows
用户流程
- [Flow 1 steps]
- [Flow 2 steps]
- [流程1步骤]
- [流程2步骤]
System Flows
系统流程
- [Flow 1 steps]
- [Flow 2 steps]
- [流程1步骤]
- [流程2步骤]
Architecture
架构
System Context
系统上下文
[Diagram or description of actors and system boundaries]
[参与者与系统边界的图或描述]
Components
组件
| Component | Purpose (Functionality) | Dependencies |
|---|---|---|
| [Name] | [What flow it supports] | [What it needs] |
| 组件 | 用途(功能) | 依赖项 |
|---|---|---|
| [名称] | [支持哪些流程] | [所需依赖] |
API Endpoints
API端点
| Endpoint | Flow | Request | Response |
|---|---|---|---|
| POST /api/x | User uploads | {...} | {...} |
| 端点 | 对应流程 | 请求 | 响应 |
|---|---|---|---|
| POST /api/x | 用户上传 | {...} | {...} |
Key Decisions
关键决策
Decision 1: [Title]
决策1:[标题]
- Context: [Functionality driver]
- Options: [List]
- Trade-offs: [Table]
- Decision: [Choice]
- Rationale: [Why]
- 背景:[驱动决策的功能需求]
- 选项:[列表]
- 权衡:[表格]
- 决策:[所选选项]
- 理由:[原因]
Implementation Roadmap
实施路线图
Critical (Must have for core flow)
关键(核心流程必备)
- [Component/feature]
- [组件/功能]
Important (Completes flows)
重要(完善流程)
- [Component/feature]
- [组件/功能]
Enhancement (Improves experience)
增强(提升体验)
- [Component/feature]
undefined- [组件/功能]
undefinedFinal Check
最终检查
Before completing architecture design:
- All user flows mapped
- All system flows mapped
- Each component traces to functionality
- Each API endpoint traces to flow
- Decisions documented with trade-offs
- Implementation roadmap prioritized
完成架构设计前,请确认:
- 所有用户流程已梳理
- 所有系统流程已梳理
- 每个组件都能追溯到对应功能
- 每个API端点都能追溯到对应流程
- 决策已记录并包含权衡分析
- 实施路线图已按优先级排序