architect

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Architecture Design

架构设计

Design system architecture and make strategic technical decisions.
设计系统架构并制定战略性技术决策。

Core Principle

核心原则

Good architecture enables change while maintaining simplicity.
优秀的架构能在保持简洁性的同时支持变更。

Name

名称

han-core:architect - Design system architecture and high-level technical strategy
han-core:architect - 设计系统架构与高级技术策略

Synopsis

概要

/architect [arguments]
/architect [arguments]

Architecture vs Planning

架构设计 vs 技术规划

Architecture Design (this skill):
  • Strategic: "How should the system be structured?"
  • Component interactions and boundaries
  • Technology and pattern choices
  • Long-term implications
  • System-level decisions
Technical Planning:
  • Tactical: "How do I implement feature X?"
  • Specific implementation tasks
  • Execution details
  • Short-term focus
Use /architect when:
  • Designing new systems or subsystems
  • Significant system change (new subsystem, major refactor)
  • Affects multiple components or teams
  • Major refactors affecting multiple components
  • Technology selection decisions
  • Defining system boundaries and interfaces
  • Long-term technical strategy needed
  • Need to evaluate multiple approaches
  • Decisions have broad impact
Use /plan when:
  • Implementing within existing architecture
  • Implementing specific feature within existing architecture
  • Tactical execution planning
  • Breaking down known work
  • Architecture is already decided
  • Task sequencing and execution
架构设计(本技能):
  • 战略性:「系统应如何架构?」
  • 组件交互与边界
  • 技术与模式选择
  • 长期影响
  • 系统级决策
技术规划:
  • 战术性:「我该如何实现功能X?」
  • 具体的实现任务
  • 执行细节
  • 短期聚焦
何时使用/architect:
  • 设计新系统或子系统
  • 重大系统变更(新增子系统、大规模重构)
  • 影响多个组件或团队
  • 影响多组件的大规模重构
  • 技术选型决策
  • 定义系统边界与接口
  • 需要长期技术策略
  • 需要评估多种方案
  • 决策具有广泛影响
何时使用/plan:
  • 在现有架构内进行实现
  • 在现有架构内实现特定功能
  • 战术性执行规划
  • 拆解已知工作任务
  • 架构已确定
  • 任务排序与执行

Architecture Process

架构设计流程

1. Understand Context

1. 理解上下文

Business context:
  • What problem are we solving?
  • Who are the users?
  • What are the business goals?
  • What are the success metrics?
Technical context:
  • What exists today?
  • What constraints exist?
  • What must we integrate with?
  • What scale must we support?
Team context:
  • What's our expertise?
  • What can we maintain?
  • What's our velocity?
业务上下文:
  • 我们要解决什么问题?
  • 用户群体是谁?
  • 业务目标是什么?
  • 成功指标有哪些?
技术上下文:
  • 当前已有哪些系统?
  • 存在哪些约束?
  • 必须与哪些系统集成?
  • 需要支持多大的规模?
团队上下文:
  • 我们的技术专长是什么?
  • 我们能维护什么样的系统?
  • 团队的交付速度如何?

2. Gather Requirements

2. 收集需求

Functional requirements:
  • What must the system do?
  • What are the features?
  • What are the user scenarios?
Non-functional requirements:
  • Performance: Response time, throughput
  • Scalability: Expected load, growth
  • Availability: Uptime requirements
  • Security: Compliance, data protection
  • Maintainability: Team size, skills
  • Cost: Budget constraints
Example:
markdown
undefined
功能需求:
  • 系统必须实现哪些功能?
  • 有哪些特性?
  • 用户场景有哪些?
非功能需求:
  • 性能:响应时间、吞吐量
  • 可扩展性:预期负载、增长规模
  • 可用性:上线时间要求
  • 安全性:合规性、数据保护
  • 可维护性:团队规模、技能水平
  • 成本:预算限制
示例:
markdown
undefined

Requirements

需求

Functional

功能需求

  • Users can search products by name/category
  • Users can add items to cart
  • Users can checkout and pay
  • 用户可按名称/类别搜索产品
  • 用户可将商品加入购物车
  • 用户可完成结账与支付

Non-Functional

非功能需求

  • Search response time < 200ms (p95)
  • Support 10,000 concurrent users
  • 99.9% uptime
  • PCI DSS compliant for payments
  • Team of 5 developers can maintain
undefined
  • 搜索响应时间 < 200ms(p95)
  • 支持10,000并发用户
  • 99.9% 上线率
  • 支付流程符合PCI DSS合规要求
  • 5人开发团队可维护
