system-architecture-advisor

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

System Architecture Advisor

系统架构顾问

Overview

概述

Expert guidance for designing robust, scalable, and maintainable software architectures. Assists with architecture patterns, API design, tech stack selection, visual system diagrams, and best practices for modern application development.
When to use this skill:
  • Designing new system architecture
  • Evaluating or refactoring existing architecture
  • Choosing between architecture patterns
  • Planning API design (REST, GraphQL, RPC)
  • Creating system diagrams and documentation
  • Stack selection and technology evaluation
  • Scalability and performance planning
  • Security architecture design

为设计稳健、可扩展且易于维护的软件架构提供专业指导。协助处理架构模式、API设计、技术栈选型、可视化系统图表以及现代应用开发的最佳实践。
何时使用此技能:
  • 设计新的系统架构
  • 评估或重构现有架构
  • 选择架构模式
  • 规划API设计(REST、GraphQL、RPC)
  • 创建系统图表与文档
  • 技术栈选型与技术评估
  • 可扩展性与性能规划
  • 安全架构设计

Core Architecture Patterns

核心架构模式

Pattern Selection Framework

模式选择框架

Assess these factors first:
  1. Scale Requirements
    • Current users: <1K, 1K-100K, 100K-1M, >1M
    • Growth projection: 6 months, 1 year, 3+ years
    • Geographic distribution: Single region, multi-region, global
  2. Team Structure
    • Team size: 1-3, 4-10, 11-50, 50+
    • Team distribution: Co-located, distributed, hybrid
    • Technical expertise: Junior, mixed, senior
  3. Business Constraints
    • Time to market: Critical, normal, flexible
    • Budget: Startup, growth, enterprise
    • Compliance: Standard, regulated industry, highly regulated
首先评估以下因素:
  1. 规模需求
    • 当前用户量:<1K、1K-100K、100K-1M、>1M
    • 增长预期:6个月、1年、3年以上
    • 地域分布:单区域、多区域、全球化
  2. 团队结构
    • 团队规模:1-3人、4-10人、11-50人、50人以上
    • 团队分布:集中办公、分布式办公、混合模式
    • 技术能力:初级、混合、资深
  3. 业务约束
    • 上市时间:紧急、正常、灵活
    • 预算:初创、增长、企业级
    • 合规要求:标准、受监管行业、高度监管

Architecture Pattern Decision Tree

架构模式决策树

Start here and follow the path:
Is this a new project or refactoring existing?
├─ NEW PROJECT
│  │
│  ├─ Team size 1-3, MVP needed fast?
│  │  └─→ **MONOLITH** (Layered or Modular)
│  │
│  ├─ Multiple teams, different domains?
│  │  └─→ **MICROSERVICES**
│  │
│  ├─ Event-heavy, real-time processing?
│  │  └─→ **EVENT-DRIVEN ARCHITECTURE**
│  │
│  └─ Variable workload, cost-sensitive?
│     └─→ **SERVERLESS**
└─ REFACTORING EXISTING
   ├─ Monolith too complex, teams blocked?
   │  └─→ Gradually extract to **MICROSERVICES**
   ├─ Tight coupling causing issues?
   │  └─→ Introduce **EVENT-DRIVEN** patterns
   └─ Cost or scaling issues?
      └─→ Migrate components to **SERVERLESS**

从此处开始,遵循路径选择:
Is this a new project or refactoring existing?
├─ NEW PROJECT
│  │
│  ├─ Team size 1-3, MVP needed fast?
│  │  └─→ **MONOLITH** (Layered or Modular)
│  │
│  ├─ Multiple teams, different domains?
│  │  └─→ **MICROSERVICES**
│  │
│  ├─ Event-heavy, real-time processing?
│  │  └─→ **EVENT-DRIVEN ARCHITECTURE**
│  │
│  └─ Variable workload, cost-sensitive?
│     └─→ **SERVERLESS**
└─ REFACTORING EXISTING
   ├─ Monolith too complex, teams blocked?
   │  └─→ Gradually extract to **MICROSERVICES**
   ├─ Tight coupling causing issues?
   │  └─→ Introduce **EVENT-DRIVEN** patterns
   └─ Cost or scaling issues?
      └─→ Migrate components to **SERVERLESS**

Pattern Details with Pros/Cons

模式详情及优缺点

Monolithic Architecture

单体架构

When to use:
  • Startups needing fast iteration
  • Small teams (1-10 developers)
  • Straightforward business logic
  • Predictable traffic patterns
