c4-architecture

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

C4 Architecture Documentation

C4架构文档

Generate software architecture documentation using C4 model diagrams in Mermaid syntax.
使用Mermaid语法的C4模型图生成软件架构文档。

Workflow

工作流程

  1. Understand scope - Determine which C4 level(s) are needed based on audience
  2. Analyze codebase - Explore the system to identify components, containers, and relationships
  3. Generate diagrams - Create Mermaid C4 diagrams at appropriate abstraction levels
  4. Document - Write diagrams to markdown files with explanatory context
  1. 明确范围 - 根据受众确定所需的C4层级
  2. 分析代码库 - 探索系统以识别组件、容器及它们之间的关系
  3. 生成图表 - 在合适的抽象层级创建Mermaid C4图
  4. 文档记录 - 将图表写入Markdown文件并添加说明性上下文

C4 Diagram Levels

C4图表层级

Select the appropriate level based on the documentation need:
LevelDiagram TypeAudienceShowsWhen to Create
1C4ContextEveryoneSystem + external actorsAlways (required)
2C4ContainerTechnicalApps, databases, servicesAlways (required)
3C4ComponentDevelopersInternal componentsOnly if adds value
4C4DeploymentDevOpsInfrastructure nodesFor production systems
-C4DynamicTechnicalRequest flows (numbered)For complex workflows
Key Insight: "Context + Container diagrams are sufficient for most software development teams." Only create Component/Code diagrams when they genuinely add value.
根据文档需求选择合适的层级:
层级图表类型受众展示内容创建时机
1C4Context所有相关人员系统及外部参与者始终需要(必填)
2C4Container技术人员应用、数据库、服务始终需要(必填)
3C4Component开发人员内部组件仅当能增加价值时
4C4DeploymentDevOps人员基础设施节点针对生产系统
-C4Dynamic技术人员请求流程(带编号)针对复杂工作流
关键见解: "上下文图+容器图对大多数软件开发团队来说已足够。"仅当组件/代码图能真正增加价值时才创建。

Quick Start Examples

快速开始示例

System Context (Level 1)

系统上下文(层级1)

mermaid
C4Context
  title System Context - Workout Tracker

  Person(user, "User", "Tracks workouts and exercises")
  System(app, "Workout Tracker", "Vue PWA for tracking strength and CrossFit workouts")
  System_Ext(browser, "Web Browser", "Stores data in IndexedDB")

  Rel(user, app, "Uses")
  Rel(app, browser, "Persists data to", "IndexedDB")
mermaid
C4Context
  title System Context - Workout Tracker

  Person(user, "User", "Tracks workouts and exercises")
  System(app, "Workout Tracker", "Vue PWA for tracking strength and CrossFit workouts")
  System_Ext(browser, "Web Browser", "Stores data in IndexedDB")

  Rel(user, app, "Uses")
  Rel(app, browser, "Persists data to", "IndexedDB")

Container Diagram (Level 2)

容器图(层级2)

mermaid
C4Container
  title Container Diagram - Workout Tracker

  Person(user, "User", "Tracks workouts")

  Container_Boundary(app, "Workout Tracker PWA") {
    Container(spa, "SPA", "Vue 3, TypeScript", "Single-page application")
    Container(pinia, "State Management", "Pinia", "Manages application state")
    ContainerDb(indexeddb, "IndexedDB", "Dexie", "Local workout storage")
  }

  Rel(user, spa, "Uses")
  Rel(spa, pinia, "Reads/writes state")
  Rel(pinia, indexeddb, "Persists", "Dexie ORM")
mermaid
C4Container
  title Container Diagram - Workout Tracker

  Person(user, "User", "Tracks workouts")

  Container_Boundary(app, "Workout Tracker PWA") {
    Container(spa, "SPA", "Vue 3, TypeScript", "Single-page application")
    Container(pinia, "State Management", "Pinia", "Manages application state")
    ContainerDb(indexeddb, "IndexedDB", "Dexie", "Local workout storage")
  }

  Rel(user, spa, "Uses")
  Rel(spa, pinia, "Reads/writes state")
  Rel(pinia, indexeddb, "Persists", "Dexie ORM")