undefined

3. Identify Constraints

3. 识别约束

Technical constraints:
  • Must use existing authentication system
  • Must integrate with legacy inventory system
  • Database must be PostgreSQL (existing infrastructure)
Business constraints:
  • Budget for infrastructure
  • Must support EU data residency
Team constraints:
  • Team experienced in Python, less in Go
  • No DevOps specialist on team
  • Remote team across timezones
技术约束:
  • 必须使用现有认证系统
  • 必须与遗留库存系统集成
  • 数据库必须为PostgreSQL(现有基础设施)
业务约束:
  • 基础设施预算限制
  • 必须支持欧盟数据驻留要求
团队约束:
  • 团队精通Python,对Go经验较少
  • 团队无DevOps专家
  • 跨时区远程团队

4. Consider Alternatives

4. 评估备选方案

Never design in a vacuum - consider options:
Example: Data storage choice
Option 1: PostgreSQL
  • Pros: Team knows it, ACID guarantees, rich query support
  • Cons: Vertical scaling limits, setup complexity
Option 2: MongoDB
  • Pros: Flexible schema, horizontal scaling
  • Cons: Team unfamiliar, eventual consistency
Option 3: DynamoDB
  • Pros: Fully managed, auto-scaling
  • Cons: Vendor lock-in, query limitations, cost at scale
Decision: PostgreSQL
  • Team expertise outweighs scaling concerns
  • Can re-evaluate if scale becomes issue
  • Faster initial development
切勿闭门造车——多考量不同选项:
示例:数据存储选型
方案1:PostgreSQL
  • 优点:团队熟悉、ACID保证、丰富的查询支持
  • 缺点:垂直扩展受限、部署复杂度高
方案2:MongoDB
  • 优点:灵活的 schema、水平扩展能力
  • 缺点:团队不熟悉、最终一致性问题
方案3:DynamoDB
  • 优点:全托管、自动扩展
  • 缺点:厂商锁定、查询限制、大规模场景下成本高
决策:PostgreSQL
  • 团队专业能力的优势超过了扩展顾虑
  • 若规模成为问题可重新评估
  • 初始开发速度更快

5. Design System Structure

5. 设计系统结构

Define components and their responsibilities:
┌─────────────────────────────────────────────┐
│             Client Apps                      │
│  (Web, iOS, Android)                         │
└────────────────┬────────────────────────────┘
┌─────────────────────────────────────────────┐
│          API Gateway / Load Balancer         │
└────────────────┬────────────────────────────┘
        ┌────────┴────────┐
        ▼                 ▼
┌───────────────┐  ┌───────────────┐
│   Auth        │  │   Core API     │
│   Service     │  │   Service      │
└───────┬───────┘  └───────┬───────┘
        │                  │
        │         ┌────────┴────────┐
        │         ▼                 ▼
        │  ┌──────────────┐  ┌──────────────┐
        │  │  PostgreSQL  │  │   Redis      │
        │  │  (Primary)   │  │   (Cache)    │
        │  └──────────────┘  └──────────────┘
┌───────────────┐
│   User DB     │
└───────────────┘
Component descriptions:
markdown
undefined
定义组件及其职责:
┌─────────────────────────────────────────────┐
│             Client Apps                      │
│  (Web, iOS, Android)                         │
└────────────────┬────────────────────────────┘
┌─────────────────────────────────────────────┐
│          API Gateway / Load Balancer         │
└────────────────┬────────────────────────────┘
        ┌────────┴────────┐
        ▼                 ▼
┌───────────────┐  ┌───────────────┐
│   Auth        │  │   Core API     │
│   Service     │  │   Service      │
└───────┬───────┘  └───────┬───────┘
        │                  │
        │         ┌────────┴────────┐
        │         ▼                 ▼
        │  ┌──────────────┐  ┌──────────────┐
        │  │  PostgreSQL  │  │   Redis      │
        │  │  (Primary)   │  │   (Cache)    │
        │  └──────────────┘  └──────────────┘
┌───────────────┐
│   User DB     │
└───────────────┘
组件说明:
markdown
undefined

Components

组件

API Gateway

API网关

Responsibility: Route requests, rate limiting, authentication Technology: Nginx Dependencies: Auth Service, Core API Service Scale: 2-3 instances behind load balancer
职责: 请求路由、限流、认证 技术栈: Nginx 依赖: 认证服务、核心API服务 规模: 负载均衡后部署2-3个实例