Structure:
Layered Monolith:
├─ Presentation Layer (UI/API)
├─ Business Logic Layer
├─ Data Access Layer
└─ Database

Modular Monolith:
├─ User Module (domain-driven)
├─ Product Module
├─ Order Module
├─ Payment Module
└─ Shared Kernel
Pros:
  • Simple deployment and debugging
  • Easier local development
  • ACID transactions work naturally
  • Lower operational complexity
Cons:
  • Scales as single unit (all or nothing)
  • Technology lock-in
  • Longer build/test times as app grows
  • Team conflicts in large codebases
Example Stack:
  • Next.js + Supabase: Modern, production-ready monolith
  • Django + PostgreSQL: Batteries-included framework
  • Rails + PostgreSQL: Convention over configuration

适用场景:
  • 需要快速迭代的初创公司
  • 小型团队(1-10名开发者)
  • 业务逻辑简单直接
  • 流量模式可预测
结构:
Layered Monolith:
├─ Presentation Layer (UI/API)
├─ Business Logic Layer
├─ Data Access Layer
└─ Database

Modular Monolith:
├─ User Module (domain-driven)
├─ Product Module
├─ Order Module
├─ Payment Module
└─ Shared Kernel
优点:
  • 部署与调试简单
  • 本地开发更便捷
  • ACID事务天然适用
  • 运维复杂度较低
缺点:
  • 作为单一单元扩展(全有或全无)
  • 技术锁定
  • 应用增长后构建/测试时间变长
  • 大型代码库中易出现团队冲突
示例技术栈:
  • Next.js + Supabase: 现代化、可用于生产环境的单体应用
  • Django + PostgreSQL: 功能完备的框架
  • Rails + PostgreSQL: 约定优于配置

Microservices Architecture

微服务架构

When to use:
  • Multiple teams working independently
  • Different domains with distinct scaling needs
  • Need for technology diversity
  • Mature DevOps capabilities
Structure:
API Gateway
├─ User Service (Node.js)
├─ Product Service (Go)
├─ Order Service (Python)
├─ Payment Service (Java)
└─ Notification Service (Serverless)

Each service:
├─ Own database
├─ Independent deployment
└─ RESTful/gRPC APIs
Pros:
  • Independent scaling per service
  • Technology flexibility
  • Team autonomy
  • Fault isolation
Cons:
  • Distributed system complexity
  • Network latency between services
  • Eventual consistency challenges
  • Higher operational overhead
Key Patterns:
  • API Gateway: Single entry point, request routing
  • Service Discovery: Dynamic service location
  • Circuit Breaker: Prevent cascading failures
  • Saga Pattern: Distributed transactions

适用场景:
  • 多个团队独立工作
  • 不同领域有不同的扩展需求
  • 需要技术多样性
  • 具备成熟的DevOps能力
结构:
API Gateway
├─ User Service (Node.js)
├─ Product Service (Go)
├─ Order Service (Python)
├─ Payment Service (Java)
└─ Notification Service (Serverless)

Each service:
├─ Own database
├─ Independent deployment
└─ RESTful/gRPC APIs
优点:
  • 按服务独立扩展
  • 技术灵活性高
  • 团队自主性强
  • 故障隔离
缺点:
  • 分布式系统复杂度高
  • 服务间存在网络延迟
  • 最终一致性挑战
  • 运维开销更高
关键模式:
  • API Gateway: 单一入口点,请求路由
  • Service Discovery: 动态服务定位
  • Circuit Breaker: 防止级联故障
  • Saga Pattern: 分布式事务

Event-Driven Architecture

事件驱动架构

When to use:
  • Real-time data processing
  • Decoupled components needed
  • Asynchronous workflows
  • IoT or streaming data
Structure:
Event Producers → Event Bus → Event Consumers
                (Kafka/RabbitMQ)
        ┌───────────┼───────────┐
        ↓           ↓           ↓
    Service A   Service B   Service C
Pros:
  • Loose coupling between services
  • Excellent scalability
  • Asynchronous processing
  • Real-time responsiveness
Cons:
  • Eventual consistency
  • Debugging challenges (event flows)
  • Event schema management
  • Requires message broker infrastructure
Technologies:
  • Apache Kafka: High-throughput, distributed log
  • RabbitMQ: Feature-rich message broker
  • AWS EventBridge: Managed event bus
  • Google Pub/Sub: Cloud-native messaging

适用场景:
  • 实时数据处理
  • 需要解耦组件
  • 异步工作流
  • IoT或流数据场景