Component Diagram (Level 3)

组件图(层级3)

mermaid
C4Component
  title Component Diagram - Workout Feature

  Container(views, "Views", "Vue Router pages")

  Container_Boundary(workout, "Workout Feature") {
    Component(useWorkout, "useWorkout", "Composable", "Workout execution state")
    Component(useTimer, "useTimer", "Composable", "Timer state machine")
    Component(workoutRepo, "WorkoutRepository", "Dexie", "Workout persistence")
  }

  Rel(views, useWorkout, "Uses")
  Rel(useWorkout, useTimer, "Controls")
  Rel(useWorkout, workoutRepo, "Saves to")
mermaid
C4Component
  title Component Diagram - Workout Feature

  Container(views, "Views", "Vue Router pages")

  Container_Boundary(workout, "Workout Feature") {
    Component(useWorkout, "useWorkout", "Composable", "Workout execution state")
    Component(useTimer, "useTimer", "Composable", "Timer state machine")
    Component(workoutRepo, "WorkoutRepository", "Dexie", "Workout persistence")
  }

  Rel(views, useWorkout, "Uses")
  Rel(useWorkout, useTimer, "Controls")
  Rel(useWorkout, workoutRepo, "Saves to")

Dynamic Diagram (Request Flow)

动态图(请求流程)

mermaid
C4Dynamic
  title Dynamic Diagram - User Sign In Flow

  ContainerDb(db, "Database", "PostgreSQL", "User credentials")
  Container(spa, "Single-Page App", "React", "Banking UI")

  Container_Boundary(api, "API Application") {
    Component(signIn, "Sign In Controller", "Express", "Auth endpoint")
    Component(security, "Security Service", "JWT", "Validates credentials")
  }

  Rel(spa, signIn, "1. Submit credentials", "JSON/HTTPS")
  Rel(signIn, security, "2. Validate")
  Rel(security, db, "3. Query user", "SQL")

  UpdateRelStyle(spa, signIn, $textColor="blue", $offsetY="-30")
mermaid
C4Dynamic
  title Dynamic Diagram - User Sign In Flow

  ContainerDb(db, "Database", "PostgreSQL", "User credentials")
  Container(spa, "Single-Page App", "React", "Banking UI")

  Container_Boundary(api, "API Application") {
    Component(signIn, "Sign In Controller", "Express", "Auth endpoint")
    Component(security, "Security Service", "JWT", "Validates credentials")
  }

  Rel(spa, signIn, "1. Submit credentials", "JSON/HTTPS")
  Rel(signIn, security, "2. Validate")
  Rel(security, db, "3. Query user", "SQL")

  UpdateRelStyle(spa, signIn, $textColor="blue", $offsetY="-30")

Deployment Diagram

部署图

mermaid
C4Deployment
  title Deployment Diagram - Production

  Deployment_Node(browser, "Customer Browser", "Chrome/Firefox") {
    Container(spa, "SPA", "React", "Web application")
  }

  Deployment_Node(aws, "AWS Cloud", "us-east-1") {
    Deployment_Node(ecs, "ECS Cluster", "Fargate") {
      Container(api, "API Service", "Node.js", "REST API")
    }
    Deployment_Node(rds, "RDS", "db.r5.large") {
      ContainerDb(db, "Database", "PostgreSQL", "Application data")
    }
  }

  Rel(spa, api, "API calls", "HTTPS")
  Rel(api, db, "Reads/writes", "JDBC")
mermaid
C4Deployment
  title Deployment Diagram - Production

  Deployment_Node(browser, "Customer Browser", "Chrome/Firefox") {
    Container(spa, "SPA", "React", "Web application")
  }

  Deployment_Node(aws, "AWS Cloud", "us-east-1") {
    Deployment_Node(ecs, "ECS Cluster", "Fargate") {
      Container(api, "API Service", "Node.js", "REST API")
    }
    Deployment_Node(rds, "RDS", "db.r5.large") {
      ContainerDb(db, "Database", "PostgreSQL", "Application data")
    }
  }

  Rel(spa, api, "API calls", "HTTPS")
  Rel(api, db, "Reads/writes", "JDBC")