Auth Service

认证服务

Responsibility: User authentication, session management, JWT issuing Technology: Python (Flask), PostgreSQL API: REST Scale: Stateless, 2-N instances
职责: 用户认证、会话管理、JWT签发 技术栈: Python (Flask)、PostgreSQL API类型: REST 规模: 无状态,可部署2-N个实例

Core API Service

核心API服务

Responsibility: Business logic, data access, external integrations Technology: Python (FastAPI), PostgreSQL, Redis API: REST Scale: Stateless, 2-N instances
职责: 业务逻辑、数据访问、外部集成 技术栈: Python (FastAPI)、PostgreSQL、Redis API类型: REST 规模: 无状态,可部署2-N个实例

PostgreSQL

PostgreSQL

Responsibility: Primary data store Scale: Primary with read replica
职责: 主数据存储 规模: 主节点搭配只读副本

Redis

Redis

Responsibility: Session storage, caching, rate limiting Scale: Cluster mode (3 nodes)
undefined
职责: 会话存储、缓存、限流 规模: 集群模式(3节点)
undefined

6. Define Interfaces

6. 定义接口

API contracts:
markdown
undefined
API契约:
markdown
undefined

API Design

API设计

POST /api/auth/login

POST /api/auth/login

Purpose: Authenticate user, issue JWT
Request:
json
{
  "email": "user@example.com",
  "password": "secure_password"
}
Response (200):
json
{
  "token": "eyJ...",
  "user": {
    "id": "123",
    "email": "user@example.com",
    "name": "John Doe"
  }
}
Errors:
  • 400: Invalid request
  • 401: Invalid credentials
  • 429: Rate limit exceeded
undefined
用途: 用户认证,签发JWT
请求:
json
{
  "email": "user@example.com",
  "password": "secure_password"
}
响应(200):
json
{
  "token": "eyJ...",
  "user": {
    "id": "123",
    "email": "user@example.com",
    "name": "John Doe"
  }
}
错误:
  • 400:无效请求
  • 401:凭证无效
  • 429:超出限流阈值
undefined

7. Plan for Failure

7. 故障预案设计

What can go wrong?
  • Database unavailable
  • External API down
  • Network partition
  • High load
  • Data corruption
Mitigation strategies:
  • Retry with exponential backoff
  • Circuit breakers for external services
  • Graceful degradation
  • Health checks and monitoring
  • Database backups
Example:
markdown
undefined
可能出现哪些问题?
  • 数据库不可用
  • 外部API宕机
  • 网络分区
  • 高负载
  • 数据损坏
缓解策略:
  • 指数退避重试
  • 外部服务断路器
  • 优雅降级
  • 健康检查与监控
  • 数据库备份
示例:
markdown
undefined

Failure Scenarios

故障场景

Database Unavailable

数据库不可用

Impact: Cannot read/write data Mitigation:
  • Read replica failover (automated)
  • Circuit breaker after 3 failures
  • Cache serves stale data for 5 minutes
  • User sees degraded experience message Recovery: Manual failover to replica, fix primary
影响: 无法读写数据 缓解方案:
  • 只读副本自动故障转移
  • 连续3次失败后触发断路器
  • 缓存提供5分钟过期的 stale 数据
  • 向用户展示降级体验提示 恢复方案: 手动将副本切换为主节点,修复原主节点

External Payment API Down

外部支付API宕机

Impact: Cannot process payments Mitigation:
  • Retry 3 times with exponential backoff
  • Queue payments for later processing
  • User notified of delay
  • Alert on-call engineer Recovery: Process queued payments once API recovers
undefined
影响: 无法处理支付 缓解方案:
  • 指数退避重试3次
  • 将支付请求加入队列待后续处理
  • 通知用户支付延迟
  • 触发值班工程师告警 恢复方案: API恢复后处理队列中的支付请求
undefined

8. Document Decisions

8. 记录决策

Architecture Decision Record (ADR):
markdown
undefined
架构决策记录(ADR):
markdown
undefined

ADR-001: Use PostgreSQL for Primary Database

ADR-001:使用PostgreSQL作为主数据库

Status: Accepted Date: 2024-01-15 Deciders: Tech Lead, Backend Team
状态: 已通过 日期: 2024-01-15 决策人: 技术负责人、后端团队

Context

背景

We need to choose a primary database for user data, products, and orders.
Requirements:
  • Strong consistency (ACID)
  • Complex queries (joins, aggregations)
  • < 200ms query time for 90% of queries
  • Support 100k users initially