结构:
Event Producers → Event Bus → Event Consumers
                (Kafka/RabbitMQ)
        ┌───────────┼───────────┐
        ↓           ↓           ↓
    Service A   Service B   Service C
优点:
  • 服务间松耦合
  • 扩展性出色
  • 异步处理
  • 实时响应能力
缺点:
  • 最终一致性问题
  • 调试难度大(事件流)
  • 事件 schema 管理复杂
  • 需要消息中间件基础设施
相关技术:
  • Apache Kafka: 高吞吐量分布式日志系统
  • RabbitMQ: 功能丰富的消息中间件
  • AWS EventBridge: 托管式事件总线
  • Google Pub/Sub: 云原生消息服务

Serverless Architecture

Serverless架构

When to use:
  • Variable/unpredictable traffic
  • Event-triggered workloads
  • Cost optimization priority
  • Minimal ops overhead desired
Structure:
API Gateway → Lambda Functions → Managed Services
              ├─ Auth Function → Cognito
              ├─ CRUD Function → DynamoDB
              └─ Processing Function → S3
Pros:
  • Pay per execution
  • Auto-scaling to zero
  • No server management
  • Fast deployment cycles
Cons:
  • Cold start latency
  • Vendor lock-in risk
  • Debugging complexity
  • Stateless constraints
Providers:
  • AWS Lambda + API Gateway + DynamoDB
  • Cloudflare Workers + D1 + R2
  • Vercel Functions + PostgreSQL
  • Supabase Edge Functions

适用场景:
  • 流量可变/不可预测
  • 事件触发的工作负载
  • 优先考虑成本优化
  • 希望最小化运维开销
结构:
API Gateway → Lambda Functions → Managed Services
              ├─ Auth Function → Cognito
              ├─ CRUD Function → DynamoDB
              └─ Processing Function → S3
优点:
  • 按执行量付费
  • 自动缩容至零
  • 无需服务器管理
  • 部署周期快
缺点:
  • 冷启动延迟
  • 供应商锁定风险
  • 调试复杂度高
  • 无状态约束
服务提供商:
  • AWS Lambda + API Gateway + DynamoDB
  • Cloudflare Workers + D1 + R2
  • Vercel Functions + PostgreSQL
  • Supabase Edge Functions

API Design Guidance

API设计指导

REST vs GraphQL vs RPC Decision Matrix

REST vs GraphQL vs RPC决策矩阵

FactorRESTGraphQLgRPC
Best forSimple CRUD, public APIsComplex data fetchingInternal microservices
PerformanceModerateGood (no over-fetching)Excellent (binary)
Learning curveLowMediumHigh
ToolingExcellentGoodGood
CachingNative HTTPCustomCustom
Real-timeWebSocket add-onBuilt-in subscriptionsStreaming RPC
因素RESTGraphQLgRPC
最佳适用场景简单CRUD、公开API复杂数据获取内部微服务
性能中等良好(无过度获取)优秀(二进制协议)
学习曲线中等
工具支持优秀良好良好
缓存原生HTTP缓存自定义缓存自定义缓存
实时性需添加WebSocket内置订阅功能流式RPC

REST API Best Practices

REST API最佳实践

Resource naming:
GET    /users              # List users
POST   /users              # Create user
GET    /users/{id}         # Get user
PUT    /users/{id}         # Update user (full)
PATCH  /users/{id}         # Update user (partial)
DELETE /users/{id}         # Delete user
资源命名:
GET    /users              # 列出用户
POST   /users              # 创建用户
GET    /users/{id}         # 获取单个用户
PUT    /users/{id}         # 完整更新用户
PATCH  /users/{id}         # 部分更新用户
DELETE /users/{id}         # 删除用户

Nested resources

嵌套资源

GET /users/{id}/orders # User's orders POST /users/{id}/orders # Create order for user