Element Syntax

元素语法

People and Systems

人员与系统

Person(alias, "Label", "Description")
Person_Ext(alias, "Label", "Description")       # External person
System(alias, "Label", "Description")
System_Ext(alias, "Label", "Description")       # External system
SystemDb(alias, "Label", "Description")         # Database system
SystemQueue(alias, "Label", "Description")      # Queue system
Person(alias, "Label", "Description")
Person_Ext(alias, "Label", "Description")       # External person
System(alias, "Label", "Description")
System_Ext(alias, "Label", "Description")       # External system
SystemDb(alias, "Label", "Description")         # Database system
SystemQueue(alias, "Label", "Description")      # Queue system

Containers

容器

Container(alias, "Label", "Technology", "Description")
Container_Ext(alias, "Label", "Technology", "Description")
ContainerDb(alias, "Label", "Technology", "Description")
ContainerQueue(alias, "Label", "Technology", "Description")
Container(alias, "Label", "Technology", "Description")
Container_Ext(alias, "Label", "Technology", "Description")
ContainerDb(alias, "Label", "Technology", "Description")
ContainerQueue(alias, "Label", "Technology", "Description")

Components

组件

Component(alias, "Label", "Technology", "Description")
Component_Ext(alias, "Label", "Technology", "Description")
ComponentDb(alias, "Label", "Technology", "Description")
Component(alias, "Label", "Technology", "Description")
Component_Ext(alias, "Label", "Technology", "Description")
ComponentDb(alias, "Label", "Technology", "Description")

Boundaries

边界

Enterprise_Boundary(alias, "Label") { ... }
System_Boundary(alias, "Label") { ... }
Container_Boundary(alias, "Label") { ... }
Boundary(alias, "Label", "type") { ... }
Enterprise_Boundary(alias, "Label") { ... }
System_Boundary(alias, "Label") { ... }
Container_Boundary(alias, "Label") { ... }
Boundary(alias, "Label", "type") { ... }

Relationships

关系

Rel(from, to, "Label")
Rel(from, to, "Label", "Technology")
BiRel(from, to, "Label")                        # Bidirectional
Rel_U(from, to, "Label")                        # Upward
Rel_D(from, to, "Label")                        # Downward
Rel_L(from, to, "Label")                        # Leftward
Rel_R(from, to, "Label")                        # Rightward
Rel(from, to, "Label")
Rel(from, to, "Label", "Technology")
BiRel(from, to, "Label")                        # Bidirectional
Rel_U(from, to, "Label")                        # Upward
Rel_D(from, to, "Label")                        # Downward
Rel_L(from, to, "Label")                        # Leftward
Rel_R(from, to, "Label")                        # Rightward

Deployment Nodes

部署节点

Deployment_Node(alias, "Label", "Type", "Description") { ... }
Node(alias, "Label", "Type", "Description") { ... }  # Shorthand
Deployment_Node(alias, "Label", "Type", "Description") { ... }
Node(alias, "Label", "Type", "Description") { ... }  # Shorthand

Styling and Layout

样式与布局

Layout Configuration

布局配置

UpdateLayoutConfig($c4ShapeInRow="3", $c4BoundaryInRow="1")
  • $c4ShapeInRow
    - Number of shapes per row (default: 4)
  • $c4BoundaryInRow
    - Number of boundaries per row (default: 2)
UpdateLayoutConfig($c4ShapeInRow="3", $c4BoundaryInRow="1")
  • $c4ShapeInRow
    - 每行形状数量(默认:4)
  • $c4BoundaryInRow
    - 每行边界数量(默认:2)

Element Styling

元素样式

UpdateElementStyle(alias, $fontColor="red", $bgColor="grey", $borderColor="red")
UpdateElementStyle(alias, $fontColor="red", $bgColor="grey", $borderColor="red")