我们需要为用户数据、产品与订单选择主数据库。
需求:
  • 强一致性(ACID)
  • 复杂查询(关联、聚合)
  • 90%的查询响应时间 < 200ms
  • 初始支持10万用户

Decision

决策

Use PostgreSQL as primary database.
采用PostgreSQL作为主数据库。

Alternatives Considered

评估的备选方案

MongoDB

MongoDB

  • Pros: Flexible schema, horizontal scaling
  • Cons: Team unfamiliar, eventual consistency issues
  • Why not: Team expertise more valuable than flexibility
  • 优点: 灵活schema、水平扩展
  • 缺点: 团队不熟悉、最终一致性问题
  • 未选原因: 团队专业能力比灵活性更重要

DynamoDB

DynamoDB

  • Pros: Managed service, auto-scaling
  • Cons: Vendor lock-in, limited query capability, cost
  • Why not: Query limitations would hurt development velocity
  • 优点: 托管服务、自动扩展
  • 缺点: 厂商锁定、查询能力有限、成本高
  • 未选原因: 查询限制会影响开发效率

MySQL

MySQL

  • Pros: Similar to PostgreSQL, team knows it
  • Cons: Less feature-rich than PostgreSQL
  • Why not: PostgreSQL offers JSON support, better full-text search
  • 优点: 与PostgreSQL类似、团队熟悉
  • 缺点: 功能丰富度不如PostgreSQL
  • 未选原因: PostgreSQL支持JSON、全文搜索能力更强

Consequences

后果

Positive:
  • Team can be productive immediately
  • Strong consistency guarantees
  • Rich query capabilities
  • JSON support for flexible data
Negative:
  • Vertical scaling limits (mitigated: can add read replicas)
  • More complex than managed services (mitigated: use RDS)
  • Higher operational overhead
Trade-offs:
  • Chose familiarity over horizontal scaling
  • Chose rich queries over eventual consistency
  • Can re-evaluate if scale requirements change
积极影响:
  • 团队可立即进入高效开发状态
  • 强一致性保证
  • 丰富的查询能力
  • JSON支持灵活数据存储
消极影响:
  • 垂直扩展受限(缓解方案:可添加只读副本)
  • 比托管服务复杂度更高(缓解方案:使用RDS)
  • 运维 overhead 更高
权衡:
  • 选择了熟悉度而非水平扩展能力
  • 选择了丰富查询能力而非最终一致性
  • 若规模需求变化可重新评估

Validation

验证

  • Team confirmed expertise in PostgreSQL
  • Load testing shows meets performance requirements
  • Cost analysis shows acceptable for first year
undefined
  • 团队确认具备PostgreSQL专业能力
  • 负载测试显示满足性能要求
  • 成本分析显示首年预算可接受
undefined

Architecture Document Structure

架构文档结构

markdown
undefined
markdown
undefined

Architecture Design: [System/Feature Name]

架构设计:[系统/功能名称]

Context

背景

Problem Statement

问题陈述

[What business problem are we solving?]
[我们要解决什么业务问题?]

Goals

目标

[What are we trying to achieve?]
[我们要达成什么?]

Non-Goals

非目标

[What are we explicitly NOT trying to achieve?]
[明确我们不打算解决的问题?]

Requirements

需求

Functional:
  • [Requirement 1]
  • [Requirement 2]
Non-Functional:
  • Performance: [e.g., < 200ms response time]
  • Scalability: [e.g., handle 10k concurrent users]
  • Security: [e.g., PCI compliance]
  • Maintainability: [e.g., easy to modify]
功能需求:
  • [需求1]
  • [需求2]
非功能需求:
  • 性能:[例如,< 200ms响应时间]
  • 可扩展性:[例如,支持1万并发用户]
  • 安全性:[例如,PCI合规]
  • 可维护性:[例如,易于修改]

Constraints

约束

[Technical, time, resource, or business constraints]
[技术、时间、资源或业务约束]

Current Architecture

当前架构

[What exists today? What needs to change?]
[现有系统是什么样的?需要变更哪些部分?]

Proposed Architecture

拟议架构

High-Level Design

高层设计

[Diagram or description of system components]

┌─────────────┐     ┌─────────────┐     ┌──────────────┐
│   Client    │────▶│   API       │────▶│  Database    │
└─────────────┘     └─────────────┘     └──────────────┘
                    ┌─────────────┐
                    │  Cache      │
                    └─────────────┘