**Response structure:**
```json
{
  "data": { /* response payload */ },
  "meta": {
    "page": 1,
    "per_page": 20,
    "total": 150
  },
  "links": {
    "self": "/users?page=1",
    "next": "/users?page=2",
    "prev": null
  }
}
Status codes:
  • 200 OK
    - Successful GET, PUT, PATCH
  • 201 Created
    - Successful POST
  • 204 No Content
    - Successful DELETE
  • 400 Bad Request
    - Validation error
  • 401 Unauthorized
    - Missing auth
  • 403 Forbidden
    - Insufficient permissions
  • 404 Not Found
    - Resource doesn't exist
  • 500 Internal Server Error
    - Server failure
GET /users/{id}/orders # 用户的订单 POST /users/{id}/orders # 为用户创建订单

**响应结构:**
```json
{
  "data": { /* 响应负载 */ },
  "meta": {
    "page": 1,
    "per_page": 20,
    "total": 150
  },
  "links": {
    "self": "/users?page=1",
    "next": "/users?page=2",
    "prev": null
  }
}
状态码:
  • 200 OK
    - 成功的GET、PUT、PATCH请求
  • 201 Created
    - 成功的POST请求
  • 204 No Content
    - 成功的DELETE请求
  • 400 Bad Request
    - 验证错误
  • 401 Unauthorized
    - 缺少认证信息
  • 403 Forbidden
    - 权限不足
  • 404 Not Found
    - 资源不存在
  • 500 Internal Server Error
    - 服务器故障

GraphQL API Patterns

GraphQL API模式

Schema design:
graphql
type User {
  id: ID!
  name: String!
  email: String!
  orders: [Order!]!
}

type Order {
  id: ID!
  total: Float!
  items: [OrderItem!]!
  user: User!
}

type Query {
  user(id: ID!): User
  users(limit: Int, offset: Int): [User!]!
}

type Mutation {
  createUser(input: CreateUserInput!): User!
  updateUser(id: ID!, input: UpdateUserInput!): User!
}

type Subscription {
  orderCreated: Order!
}
Pros:
  • Single endpoint
  • Client specifies needed fields
  • Strong typing
  • Real-time with subscriptions
Cons:
  • Caching complexity
  • N+1 query problem (use DataLoader)
  • Learning curve for teams

Schema设计:
graphql
type User {
  id: ID!
  name: String!
  email: String!
  orders: [Order!]!
}

type Order {
  id: ID!
  total: Float!
  items: [OrderItem!]!
  user: User!
}

type Query {
  user(id: ID!): User
  users(limit: Int, offset: Int): [User!]!
}

type Mutation {
  createUser(input: CreateUserInput!): User!
  updateUser(id: ID!, input: UpdateUserInput!): User!
}

type Subscription {
  orderCreated: Order!
}
优点:
  • 单一端点
  • 客户端指定所需字段
  • 强类型
  • 订阅功能支持实时性
缺点:
  • 缓存复杂度高
  • N+1查询问题(使用DataLoader解决)
  • 团队学习曲线较陡

Tech Stack Recommendations

技术栈推荐

Full-Stack JavaScript (Modern SaaS)

全栈JavaScript(现代SaaS)

Stack: Next.js + Supabase + Vercel
Frontend: Next.js 15 (App Router)
Backend: Next.js API Routes + Supabase Edge Functions
Database: PostgreSQL (Supabase)
Auth: Supabase Auth
Storage: Supabase Storage
Hosting: Vercel (frontend), Supabase (backend)
Pros:
  • Single language (TypeScript)
  • Fast development
  • Excellent DX
  • Built-in auth, storage, real-time
Cons:
  • Vendor lock-in (mitigated: open-source)
  • Limited to JavaScript ecosystem
Perfect for: SaaS products, web apps, MVPs

技术栈: Next.js + Supabase + Vercel
Frontend: Next.js 15 (App Router)
Backend: Next.js API Routes + Supabase Edge Functions
Database: PostgreSQL (Supabase)
Auth: Supabase Auth
Storage: Supabase Storage
Hosting: Vercel (frontend), Supabase (backend)
优点:
  • 单一语言(TypeScript)
  • 开发速度快
  • 出色的开发者体验(DX)
  • 内置认证、存储、实时功能
缺点:
  • 供应商锁定(可通过开源缓解)
  • 局限于JavaScript生态
最佳适用: SaaS产品、Web应用、MVP

Python Backend + React Frontend

Python后端 + React前端

Stack: FastAPI + PostgreSQL + React + AWS
Frontend: React + Vite + TanStack Query
Backend: FastAPI (Python)
Database: PostgreSQL
Cache: Redis
Deployment: AWS ECS/Lambda + S3 + CloudFront
Pros:
  • Python for data-heavy backend
  • Rich ML/data science ecosystem
  • React for modern UI
  • AWS flexibility
Cons:
  • More moving parts
  • Two languages to maintain
Perfect for: Data-intensive apps, ML integration, complex business logic

技术栈: FastAPI + PostgreSQL + React + AWS
Frontend: React + Vite + TanStack Query
Backend: FastAPI (Python)
Database: PostgreSQL
Cache: Redis
Deployment: AWS ECS/Lambda + S3 + CloudFront
优点:
  • Python适用于数据密集型后端
  • 丰富的ML/数据科学生态
  • React构建现代UI
  • AWS灵活性高
