architecture-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseArchitecture Patterns
架构模式(Architecture Patterns)
Overview
概述
Architecture patterns provide proven solutions for structuring software systems. Choosing the right architecture is crucial for scalability, maintainability, and team productivity.
架构模式为软件系统的结构化提供了经过验证的解决方案。选择合适的架构对于可扩展性、可维护性和团队生产力至关重要。
Patterns
模式
Monolithic Architecture
单体架构(Monolithic Architecture)
Description: Single deployable unit containing all application functionality.
Key Features:
- Simple deployment and development
- Shared database and memory
- Straightforward debugging
Use Cases:
- MVPs and startups
- Small teams (< 10 developers)
- Simple domain logic
Best Practices:
src/
├── modules/ # Feature-based organization
│ ├── users/
│ ├── orders/
│ └── products/
├── shared/ # Cross-cutting concerns
└── infrastructure/ # External services说明:包含所有应用功能的单一可部署单元。
核心特性:
- 简单部署与开发
- 共享数据库与内存
- 调试直观
适用场景:
- MVP与初创项目
- 小型团队(少于10名开发者)
- 简单领域逻辑
最佳实践:
src/
├── modules/ # 基于功能的组织
│ ├── users/
│ ├── orders/
│ └── products/
├── shared/ # 横切关注点
└── infrastructure/ # 外部服务Microservices Architecture
微服务架构(Microservices Architecture)
Description: Distributed system of independently deployable services.
Key Features:
- Independent deployment and scaling
- Technology diversity per service
- Fault isolation
Use Cases:
- Large teams needing autonomy
- Complex domains with clear boundaries
- High scalability requirements
Key Components:
| Component | Purpose | Tools |
|---|---|---|
| API Gateway | Entry point, routing | Kong, AWS API Gateway |
| Service Discovery | Service registration | Consul, Kubernetes DNS |
| Config Management | Centralized config | Spring Cloud Config, Consul |
| Circuit Breaker | Fault tolerance | Resilience4j, Hystrix |
Best Practices:
- Design around business capabilities
- Decentralize data management
- Design for failure
- Automate deployment
说明:由独立可部署服务组成的分布式系统。
核心特性:
- 独立部署与扩容
- 各服务可采用不同技术栈
- 故障隔离
适用场景:
- 需要自治的大型团队
- 具有清晰边界的复杂领域
- 高可扩展性需求
核心组件:
| 组件 | 用途 | 工具 |
|---|---|---|
| API Gateway | 入口点、路由 | Kong, AWS API Gateway |
| Service Discovery | 服务注册 | Consul, Kubernetes DNS |
| Config Management | 集中式配置 | Spring Cloud Config, Consul |
| Circuit Breaker | 容错 | Resilience4j, Hystrix |
最佳实践:
- 围绕业务能力设计
- 去中心化数据管理
- 为故障场景设计
- 自动化部署
Event-Driven Architecture
事件驱动架构(Event-Driven Architecture)
Description: Systems communicating through events.
Key Patterns:
| Pattern | Description | Use Case |
|---|---|---|
| Event Sourcing | Store state as events | Audit trails, temporal queries |
| CQRS | Separate read/write models | High-read workloads |
| Saga | Distributed transactions | Cross-service workflows |
Event Sourcing Example:
typescript
// Events are the source of truth
interface OrderEvent {
id: string;
type: 'OrderCreated' | 'ItemAdded' | 'OrderShipped';
timestamp: Date;
payload: unknown;
}
// Rebuild state from events
function rebuildOrder(events: OrderEvent[]): Order {
return events.reduce((order, event) => {
switch (event.type) {
case 'OrderCreated': return { ...event.payload };
case 'ItemAdded': return { ...order, items: [...order.items, event.payload] };
case 'OrderShipped': return { ...order, status: 'shipped' };
}
}, {} as Order);
}说明:通过事件进行通信的系统。
核心模式:
| 模式 | 说明 | 适用场景 |
|---|---|---|
| Event Sourcing | 将状态以事件形式存储 | 审计追踪、时态查询 |
| CQRS | 分离读写模型 | 高读负载场景 |
| Saga | 分布式事务 | 跨服务工作流 |
Event Sourcing示例:
typescript
// Events are the source of truth
interface OrderEvent {
id: string;
type: 'OrderCreated' | 'ItemAdded' | 'OrderShipped';
timestamp: Date;
payload: unknown;
}
// Rebuild state from events
function rebuildOrder(events: OrderEvent[]): Order {
return events.reduce((order, event) => {
switch (event.type) {
case 'OrderCreated': return { ...event.payload };
case 'ItemAdded': return { ...order, items: [...order.items, event.payload] };
case 'OrderShipped': return { ...order, status: 'shipped' };
}
}, {} as Order);
}Serverless Architecture
无服务器架构(Serverless Architecture)
Description: Cloud-managed execution without server management.
Key Features:
- Pay-per-execution pricing
- Auto-scaling to zero
- Reduced operational overhead
Considerations:
| Aspect | Impact |
|---|---|
| Cold Start | 100ms-2s latency on first invocation |
| Timeout | Usually 15-30 min max execution |
| State | Must use external storage |
| Vendor Lock-in | Platform-specific features |
Best Practices:
- Keep functions small and focused
- Minimize dependencies
- Use connection pooling for databases
- Implement proper error handling
说明:无需管理服务器的云托管执行架构。
核心特性:
- 按执行次数付费
- 自动缩容至零
- 降低运维开销
注意事项:
| 方面 | 影响 |
|---|---|
| Cold Start | 首次调用时延迟100ms-2s |
| Timeout | 通常最大执行时间为15-30分钟 |
| State | 必须使用外部存储 |
| Vendor Lock-in | 平台特定特性 |
最佳实践:
- 保持函数小巧且聚焦
- 最小化依赖
- 对数据库使用连接池
- 实现完善的错误处理
Clean Architecture
整洁架构(Clean Architecture)
Description: Dependency-inverted architecture with domain at center.
Layer Structure:
┌──────────────────────────────────────┐
│ Frameworks & Drivers │ ← External (DB, Web, UI)
├──────────────────────────────────────┤
│ Interface Adapters │ ← Controllers, Gateways
├──────────────────────────────────────┤
│ Application Business │ ← Use Cases
├──────────────────────────────────────┤
│ Enterprise Business │ ← Entities, Domain Rules
└──────────────────────────────────────┘Dependency Rule: Dependencies point inward. Inner layers know nothing about outer layers.
说明:以领域为核心的依赖倒置架构。
层级结构:
┌──────────────────────────────────────┐
│ Frameworks & Drivers │ ← 外部层(数据库、Web、UI)
├──────────────────────────────────────┤
│ Interface Adapters │ ← 控制器、网关
├──────────────────────────────────────┤
│ Application Business │ ← 用例
├──────────────────────────────────────┤
│ Enterprise Business │ ← 实体、领域规则
└──────────────────────────────────────┘依赖规则:依赖关系向内指向。内层对外层一无所知。
Domain-Driven Design (DDD)
领域驱动设计(Domain-Driven Design, DDD)
Description: Architecture aligned with business domain.
Strategic Patterns:
| Pattern | Purpose |
|---|---|
| Bounded Context | Clear domain boundaries |
| Context Map | Relationships between contexts |
| Ubiquitous Language | Shared vocabulary |
Tactical Patterns:
| Pattern | Purpose |
|---|---|
| Entity | Objects with identity |
| Value Object | Immutable descriptors |
| Aggregate | Consistency boundary |
| Repository | Collection-like persistence |
| Domain Event | Something that happened |
说明:与业务领域对齐的架构。
战略模式:
| 模式 | 用途 |
|---|---|
| Bounded Context | 清晰的领域边界 |
| Context Map | 上下文之间的关系 |
| Ubiquitous Language | 共享词汇表 |
战术模式:
| 模式 | 用途 |
|---|---|
| Entity | 具有标识的对象 |
| Value Object | 不可变描述符 |
| Aggregate | 一致性边界 |
| Repository | 类集合的持久化 |
| Domain Event | 已发生的事件 |
Decision Guide
决策指南
START
│
├─ Team size < 10? ──────────────────→ Monolith
│
├─ Need independent deployments? ────→ Microservices
│
├─ Audit trail required? ────────────→ Event Sourcing
│
├─ Variable/unpredictable load? ─────→ Serverless
│
├─ Complex business logic? ──────────→ Clean Architecture + DDD
│
└─ Default ──────────────────────────→ Modular MonolithSTART
│
├─ 团队规模 < 10人? ──────────────────→ Monolith
│
├─ 需要独立部署? ────→ Microservices
│
├─ 需要审计追踪? ────→ Event Sourcing
│
├─ 负载可变/不可预测? ─────→ Serverless
│
├─ 复杂业务逻辑? ──────────→ Clean Architecture + DDD
│
└─ 默认 ──────────────────────────→ Modular MonolithCommon Pitfalls
常见陷阱
1. Premature Microservices
1. 过早采用微服务
Problem: Starting with microservices for a simple application
Solution: Start monolithic, extract services when boundaries are clear
问题:为简单应用初始就采用微服务
解决方案:从单体开始,当边界清晰后再拆分服务
2. Distributed Monolith
2. 分布式单体
Problem: Microservices that must deploy together
Solution: Ensure services are truly independent with clear API contracts
问题:必须一起部署的微服务
解决方案:确保服务真正独立,具有清晰的API契约
3. Ignoring Data Boundaries
3. 忽略数据边界
Problem: Shared database across services
Solution: Each service owns its data, use events for synchronization
问题:跨服务共享数据库
解决方案:每个服务拥有自己的数据,使用事件进行同步
Hexagonal Architecture (Ports & Adapters)
六边形架构(Hexagonal Architecture, Ports & Adapters)
Description: Application core isolated from external concerns through ports (interfaces) and adapters (implementations).
Structure:
┌─────────────────────────────────────────────────────────────┐
│ Driving Adapters │
│ (REST API, CLI, GraphQL, Message Consumer) │
└──────────────────────────┬──────────────────────────────────┘
│
┌──────────────────────────▼──────────────────────────────────┐
│ Input Ports │
│ (Use Case Interfaces) │
├─────────────────────────────────────────────────────────────┤
│ │
│ APPLICATION CORE │
│ (Domain Logic, Entities) │
│ │
├─────────────────────────────────────────────────────────────┤
│ Output Ports │
│ (Repository, Gateway Interfaces) │
└──────────────────────────┬──────────────────────────────────┘
│
┌──────────────────────────▼──────────────────────────────────┐
│ Driven Adapters │
│ (Database, External APIs, Message Publisher) │
└─────────────────────────────────────────────────────────────┘TypeScript Example:
typescript
// Port (Interface)
interface OrderRepository {
save(order: Order): Promise<void>;
findById(id: string): Promise<Order | null>;
}
// Adapter (Implementation)
class PostgresOrderRepository implements OrderRepository {
constructor(private db: Database) {}
async save(order: Order): Promise<void> {
await this.db.query('INSERT INTO orders...', [order]);
}
async findById(id: string): Promise<Order | null> {
const row = await this.db.query('SELECT * FROM orders WHERE id = $1', [id]);
return row ? this.toDomain(row) : null;
}
}
// Use Case (Application Core)
class CreateOrderUseCase {
constructor(private orderRepo: OrderRepository) {} // Depends on Port, not Adapter
async execute(input: CreateOrderInput): Promise<Order> {
const order = new Order(input);
await this.orderRepo.save(order);
return order;
}
}Benefits:
- Easy to swap implementations (DB, external services)
- Highly testable (mock ports)
- Framework-agnostic domain logic
说明:通过端口(接口)和适配器(实现)将应用核心与外部关注点隔离的架构。
结构:
┌─────────────────────────────────────────────────────────────┐
│ Driving Adapters │
│ (REST API, CLI, GraphQL, Message Consumer) │
└──────────────────────────┬──────────────────────────────────┘
│
┌──────────────────────────▼──────────────────────────────────┐
│ Input Ports │
│ (Use Case Interfaces) │
├─────────────────────────────────────────────────────────────┤
│ │
│ APPLICATION CORE │
│ (Domain Logic, Entities) │
│ │
├─────────────────────────────────────────────────────────────┤
│ Output Ports │
│ (Repository, Gateway Interfaces) │
└──────────────────────────┬──────────────────────────────────┘
│
┌──────────────────────────▼──────────────────────────────────┐
│ Driven Adapters │
│ (Database, External APIs, Message Publisher) │
└─────────────────────────────────────────────────────────────┘TypeScript示例:
typescript
// Port (Interface)
interface OrderRepository {
save(order: Order): Promise<void>;
findById(id: string): Promise<Order | null>;
}
// Adapter (Implementation)
class PostgresOrderRepository implements OrderRepository {
constructor(private db: Database) {}
async save(order: Order): Promise<void> {
await this.db.query('INSERT INTO orders...', [order]);
}
async findById(id: string): Promise<Order | null> {
const row = await this.db.query('SELECT * FROM orders WHERE id = $1', [id]);
return row ? this.toDomain(row) : null;
}
}
// Use Case (Application Core)
class CreateOrderUseCase {
constructor(private orderRepo: OrderRepository) {} // Depends on Port, not Adapter
async execute(input: CreateOrderInput): Promise<Order> {
const order = new Order(input);
await this.orderRepo.save(order);
return order;
}
}优势:
- 易于替换实现(数据库、外部服务)
- 高可测试性(模拟端口)
- 领域逻辑与框架无关
Modular Monolith
模块化单体(Modular Monolith)
Description: Monolith with strict module boundaries, preparing for potential microservices extraction.
Key Features:
- Modules communicate via defined interfaces
- Each module owns its data
- Can be deployed as single unit or extracted
Structure:
src/
├── modules/
│ ├── users/
│ │ ├── api/ # Public API of module
│ │ │ └── UserService.ts
│ │ ├── internal/ # Private implementation
│ │ │ ├── UserRepository.ts
│ │ │ └── UserEntity.ts
│ │ └── index.ts # Only exports public API
│ ├── orders/
│ │ ├── api/
│ │ │ └── OrderService.ts
│ │ ├── internal/
│ │ └── index.ts
│ └── shared/ # Cross-cutting utilities
├── infrastructure/
│ ├── database/
│ ├── messaging/
│ └── http/
└── main.tsModule Communication Rules:
typescript
// ✅ Good: Use public API
import { UserService } from '@modules/users';
const user = await userService.getById(id);
// ❌ Bad: Direct access to internal
import { UserRepository } from '@modules/users/internal/UserRepository';Enforcement:
json
// eslint rules or ts-paths to prevent internal imports
{
"rules": {
"no-restricted-imports": ["error", {
"patterns": ["@modules/*/internal/*"]
}]
}
}说明:具有严格模块边界的单体架构,为未来可能的微服务拆分做准备。
核心特性:
- 模块通过定义的接口通信
- 每个模块拥有自己的数据
- 可作为单一单元部署或拆分
结构:
src/
├── modules/
│ ├── users/
│ │ ├── api/ # 模块的公共API
│ │ │ └── UserService.ts
│ │ ├── internal/ # 私有实现
│ │ │ ├── UserRepository.ts
│ │ │ └── UserEntity.ts
│ │ └── index.ts # 仅导出公共API
│ ├── orders/
│ │ ├── api/
│ │ │ └── OrderService.ts
│ │ ├── internal/
│ │ └── index.ts
│ └── shared/ # 横切工具
├── infrastructure/
│ ├── database/
│ ├── messaging/
│ └── http/
└── main.ts模块通信规则:
typescript
// ✅ 推荐:使用公共API
import { UserService } from '@modules/users';
const user = await userService.getById(id);
// ❌ 不推荐:直接访问内部实现
import { UserRepository } from '@modules/users/internal/UserRepository';强制执行方式:
json
// eslint规则或ts-paths防止内部导入
{
"rules": {
"no-restricted-imports": ["error", {
"patterns": ["@modules/*/internal/*"]
}]
}
}Strangler Fig Pattern
绞杀者模式(Strangler Fig Pattern)
Description: Gradually replace legacy system by routing traffic to new implementation.
Migration Process:
Phase 1: Facade
┌─────────┐ ┌─────────┐ ┌─────────────┐
│ Client │────→│ Facade │────→│ Legacy │
└─────────┘ └─────────┘ │ System │
└─────────────┘
Phase 2: Partial Migration
┌─────────┐ ┌─────────┐ ┌─────────────┐
│ Client │────→│ Facade │──┬─→│ Legacy │
└─────────┘ └─────────┘ │ └─────────────┘
│ ┌─────────────┐
└─→│ New System │
└─────────────┘
Phase 3: Complete Migration
┌─────────┐ ┌─────────┐ ┌─────────────┐
│ Client │────→│ Facade │────→│ New System │
└─────────┘ └─────────┘ └─────────────┘Implementation:
typescript
class PaymentFacade {
constructor(
private legacyPayment: LegacyPaymentService,
private newPayment: NewPaymentService,
private featureFlags: FeatureFlags
) {}
async processPayment(payment: Payment): Promise<Result> {
// Gradually migrate traffic
if (this.featureFlags.isEnabled('new-payment-system', payment.userId)) {
return this.newPayment.process(payment);
}
return this.legacyPayment.process(payment);
}
}说明:通过将流量路由到新实现,逐步替换遗留系统。
迁移流程:
Phase 1: Facade
┌─────────┐ ┌─────────┐ ┌─────────────┐
│ Client │────→│ Facade │────→│ Legacy │
└─────────┘ └─────────┘ │ System │
└─────────────┘
Phase 2: Partial Migration
┌─────────┐ ┌─────────┐ ┌─────────────┐
│ Client │────→│ Facade │──┬─→│ Legacy │
└─────────┘ └─────────┘ │ └─────────────┘
│ ┌─────────────┐
└─→│ New System │
└─────────────┘
Phase 3: Complete Migration
┌─────────┐ ┌─────────┐ ┌─────────────┐
│ Client │────→│ Facade │────→│ New System │
└─────────┘ └─────────┘ └─────────────┘实现示例:
typescript
class PaymentFacade {
constructor(
private legacyPayment: LegacyPaymentService,
private newPayment: NewPaymentService,
private featureFlags: FeatureFlags
) {}
async processPayment(payment: Payment): Promise<Result> {
// 逐步迁移流量
if (this.featureFlags.isEnabled('new-payment-system', payment.userId)) {
return this.newPayment.process(payment);
}
return this.legacyPayment.process(payment);
}
}Backend for Frontend (BFF)
前端后端(Backend for Frontend, BFF)
Description: Dedicated backend for each frontend type (web, mobile, etc.).
Structure:
┌─────────────┐
│ Web Client │
└──────┬──────┘
│
┌──────▼──────┐
│ Web BFF │
└──────┬──────┘
│
┌───────────────────┼───────────────────┐
│ │ │
┌──────▼──────┐ ┌──────▼──────┐ ┌──────▼──────┐
│ User Service│ │Order Service│ │Product Svc │
└─────────────┘ └─────────────┘ └─────────────┘
│ │ │
└───────────────────┼───────────────────┘
│
┌──────▼──────┐
│ Mobile BFF │
└──────┬──────┘
│
┌──────▼──────┐
│Mobile Client│
└─────────────┘Benefits:
- Optimized payload for each client
- Client-specific authentication
- Independent deployment per frontend
- Reduces over-fetching
When to Use:
| Scenario | Recommendation |
|---|---|
| Single client type | Skip BFF |
| Web + Mobile with same needs | Single API Gateway |
| Different UX per platform | Separate BFFs |
| Multiple teams per frontend | Dedicated BFFs |
说明:为每种前端类型(Web、移动等)提供专用的后端。
结构:
┌─────────────┐
│ Web Client │
└──────┬──────┘
│
┌──────▼──────┐
│ Web BFF │
└──────┬──────┘
│
┌───────────────────┼───────────────────┐
│ │ │
┌──────▼──────┐ ┌──────▼──────┐ ┌──────▼──────┐
│ User Service│ │Order Service│ │Product Svc │
└─────────────┘ └─────────────┘ └─────────────┘
│ │ │
└───────────────────┼───────────────────┘
│
┌──────▼──────┐
│ Mobile BFF │
└──────┬──────┘
│
┌──────▼──────┐
│Mobile Client│
└─────────────┘优势:
- 为每个客户端优化负载
- 客户端特定的认证
- 每个前端独立部署
- 减少过度获取数据
适用场景:
| 场景 | 建议 |
|---|---|
| 单一客户端类型 | 跳过BFF |
| Web + 移动需求相同 | 单一API网关 |
| 各平台UX不同 | 独立BFF |
| 每个前端对应多个团队 | 专用BFF |
Architecture Patterns Comparison
架构模式对比
| Pattern | Complexity | Scalability | Team Size | Best For |
|---|---|---|---|---|
| Monolith | Low | Vertical | Small (2-10) | MVPs, Simple apps |
| Modular Monolith | Medium | Vertical | Medium (5-20) | Growing apps |
| Microservices | High | Horizontal | Large (20+) | Complex domains |
| Serverless | Medium | Auto | Any | Event-driven, Variable load |
| Event-Driven | High | Horizontal | Medium-Large | Async workflows |
| 模式 | 复杂度 | 可扩展性 | 团队规模 | 最佳适用场景 |
|---|---|---|---|---|
| Monolith | 低 | 垂直扩容 | 小型(2-10人) | MVP、简单应用 |
| Modular Monolith | 中 | 垂直扩容 | 中型(5-20人) | 成长型应用 |
| Microservices | 高 | 水平扩容 | 大型(20+人) | 复杂领域 |
| Serverless | 中 | 自动扩容 | 任意规模 | 事件驱动、可变负载 |
| Event-Driven | 高 | 水平扩容 | 中大型 | 异步工作流 |
Architecture Decision Record (ADR) Template
架构决策记录(ADR)模板
When choosing an architecture, document decisions:
markdown
undefined选择架构时,记录决策:
markdown
undefinedADR-001: Choose Modular Monolith
ADR-001: 选择模块化单体架构
Status
状态
Accepted
已接受
Context
背景
- Team of 8 developers
- MVP deadline in 3 months
- Uncertain about domain boundaries
- Limited DevOps resources
- 8人开发团队
- 3个月后交付MVP
- 领域边界不明确
- DevOps资源有限
Decision
决策
Adopt Modular Monolith with strict boundaries
采用具有严格边界的模块化单体架构
Consequences
影响
Positive
积极
- Faster initial development
- Simpler deployment
- Can extract services later
- 初始开发更快
- 部署更简单
- 未来可拆分服务
Negative
消极
- Single point of failure
- Scaling limited to vertical
- Need discipline for module boundaries
- 单点故障
- 扩容仅限于垂直方向
- 需要严格遵守模块边界规范
Alternatives Considered
备选方案
- Microservices - Too complex for team size
- Traditional Monolith - No path to scale
---- 微服务 - 团队规模过小,复杂度太高
- 传统单体 - 无扩容路径
---Evolution Path
演进路径
┌─────────────────────────────────────────────────────────────────┐
│ Architecture Evolution │
│ │
│ Monolith ──→ Modular Monolith ──→ Microservices │
│ │ │ │ │
│ │ │ ▼ │
│ │ │ Event-Driven / CQRS │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ [Simple] [Growing] [Complex/Scale] │
│ │
│ Tip: Don't skip steps. Each stage teaches domain boundaries. │
└─────────────────────────────────────────────────────────────────┘┌─────────────────────────────────────────────────────────────────┐
│ 架构演进路径 │
│ │
│ Monolith ──→ Modular Monolith ──→ Microservices │
│ │ │ │ │
│ │ │ ▼ │
│ │ │ Event-Driven / CQRS │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ [简单] [成长中] [复杂/大规模] │
│ │
│ 提示:不要跳过阶段。每个阶段都能帮助理解领域边界。 │
└─────────────────────────────────────────────────────────────────┘Anti-Patterns to Avoid
需避免的反模式
1. Big Ball of Mud
1. 大泥球(Big Ball of Mud)
Symptom: No clear structure, everything depends on everything
Fix: Introduce module boundaries, apply Clean Architecture principles
症状:无清晰结构,一切依赖于一切
修复:引入模块边界,应用整洁架构原则
2. Golden Hammer
2. 金锤子(Golden Hammer)
Symptom: Using same architecture for every project
Fix: Evaluate requirements, use decision guide
症状:所有项目使用相同架构
修复:评估需求,使用决策指南
3. Accidental Complexity
3. 意外复杂度(Accidental Complexity)
Symptom: Architecture more complex than domain requires
Fix: Start simple, add complexity only when needed
症状:架构比领域需求更复杂
修复:从简单开始,仅在需要时增加复杂度
4. Resume-Driven Development
4. 简历驱动开发(Resume-Driven Development)
Symptom: Choosing tech for learning, not solving problems
Fix: Align architecture with team skills and project needs
症状:选择技术是为了学习而非解决问题
修复:使架构与团队技能和项目需求对齐
5. Vendor Lock-In
5. 供应商锁定(Vendor Lock-In)
Symptom: Core logic tightly coupled to cloud provider
Fix: Use Hexagonal Architecture, abstract vendor-specific code
症状:核心逻辑与云提供商紧密耦合
修复:使用六边形架构,抽象供应商特定代码
Performance Considerations by Pattern
各模式的性能考量
| Pattern | Latency | Throughput | Cold Start |
|---|---|---|---|
| Monolith | Low | High | N/A |
| Microservices | Medium (network) | High (distributed) | N/A |
| Serverless | Variable | Auto-scale | 100ms-2s |
| Event-Driven | Higher (async) | Very High | Depends |
| 模式 | 延迟 | 吞吐量 | 冷启动 |
|---|---|---|---|
| Monolith | 低 | 高 | 无 |
| Microservices | 中等(网络开销) | 高(分布式) | 无 |
| Serverless | 可变 | 自动扩容 | 100ms-2s |
| Event-Driven | 较高(异步) | 极高 | 取决于具体实现 |
Testing Strategies by Pattern
各模式的测试策略
Monolith
Monolith
Unit Tests → Integration Tests → E2E Tests
70% 20% 10%单元测试 → 集成测试 → 端到端测试
70% 20% 10%Microservices
Microservices
Unit Tests → Contract Tests → Integration → E2E
60% 20% 15% 5%
// Contract Test Example (Pact)
const provider = new Pact({ consumer: 'OrderService', provider: 'UserService' });
await provider.addInteraction({
state: 'user exists',
uponReceiving: 'get user request',
withRequest: { method: 'GET', path: '/users/123' },
willRespondWith: { status: 200, body: { id: '123', name: 'John' } }
});单元测试 → 契约测试 → 集成测试 → 端到端测试
60% 20% 15% 5%
// 契约测试示例(Pact)
const provider = new Pact({ consumer: 'OrderService', provider: 'UserService' });
await provider.addInteraction({
state: 'user exists',
uponReceiving: 'get user request',
withRequest: { method: 'GET', path: '/users/123' },
willRespondWith: { status: 200, body: { id: '123', name: 'John' } }
});Event-Driven
Event-Driven
- Test event producers and consumers independently
- Use event schema validation
- Test saga/workflow orchestration
- 独立测试事件生产者和消费者
- 使用事件 schema 验证
- 测试Saga/工作流编排
Related Skills
相关技能
- [[api-design]] - API design for service communication
- [[system-design]] - Large-scale system considerations
- [[devops-cicd]] - Deployment strategies for each pattern
- [[data-design]] - Database patterns for each architecture
- [[api-design]] - 服务通信的API设计
- [[system-design]] - 大规模系统考量
- [[devops-cicd]] - 各模式的部署策略
- [[data-design]] - 各架构的数据库模式