[系统组件的示意图或说明]

┌─────────────┐     ┌─────────────┐     ┌──────────────┐
│   Client    │────▶│   API       │────▶│  Database    │
└─────────────┘     └─────────────┘     └──────────────┘
                    ┌─────────────┐
                    │  Cache      │
                    └─────────────┘

Components

组件

Component A

组件A

Responsibility: [What it does] Interface: [How others interact with it] Dependencies: [What it depends on] Technology: [Implementation stack]
职责: [它的功能是什么] 接口: [其他组件如何与它交互] 依赖: [它依赖哪些组件] 技术栈: [实现技术栈]

Component B

组件B

[Similar structure...]
[类似结构...]

Data Flow

数据流

[How data moves through the system]
[数据如何在系统中流转]

API Design

API设计

[Key endpoints, schemas, contracts]
[关键端点、 schema、契约]

Data Model

数据模型

[Database schema, key entities]
[数据库 schema、核心实体]

Security Model

安全模型

[Authentication, authorization, data protection]
[认证、授权、数据保护]

Alternative Approaches Considered

评估的备选方案

Alternative 1: [Approach name]

方案1:[方案名称]

Pros:
  • [Advantage 1]
  • [Advantage 2]
Cons:
  • [Disadvantage 1]
  • [Disadvantage 2]
Why not chosen: [Reasoning]
优点:
  • [优势1]
  • [优势2]
缺点:
  • [劣势1]
  • [劣势2]
未选原因: [理由]

Alternative 2: [Another approach]

方案2:[另一个方案]

[Similar structure...]
[类似结构...]

Decision Rationale

决策依据

Why This Architecture?

为何选择该架构?

[Explain the key decisions and trade-offs]
[解释关键决策与权衡]

Trade-offs Accepted

接受的权衡

[What we gave up for what benefits]
[我们为了获得哪些收益而放弃了什么]

Assumptions

假设