缺点:
  • 组件更多,复杂度更高
  • 需要维护两种语言
最佳适用: 数据密集型应用、ML集成、复杂业务逻辑

Enterprise .NET

企业级.NET

Stack: ASP.NET Core + SQL Server + Azure
Backend: ASP.NET Core Web API
Database: SQL Server / CosmosDB
Frontend: Blazor / React
Deployment: Azure App Service + Azure SQL
Pros:
  • Enterprise-grade tooling
  • Excellent IDE support (Visual Studio)
  • Strong type safety
  • Azure integration
Cons:
  • Microsoft ecosystem lock-in
  • Higher learning curve
Perfect for: Enterprise applications, financial systems, compliance-heavy domains

技术栈: ASP.NET Core + SQL Server + Azure
Backend: ASP.NET Core Web API
Database: SQL Server / CosmosDB
Frontend: Blazor / React
Deployment: Azure App Service + Azure SQL
优点:
  • 企业级工具支持
  • 出色的IDE支持(Visual Studio)
  • 强类型安全
  • 与Azure深度集成
缺点:
  • 微软生态锁定
  • 学习曲线较陡
最佳适用: 企业级应用、金融系统、合规要求高的领域

Visual Diagrams with Mermaid

Mermaid可视化图表

System Context Diagram

系统上下文图

mermaid
graph TB
    User[User]
    Admin[Administrator]
    
    subgraph "System"
        API[API Gateway]
        Auth[Auth Service]
        App[Application Service]
        DB[(Database)]
    end
    
    Ext1[Payment Gateway]
    Ext2[Email Service]
    
    User -->|HTTPS| API
    Admin -->|HTTPS| API
    API --> Auth
    API --> App
    App --> DB
    App -->|REST| Ext1
    App -->|SMTP| Ext2
mermaid
graph TB
    User[User]
    Admin[Administrator]
    
    subgraph "System"
        API[API Gateway]
        Auth[Auth Service]
        App[Application Service]
        DB[(Database)]
    end
    
    Ext1[Payment Gateway]
    Ext2[Email Service]
    
    User -->|HTTPS| API
    Admin -->|HTTPS| API
    API --> Auth
    API --> App
    App --> DB
    App -->|REST| Ext1
    App -->|SMTP| Ext2

Microservices Architecture

微服务架构

mermaid
graph LR
    Client[Client Apps]
    Gateway[API Gateway]
    
    subgraph "Services"
        US[User Service]
        PS[Product Service]
        OS[Order Service]
        NS[Notification Service]
    end
    
    subgraph "Data"
        UDB[(User DB)]
        PDB[(Product DB)]
        ODB[(Order DB)]
    end
    
    MQ[Message Queue]
    
    Client --> Gateway
    Gateway --> US
    Gateway --> PS
    Gateway --> OS
    
    US --> UDB
    PS --> PDB
    OS --> ODB
    
    OS --> MQ
    MQ --> NS
mermaid
graph LR
    Client[Client Apps]
    Gateway[API Gateway]
    
    subgraph "Services"
        US[User Service]
        PS[Product Service]
        OS[Order Service]
        NS[Notification Service]
    end
    
    subgraph "Data"
        UDB[(User DB)]
        PDB[(Product DB)]
        ODB[(Order DB)]
    end
    
    MQ[Message Queue]
    
    Client --> Gateway
    Gateway --> US
    Gateway --> PS
    Gateway --> OS
    
    US --> UDB
    PS --> PDB
    OS --> ODB
    
    OS --> MQ
    MQ --> NS

Event-Driven Flow

事件驱动流程

mermaid
sequenceDiagram
    participant UI as User Interface
    participant API as API Service
    participant Queue as Event Queue
    participant Process as Processing Service
    participant DB as Database
    participant Notify as Notification Service
    
    UI->>API: Create Order
    API->>DB: Save Order
    API->>Queue: Publish OrderCreated
    API-->>UI: 201 Created
    
    Queue->>Process: OrderCreated Event
    Process->>DB: Update Inventory
    Process->>Queue: Publish OrderProcessed
    
    Queue->>Notify: OrderProcessed Event
    Notify->>UI: Send Email/Push