Relationship Styling

关系样式

UpdateRelStyle(from, to, $textColor="blue", $lineColor="blue", $offsetX="5", $offsetY="-10")
Use
$offsetX
and
$offsetY
to fix overlapping relationship labels.
UpdateRelStyle(from, to, $textColor="blue", $lineColor="blue", $offsetX="5", $offsetY="-10")
使用
$offsetX
$offsetY
修复重叠的关系标签。

Best Practices

最佳实践

Essential Rules

核心规则

  1. Every element must have: Name, Type, Technology (where applicable), and Description
  2. Use unidirectional arrows only - Bidirectional arrows create ambiguity
  3. Label arrows with action verbs - "Sends email using", "Reads from", not just "uses"
  4. Include technology labels - "JSON/HTTPS", "JDBC", "gRPC"
  5. Stay under 20 elements per diagram - Split complex systems into multiple diagrams
  1. 每个元素必须包含:名称、类型、技术(适用时)及描述
  2. 仅使用单向箭头 - 双向箭头会造成歧义
  3. 用动作动词标记箭头 - 例如“使用...发送邮件”、“从...读取”,而非仅“使用”
  4. 包含技术标签 - 例如“JSON/HTTPS”、“JDBC”、“gRPC”
  5. 每张图的元素不超过20个 - 复杂系统拆分为多张图

Clarity Guidelines