[What we're assuming to be true]
[我们假设哪些条件成立]

Implementation Strategy

实施策略

Phase 1: [Foundation]

阶段1:[基础建设]

[What to build first]
[首先要构建什么]

Phase 2: [Core Features]

阶段2:[核心功能]

[Next phase]
[下一阶段]

Phase 3: [Enhancement]

阶段3:[优化增强]

[Final phase]
[最终阶段]

Migration Strategy

迁移策略

[If replacing existing system, how to transition?]
[如果替换现有系统,如何过渡?]

Risks & Mitigation

风险与缓解

RiskImpactProbabilityMitigation
[Risk 1]HighMedium[How to mitigate]
[Risk 2]MediumLow[How to mitigate]
风险影响概率缓解方案
[风险1][缓解措施]
[风险2][缓解措施]

Testing Strategy

测试策略

[How will we validate this architecture?]
[我们如何验证该架构?]

Monitoring & Observability

监控与可观测性

[How will we know if it's working?]
[我们如何知晓系统是否正常运行?]

Success Metrics

成功指标

[How will we measure success?]
[我们如何衡量成功?]

Open Questions

待解决问题

[What still needs to be resolved?]
[还有哪些问题需要明确?]

References

参考资料

[Links to research, related docs, RFCs]
undefined
[研究链接、相关文档、RFCs]
undefined

Architecture Principles

架构原则

1. Simplicity

1. 简洁性

Start simple, add complexity only when needed.
BAD: Microservices from day 1 with 20 services
GOOD: Start with monolith, split when needed
Apply YAGNI: You Aren't Gonna Need It
  • Don't build for hypothetical future
  • Add when actually needed
  • Simpler is easier to maintain
从简单开始,仅在必要时增加复杂度。
错误做法:第一天就搭建20个服务的微服务架构
正确做法:从单体应用开始,需要时再拆分
应用YAGNI原则:你不会需要它
  • 不要为假设的未来需求构建功能
  • 实际需要时再添加
  • 更简单的系统更易于维护

2. Separation of Concerns

2. 关注点分离

Each component has one clear responsibility.
GOOD:
- Auth Service: Authentication only
- User Service: User profile management
- Order Service: Order processing

BAD:
- God Service: Does everything
Apply SOLID principles:
  • Single Responsibility
  • Open/Closed
  • Liskov Substitution
  • Interface Segregation
  • Dependency Inversion
每个组件有且仅有一个明确的职责。
正确做法:
- 认证服务:仅负责认证
- 用户服务:仅负责用户资料管理
- 订单服务:仅负责订单处理

错误做法:
- 上帝服务:包揽所有功能
应用SOLID原则:
  • 单一职责
  • 开闭原则
  • 里氏替换
  • 接口隔离
  • 依赖反转

3. Loose Coupling

3. 松耦合

Components depend on interfaces, not implementations.
typescript
// BAD: Tight coupling
class OrderService {
  constructor(private db: PostgresDatabase) {}
}

// GOOD: Loose coupling
class OrderService {
  constructor(private db: Database) {}  // Interface
}
Benefits:
  • Easier to test (mock interface)
  • Easier to swap implementations
  • Components can evolve independently
组件依赖于接口而非具体实现。
typescript
// 错误:紧耦合
class OrderService {
  constructor(private db: PostgresDatabase) {}
}

// 正确:松耦合
class OrderService {
  constructor(private db: Database) {}  // 接口
}
优势:
  • 更易于测试(可模拟接口)
  • 更易于替换实现
  • 组件可独立演进

4. High Cohesion

4. 高内聚

Related functionality stays together.
GOOD:
user/
  - create_user.ts
  - update_user.ts
  - delete_user.ts
  - user_repository.ts

BAD:
create/
  - create_user.ts
  - create_order.ts
update/
  - update_user.ts
  - update_order.ts
相关功能应集中在一起。
正确做法:
user/
  - create_user.ts
  - update_user.ts
  - delete_user.ts
  - user_repository.ts

错误做法:
create/
  - create_user.ts
  - create_order.ts
update/
  - update_user.ts
  - update_order.ts

5. Explicit Over Implicit

5. 显式优于隐式

Make dependencies and contracts clear.
typescript
// BAD: Implicit dependency
function processOrder(orderId: string) {
  const db = global.database  // Where does this come from?
  // ...
}

// GOOD: Explicit dependency
function processOrder(
  orderId: string,
  db: Database,
  logger: Logger
) {
  // Dependencies are clear
}
明确依赖与契约。
typescript
// 错误:隐式依赖
function processOrder(orderId: string) {
  const db = global.database  // 这个来自哪里?
  // ...
}

// 正确:显式依赖
function processOrder(
  orderId: string,
  db: Database,
  logger: Logger
) {
  // 依赖关系清晰
}

6. Fail Fast

6. 快速失败

Detect and report errors early.
typescript
// BAD: Silent failure
function divide(a: number, b: number) {
  if (b === 0) return 0  // Wrong!
  return a / b
}

// GOOD: Fail fast
function divide(a: number, b: number) {
  if (b === 0) {
    throw new Error('Division by zero')
  }
  return a / b
}
尽早检测并报告错误。
typescript
// 错误:静默失败
function divide(a: number, b: number) {
  if (b === 0) return 0  // 错误!
  return a / b
}

// 正确:快速失败
function divide(a: number, b: number) {
  if (b === 0) {
    throw new Error('Division by zero')
  }
  return a / b
}

7. Design for Testability

7. 可测试性设计

Make it easy to test.
typescript
// BAD: Hard to test
class OrderService {
  processOrder(orderId: string) {
    const db = new PostgresDatabase()  // Can't mock
    const api = new PaymentAPI()       // Can't mock
    // ...
  }
}

// GOOD: Easy to test
class OrderService {
  constructor(
    private db: Database,      // Can inject mock
    private api: PaymentAPI    // Can inject mock
  ) {}

  processOrder(orderId: string) {
    // ...
  }
}
让系统易于测试。
typescript
// 错误:难以测试
class OrderService {
  processOrder(orderId: string) {
    const db = new PostgresDatabase()  // 无法模拟
    const api = new PaymentAPI()       // 无法模拟
    // ...
  }
}

// 正确:易于测试
class OrderService {
  constructor(
    private db: Database,      // 可注入模拟实现
    private api: PaymentAPI    // 可注入模拟实现
  ) {}

  processOrder(orderId: string) {
    // ...
  }
}

Common Architecture Patterns

常见架构模式

Layered Architecture

分层架构

┌─────────────────────┐
│  Presentation       │ (UI, API controllers)
├─────────────────────┤
│  Business Logic     │ (Domain, services)
├─────────────────────┤
│  Data Access        │ (Repositories, ORMs)
├─────────────────────┤
│  Database           │ (Storage)
└─────────────────────┘
When to use: Simple to moderate complexity
┌─────────────────────┐
│  表现层             │ (UI、API控制器)
├─────────────────────┤
│  业务逻辑层         │ (领域模型、服务)
├─────────────────────┤
│  数据访问层         │ (仓库、ORM)
├─────────────────────┤
│  数据库层           │ (存储)
└─────────────────────┘
适用场景: 简单到中等复杂度的系统

Hexagonal Architecture (Ports & Adapters)

六边形架构(端口与适配器)

        ┌───────────────────────┐
        │   External Systems    │
        │  (UI, DB, APIs)       │
        └──────────┬────────────┘
        ┌──────────▼────────────┐
        │      Adapters         │ (Implementation)
        │  (REST, PostgreSQL)   │
        └──────────┬────────────┘
        ┌──────────▼────────────┐
        │       Ports           │ (Interfaces)
        │  (IUserRepo, IAuth)   │
        └──────────┬────────────┘
        ┌──────────▼────────────┐
        │    Core Domain        │ (Business logic)
        │    (Pure logic)       │
        └───────────────────────┘
When to use: Want to isolate business logic, multiple frontends
        ┌───────────────────────┐
        │   外部系统            │
        │  (UI、DB、APIs)       │
        └──────────┬────────────┘
        ┌──────────▼────────────┐
        │      适配器           │ (实现)
        │  (REST、PostgreSQL)   │
        └──────────┬────────────┘
        ┌──────────▼────────────┐
        │       端口             │ (接口)
        │  (IUserRepo、IAuth)   │
        └──────────┬────────────┘
        ┌──────────▼────────────┐
        │    核心领域            │ (业务逻辑)
        │    (纯逻辑)            │
        └───────────────────────┘
适用场景: 希望隔离业务逻辑、多前端场景

Microservices

微服务

┌─────────┐  ┌─────────┐  ┌─────────┐
│  User   │  │  Order  │  │ Payment │
│ Service │  │ Service │  │ Service │
└────┬────┘  └────┬────┘  └────┬────┘
     │            │            │
     └────────────┴────────────┘
          ┌───────▼────────┐
          │  Message Bus   │
          │  (Event-driven)│
          └────────────────┘
When to use: Large team, need independent deploy, clear boundaries
Avoid when: Small team, unclear boundaries, early stage
┌─────────┐  ┌─────────┐  ┌─────────┐
│  用户服务│  │  订单服务│  │  支付服务│
└────┬────┘  └────┬────┘  └────┬────┘
     │            │            │
     └────────────┴────────────┘
          ┌───────▼────────┐
          │  消息总线       │
          │  (事件驱动)      │
          └────────────────┘
适用场景: 大型团队、需要独立部署、边界清晰的系统
避免场景: 小型团队、边界模糊、早期项目

Event-Driven Architecture

事件驱动架构

┌─────────┐       ┌─────────────┐       ┌─────────┐
│Producer │──────▶│ Event Bus   │──────▶│Consumer │
└─────────┘       └─────────────┘       └─────────┘
When to use: Async processing, decoupled systems, audit trails
┌─────────┐       ┌─────────────┐       ┌─────────┐
│生产者    │──────▶│ 事件总线     │──────▶│消费者    │
└─────────┘       └─────────────┘       └─────────┘
适用场景: 异步处理、解耦系统、审计追踪

Architectural Patterns to Consider

可参考的架构模式

System Patterns:
  • Layered architecture
  • Microservices vs monolith
  • Event-driven architecture
  • CQRS (Command Query Responsibility Segregation)
  • Hexagonal architecture
Data Patterns:
  • Database per service
  • Shared database
  • Event sourcing
  • CQRS
  • Cache-aside
Integration Patterns:
  • API Gateway
  • Service mesh
  • Message queue
  • Pub/sub
  • GraphQL federation
系统模式:
  • 分层架构
  • 微服务 vs 单体应用
  • 事件驱动架构
  • CQRS(命令查询职责分离)
  • 六边形架构
数据模式:
  • 服务专属数据库
  • 共享数据库
  • 事件溯源
  • CQRS
  • 缓存旁路
集成模式:
  • API网关
  • 服务网格
  • 消息队列
  • 发布/订阅
  • GraphQL联邦

Anti-Patterns

反模式

Premature Optimization

过早优化

Don't optimize for scale you don't have.
BAD: Build microservices for 100 users
GOOD: Start with monolith, split when needed
不要为当前不需要的规模做优化。
错误做法:为100个用户搭建微服务
正确做法:从单体应用开始,需要时再拆分

Resume-Driven Architecture

简历驱动架构

Don't choose technology to pad resume.
BAD: "I want to learn Kubernetes, let's use it"
GOOD: "Kubernetes fits our scale needs"
不要为了填充简历而选择技术。
错误做法:「我想学习Kubernetes,所以我们用它」
正确做法:「Kubernetes符合我们的规模需求」

Distributed Monolith

分布式单体

Microservices that are tightly coupled.
BAD: Service A can't deploy without Service B
GOOD: Services are independently deployable
紧耦合的微服务。
错误做法:服务A部署必须依赖服务B
正确做法:服务可独立部署

Big Ball of Mud

大泥球

No structure, everything depends on everything.
BAD: Any code can call any other code
GOOD: Clear layers and boundaries
无结构,所有组件互相依赖。
错误做法:任何代码都能调用其他代码
正确做法:清晰的分层与边界

Analysis Paralysis

分析瘫痪

Over-analyzing, never shipping.
BAD: Spend months on perfect architecture
GOOD: Design enough to start, iterate
过度分析,迟迟不交付。
错误做法:花费数月追求完美架构
正确做法:设计到足够启动的程度,再迭代优化

Architecture Review Checklist

架构评审检查清单

  • Business goals clearly understood
  • Functional requirements documented
  • Non-functional requirements defined
  • Constraints identified
  • Multiple alternatives considered
  • Trade-offs explicitly stated
  • Component responsibilities clear
  • Interfaces well-defined
  • Data flow documented
  • Failure scenarios planned for
  • Security model defined
  • Scalability addressed
  • Testability designed in
  • Decisions documented (ADRs)
  • Implementation phases outlined
  • Team can implement and maintain
  • Success metrics defined
  • 明确理解业务目标
  • 记录功能需求
  • 定义非功能需求
  • 识别约束
  • 考量多种备选方案
  • 明确权衡
  • 组件职责清晰
  • 接口定义完善
  • 记录数据流
  • 规划故障场景
  • 定义安全模型
  • 解决可扩展性问题
  • 设计可测试性
  • 记录决策(ADR)
  • 规划实施阶段
  • 团队可实现与维护
  • 定义成功指标

Examples

示例场景

When the user says:
  • "Design the architecture for our multi-tenant system"
  • "How should we structure our microservices?"
  • "Plan the technical approach for real-time notifications"
  • "Design the data model for our marketplace"
  • "Create architecture for migrating from monolith to services"
当用户提出以下需求时:
  • 「为我们的多租户系统设计架构」
  • 「我们的微服务应该如何架构?」
  • 「规划实时通知的技术方案」
  • 「为我们的市场平台设计数据模型」
  • 「设计从单体应用到微服务的迁移架构」

Integration with Other Skills

与其他技能的集成

  • Apply solid-principles - Guide component design
  • Apply simplicity-principles - KISS, YAGNI
  • Apply orthogonality-principle - Independent components
  • Apply structural-design-principles - Composition patterns
  • Use technical-planning - For implementation after design
  • 应用 solid-principles - 指导组件设计
  • 应用 simplicity-principles - KISS、YAGNI
  • 应用 orthogonality-principle - 独立组件
  • 应用 structural-design-principles - 组合模式
  • 使用 technical-planning - 架构确定后的实施规划

Notes

注意事项

  • Use TaskCreate to track architecture design steps
  • Apply all relevant design principle skills
  • Create diagrams (ASCII art or reference drawing tools)
  • Architecture evolves - document decisions and changes
  • Consider using /plan for detailed implementation after architecture is approved
  • Archive decisions as ADRs for future reference
  • 使用TaskCreate追踪架构设计步骤
  • 应用所有相关的设计原则技能
  • 创建示意图(ASCII图或参考绘图工具)
  • 架构是演进的——记录决策与变更
  • 架构获批后,可使用/plan进行详细实施规划
  • 将决策归档为ADR,供未来参考

Remember

谨记

  1. Simplicity first - Start simple, add complexity when needed
  2. Document decisions - Future you will thank you
  3. Consider alternatives - Never the first idea only
  4. State trade-offs - Every decision has consequences
  5. Design for change - Systems evolve
The best architecture is the one that's simple enough to ship and flexible enough to evolve.
  1. 简洁优先 - 从简单开始,必要时再增加复杂度
  2. 记录决策 - 未来的你会感谢现在的自己
  3. 考量备选方案 - 不要只看第一个想法
  4. 明确权衡 - 每个决策都有代价
  5. 为变更设计 - 系统会演进
最好的架构是足够简洁可交付,同时足够灵活可演进的架构。