mermaid
sequenceDiagram
    participant UI as User Interface
    participant API as API Service
    participant Queue as Event Queue
    participant Process as Processing Service
    participant DB as Database
    participant Notify as Notification Service
    
    UI->>API: Create Order
    API->>DB: Save Order
    API->>Queue: Publish OrderCreated
    API-->>UI: 201 Created
    
    Queue->>Process: OrderCreated Event
    Process->>DB: Update Inventory
    Process->>Queue: Publish OrderProcessed
    
    Queue->>Notify: OrderProcessed Event
    Notify->>UI: Send Email/Push

Layered Architecture

分层架构

mermaid
graph TD
    subgraph "Presentation Layer"
        UI[Web UI]
        API[REST API]
    end
    
    subgraph "Business Logic Layer"
        Service[Services]
        Domain[Domain Models]
    end
    
    subgraph "Data Access Layer"
        Repo[Repositories]
        ORM[ORM/Query Builder]
    end
    
    subgraph "Infrastructure"
        DB[(Database)]
        Cache[(Cache)]
        Queue[Message Queue]
    end
    
    UI --> Service
    API --> Service
    Service --> Domain
    Service --> Repo
    Repo --> ORM
    ORM --> DB
    Service --> Cache
    Service --> Queue

mermaid
graph TD
    subgraph "Presentation Layer"
        UI[Web UI]
        API[REST API]
    end
    
    subgraph "Business Logic Layer"
        Service[Services]
        Domain[Domain Models]
    end
    
    subgraph "Data Access Layer"
        Repo[Repositories]
        ORM[ORM/Query Builder]
    end
    
    subgraph "Infrastructure"
        DB[(Database)]
        Cache[(Cache)]
        Queue[Message Queue]
    end
    
    UI --> Service
    API --> Service
    Service --> Domain
    Service --> Repo
    Repo --> ORM
    ORM --> DB
    Service --> Cache
    Service --> Queue

Security Architecture Principles

安全架构原则

Security Boundaries

安全边界

1. Network Security
Internet → WAF/CDN → Load Balancer → Private Network
                                     ├─ Web Tier (DMZ)
                                     └─ App Tier (Private)
                                        └─ Data Tier (Isolated)
2. Authentication & Authorization
  • Authentication: OAuth 2.0 + OIDC (Supabase Auth, Auth0, Cognito)
  • Authorization: RBAC (Role-Based) or ABAC (Attribute-Based)
  • API Security: JWT tokens, API keys with rate limiting
3. Data Protection
  • In Transit: TLS 1.3
  • At Rest: AES-256 encryption
  • Secrets Management: Vault, AWS Secrets Manager, or environment variables
1. 网络安全
Internet → WAF/CDN → Load Balancer → Private Network
                                     ├─ Web Tier (DMZ)
                                     └─ App Tier (Private)
                                        └─ Data Tier (Isolated)
2. 认证与授权
  • 认证: OAuth 2.0 + OIDC(Supabase Auth、Auth0、Cognito)
  • 授权: RBAC(基于角色)或ABAC(基于属性)
  • API安全: JWT令牌、带速率限制的API密钥
3. 数据保护
  • 传输中: TLS 1.3
  • 静态存储: AES-256加密
  • 密钥管理: Vault、AWS Secrets Manager或环境变量

Security Checklist

安全检查清单

  • HTTPS everywhere (no HTTP)
  • Input validation and sanitization
  • OWASP Top 10 mitigations
  • Rate limiting on public APIs
  • SQL injection prevention (parameterized queries)
  • XSS prevention (output encoding)
  • CSRF protection
  • Security headers (CSP, HSTS, etc.)
  • Regular dependency updates
  • Secrets never in code/repos

  • 全链路HTTPS(禁止HTTP)
  • 输入验证与清理
  • OWASP Top 10风险缓解
  • 公开API添加速率限制
  • 防止SQL注入(参数化查询)
  • 防止XSS(输出编码)
  • CSRF防护
  • 安全头(CSP、HSTS等)
  • 定期更新依赖
  • 密钥绝不存于代码/仓库

Scalability Patterns

可扩展性模式

Horizontal vs Vertical Scaling

水平扩展 vs 垂直扩展

Vertical Scaling (Scale Up):
  • Add more resources to single server
  • Simpler to implement
  • Physical limits
Horizontal Scaling (Scale Out):
  • Add more servers
  • Load balancer required
  • Better fault tolerance
  • Preferred for high scale
垂直扩展(Scale Up):
  • 为单个服务器添加更多资源
  • 实现更简单
  • 存在物理上限
水平扩展(Scale Out):
  • 添加更多服务器
  • 需要负载均衡器
  • 容错性更好
  • 高规模场景首选