清晰性指南

  1. Start at Level 1 - Context diagrams help frame the system scope
  2. One diagram per file - Keep diagrams focused on a single abstraction level
  3. Meaningful aliases - Use descriptive aliases (e.g.,
    orderService
    not
    s1
    )
  4. Concise descriptions - Keep descriptions under 50 characters when possible
  5. Always include a title - "System Context diagram for [System Name]"
  1. 从层级1开始 - 上下文图有助于明确系统范围
  2. 一个文件一张图 - 保持图表聚焦于单一抽象层级
  3. 有意义的别名 - 使用描述性别名(例如
    orderService
    而非
    s1
  4. 简洁的描述 - 尽可能将描述控制在50字符以内
  5. 始终包含标题 - 例如“[系统名称]的系统上下文图”

What to Avoid

需避免的情况

See references/common-mistakes.md for detailed anti-patterns:
  • Confusing containers (deployable) vs components (non-deployable)
  • Modeling shared libraries as containers
  • Showing message brokers as single containers instead of individual topics
  • Adding undefined abstraction levels like "subcomponents"
  • Removing type labels to "simplify" diagrams
详细反模式请参见references/common-mistakes.md
  • 混淆容器(可部署)与组件(不可部署)
  • 将共享库建模为容器
  • 将消息代理显示为单个容器而非独立主题
  • 添加未定义的抽象层级如“子组件”
  • 移除类型标签以“简化”图表

Microservices Guidelines

微服务指南

Single Team Ownership

单团队所有权

Model each microservice as a container (or container group):
mermaid
C4Container
  title Microservices - Single Team

  System_Boundary(platform, "E-commerce Platform") {
    Container(orderApi, "Order Service", "Spring Boot", "Order processing")
    ContainerDb(orderDb, "Order DB", "PostgreSQL", "Order data")
    Container(inventoryApi, "Inventory Service", "Node.js", "Stock management")
    ContainerDb(inventoryDb, "Inventory DB", "MongoDB", "Stock data")
  }
将每个微服务建模为容器(或容器组):
mermaid
C4Container
  title Microservices - Single Team

  System_Boundary(platform, "E-commerce Platform") {
    Container(orderApi, "Order Service", "Spring Boot", "Order processing")
    ContainerDb(orderDb, "Order DB", "PostgreSQL", "Order data")
    Container(inventoryApi, "Inventory Service", "Node.js", "Stock management")
    ContainerDb(inventoryDb, "Inventory DB", "MongoDB", "Stock data")
  }

Multi-Team Ownership

多团队所有权

Promote microservices to software systems when owned by separate teams:
mermaid
C4Context
  title Microservices - Multi-Team

  Person(customer, "Customer", "Places orders")
  System(orderSystem, "Order System", "Team Alpha")
  System(inventorySystem, "Inventory System", "Team Beta")
  System(paymentSystem, "Payment System", "Team Gamma")

  Rel(customer, orderSystem, "Places orders")
  Rel(orderSystem, inventorySystem, "Checks stock")
  Rel(orderSystem, paymentSystem, "Processes payment")
当微服务由不同团队拥有时,将其提升为软件系统
mermaid
C4Context
  title Microservices - Multi-Team

  Person(customer, "Customer", "Places orders")
  System(orderSystem, "Order System", "Team Alpha")
  System(inventorySystem, "Inventory System", "Team Beta")
  System(paymentSystem, "Payment System", "Team Gamma")

  Rel(customer, orderSystem, "Places orders")
  Rel(orderSystem, inventorySystem, "Checks stock")
  Rel(orderSystem, paymentSystem, "Processes payment")

Event-Driven Architecture

事件驱动架构

Show individual topics/queues as containers, NOT a single "Kafka" box:
mermaid
C4Container
  title Event-Driven Architecture

  Container(orderService, "Order Service", "Java", "Creates orders")
  Container(stockService, "Stock Service", "Java", "Manages inventory")
  ContainerQueue(orderTopic, "order.created", "Kafka", "Order events")
  ContainerQueue(stockTopic, "stock.reserved", "Kafka", "Stock events")

  Rel(orderService, orderTopic, "Publishes to")
  Rel(stockService, orderTopic, "Subscribes to")
  Rel(stockService, stockTopic, "Publishes to")
  Rel(orderService, stockTopic, "Subscribes to")
将单个主题/队列显示为容器,而非单个“Kafka”框:
mermaid
C4Container
  title Event-Driven Architecture

  Container(orderService, "Order Service", "Java", "Creates orders")
  Container(stockService, "Stock Service", "Java", "Manages inventory")
  ContainerQueue(orderTopic, "order.created", "Kafka", "Order events")
  ContainerQueue(stockTopic, "stock.reserved", "Kafka", "Stock events")

  Rel(orderService, orderTopic, "Publishes to")
  Rel(stockService, orderTopic, "Subscribes to")
  Rel(stockService, stockTopic, "Publishes to")
  Rel(orderService, stockTopic, "Subscribes to")

Output Location

输出位置

Write architecture documentation to
docs/architecture/
with naming convention:
  • c4-context.md
    - System context diagram
  • c4-containers.md
    - Container diagram
  • c4-components-{feature}.md
    - Component diagrams per feature
  • c4-deployment.md
    - Deployment diagram
  • c4-dynamic-{flow}.md
    - Dynamic diagrams for specific flows
将架构文档写入
docs/architecture/
目录,命名规则如下:
  • c4-context.md
    - 系统上下文图
  • c4-containers.md
    - 容器图
  • c4-components-{feature}.md
    - 按功能划分的组件图
  • c4-deployment.md
    - 部署图
  • c4-dynamic-{flow}.md
    - 特定流程的动态图

Audience-Appropriate Detail

适配受众的细节

AudienceRecommended Diagrams
ExecutivesSystem Context only
Product ManagersContext + Container
ArchitectsContext + Container + key Components
DevelopersAll levels as needed
DevOpsContainer + Deployment
受众推荐图表
高管仅系统上下文图
产品经理上下文图+容器图
架构师上下文图+容器图+关键组件图
开发人员按需使用所有层级
DevOps容器图+部署图

References

参考资料

  • references/c4-syntax.md - Complete Mermaid C4 syntax
  • references/common-mistakes.md - Anti-patterns to avoid
  • references/advanced-patterns.md - Microservices, event-driven, deployment
  • references/c4-syntax.md - 完整的Mermaid C4语法
  • references/common-mistakes.md - 需避免的错误
  • references/advanced-patterns.md - 微服务、事件驱动、部署相关内容