Caching Strategy

缓存策略

Multi-Level Cache:
Request → CDN Cache → Application Cache → Database
          (Static)    (Redis/Memcached)
Cache Patterns:
  1. Cache-Aside: App loads from cache, fetches from DB on miss
  2. Write-Through: App writes to cache and DB simultaneously
  3. Write-Behind: App writes to cache, async writes to DB
多级缓存:
Request → CDN Cache → Application Cache → Database
          (Static)    (Redis/Memcached)
缓存模式:
  1. Cache-Aside: 应用先从缓存读取,缓存未命中时从数据库获取
  2. Write-Through: 应用同时写入缓存和数据库
  3. Write-Behind: 应用写入缓存,异步写入数据库

Database Scaling

数据库扩展

Read Scaling:
  • Read Replicas: Route read queries to replicas
  • CQRS Pattern: Separate read and write databases
Write Scaling:
  • Sharding: Partition data across multiple databases
  • Federation: Split by function (users DB, orders DB, products DB)

读取扩展:
  • 只读副本: 读取请求路由至副本
  • CQRS模式: 分离读、写数据库
写入扩展:
  • 分片: 数据分区存储至多个数据库
  • 联邦: 按功能拆分(用户库、订单库、产品库)

Folder Structure Recommendations

目录结构推荐

Next.js App Router (2025)

Next.js App Router(2025)

src/
├── app/
│   ├── (auth)/               # Route group
│   │   ├── login/
│   │   └── register/
│   ├── (dashboard)/
│   │   ├── layout.tsx
│   │   ├── page.tsx
│   │   └── settings/
│   ├── api/
│   │   ├── users/route.ts
│   │   └── auth/route.ts
│   └── layout.tsx            # Root layout
├── components/
│   ├── ui/                   # shadcn components
│   ├── forms/
│   └── layouts/
├── lib/
│   ├── db/                   # Database client
│   ├── auth/                 # Auth utilities
│   └── utils.ts
├── hooks/                    # Custom React hooks
└── types/                    # TypeScript types
src/
├── app/
│   ├── (auth)/               # 路由组
│   │   ├── login/
│   │   └── register/
│   ├── (dashboard)/
│   │   ├── layout.tsx
│   │   ├── page.tsx
│   │   └── settings/
│   ├── api/
│   │   ├── users/route.ts
│   │   └── auth/route.ts
│   └── layout.tsx            # 根布局
├── components/
│   ├── ui/                   # shadcn组件
│   ├── forms/
│   └── layouts/
├── lib/
│   ├── db/                   # 数据库客户端
│   ├── auth/                 # 认证工具
│   └── utils.ts
├── hooks/                    # 自定义React hooks
└── types/                    # TypeScript类型定义

Python FastAPI

Python FastAPI

app/
├── api/
│   ├── __init__.py
│   ├── dependencies.py
│   └── routes/
│       ├── users.py
│       ├── products.py
│       └── orders.py
├── core/
│   ├── config.py
│   ├── security.py
│   └── database.py
├── models/                   # SQLAlchemy models
│   ├── user.py
│   └── product.py
├── schemas/                  # Pydantic schemas
│   ├── user.py
│   └── product.py
├── services/                 # Business logic
│   ├── user_service.py
│   └── order_service.py
├── main.py
└── tests/

app/
├── api/
│   ├── __init__.py
│   ├── dependencies.py
│   └── routes/
│       ├── users.py
│       ├── products.py
│       └── orders.py
├── core/
│   ├── config.py
│   ├── security.py
│   └── database.py
├── models/                   # SQLAlchemy模型
│   ├── user.py
│   └── product.py
├── schemas/                  # Pydantic schemas
│   ├── user.py
│   └── product.py
├── services/                 # 业务逻辑
│   ├── user_service.py
│   └── order_service.py
├── main.py
└── tests/

Best Practices Summary

最佳实践总结

Separation of Concerns

关注点分离

Principle: Each component has single responsibility.
Example:
✅ Good:
- UserController: Handle HTTP requests
- UserService: Business logic
- UserRepository: Database operations

⌠Bad:
- UserController: HTTP + business logic + database
原则: 每个组件仅承担单一职责。
示例:
✅ 良好:
- UserController: 处理HTTP请求
- UserService: 业务逻辑
- UserRepository: 数据库操作

⌠不良:
- UserController: 同时处理HTTP、业务逻辑和数据库操作

Dependency Inversion

依赖反转

Principle: Depend on abstractions, not concretions.
Example:
typescript
// ✅ Good
interface IEmailService {
  sendEmail(to: string, subject: string, body: string): Promise<void>;
}

class OrderService {
  constructor(private emailService: IEmailService) {}
}

// ⌠Bad
class OrderService {
  constructor(private emailService: GmailService) {} // Concrete dependency
}
原则: 依赖抽象而非具体实现。
示例:
typescript
// ✅ 良好
interface IEmailService {
  sendEmail(to: string, subject: string, body: string): Promise<void>;
}

class OrderService {
  constructor(private emailService: IEmailService) {}
}

// ⌠不良
class OrderService {
  constructor(private emailService: GmailService) {} // 依赖具体实现
}

API Design Anti-Patterns to Avoid

API设计需避免的反模式

  • ⌠Chatty APIs (too many requests needed)
  • ⌠Overfetching (returning too much data)
  • ⌠Deeply nested resources (
    /users/123/orders/456/items/789
    )
  • ⌠RPC-style endpoints in REST (
    /getUserOrders
    ,
    /createOrderForUser
    )
  • ⌠Inconsistent naming
  • ⌠Missing pagination
  • ⌠No versioning strategy

  • ⌠碎聊式API(需要过多请求)
  • ⌠过度获取(返回过多数据)
  • ⌠深度嵌套资源(
    /users/123/orders/456/items/789
  • ⌠REST中使用RPC风格端点(
    /getUserOrders
    /createOrderForUser
  • ⌠命名不一致
  • ⌠缺少分页
  • ⌠无版本化策略

Decision Framework Template

决策框架模板

When recommending architecture, consider:
  1. Current State:
    • Existing system or greenfield?
    • Team skills and size?
    • Current pain points?
  2. Requirements:
    • Performance needs?
    • Scale expectations?
    • Budget constraints?
    • Time to market?
  3. Trade-offs:
    • Complexity vs flexibility?
    • Cost vs performance?
    • Speed vs correctness?
  4. Future-Proofing:
    • Growth trajectory?
    • Technology evolution?
    • Team expansion plans?
Output: Clear recommendation with reasoning, diagrams, and migration path (if refactoring).

推荐架构时,需考虑:
  1. 当前状态:
    • 现有系统还是全新项目?
    • 团队技能与规模?
    • 当前痛点?
  2. 需求:
    • 性能需求?
    • 规模预期?
    • 预算约束?
    • 上市时间?
  3. 权衡:
    • 复杂度 vs 灵活性?
    • 成本 vs 性能?
    • 速度 vs 正确性?
  4. 未来适配:
    • 增长轨迹?
    • 技术演进?
    • 团队扩张计划?
输出: 清晰的推荐方案及理由、图表、迁移路径(若涉及重构)。

Example Usage Patterns

示例使用模式

Request: "Design architecture for a SaaS product with 100K users"
Response includes:
  1. Recommended pattern (likely Modular Monolith → Microservices path)
  2. Tech stack (Next.js + Supabase + Vercel)
  3. System diagram (Mermaid)
  4. Folder structure
  5. Scaling plan
  6. Security considerations
  7. Migration strategy
Request: "Should I use REST or GraphQL for my e-commerce API?"
Response includes:
  1. Comparison matrix
  2. Recommendation based on context
  3. Example schema/endpoints
  4. Performance considerations
  5. Implementation guidance

请求: "为拥有10万用户的SaaS产品设计架构"
响应包含:
  1. 推荐模式(通常是模块化单体 → 微服务的演进路径)
  2. 技术栈(Next.js + Supabase + Vercel)
  3. 系统图表(Mermaid)
  4. 目录结构
  5. 扩展计划
  6. 安全考虑
  7. 迁移策略
请求: "我的电商API应该用REST还是GraphQL?"
响应包含:
  1. 对比矩阵
  2. 基于场景的推荐
  3. 示例schema/端点
  4. 性能考虑
  5. 实现指导

References

参考资料

For detailed architectural patterns and examples, see:
  • Official Next.js documentation for App Router patterns
  • AWS Well-Architected Framework for cloud architecture
  • Martin Fowler's patterns catalog for enterprise patterns
  • Microservices.io for microservices patterns
  • The Twelve-Factor App for modern app principles
如需详细的架构模式及示例,可参考:
  • Next.js官方文档中的App Router模式
  • AWS架构完善框架(云架构)
  • Martin Fowler的企业模式目录
  • Microservices.io的微服务模式
  • 《十二因素应用》现代应用原则