
Implementing Spec-Driven Development with Mermaid Charts
Implementing Spec-Driven Development with Mermaid Charts
Introduction
In modern software development, Spec-Driven Development (SDD) has emerged as a crucial methodology for ensuring project quality and team collaboration efficiency. The core principle of SDD is "define specifications first, then write code" — through detailed specification documents, we clarify system requirements, architectural design, and interface definitions, making the development process systematic and traceable.
However, traditional text-based specification documents often present several pain points:
-
High comprehension cost: Pure textual descriptions make it difficult to quickly grasp the system overview
-
Maintenance challenges: When specifications are updated, documents can easily become out of sync with actual implementation
-
Collaboration difficulties: Team members may have different interpretations of the same specification
This is where specification visualization becomes invaluable. By transforming abstract system designs into intuitive visual representations through diagrams, we can significantly improve the readability and maintainability of specifications.
Why Choose Mermaid?
Mermaid, as a text-based diagram generation tool, offers unique advantages in Spec-Driven Development:
-
Plain text format: Diagrams exist as code and can be directly embedded in Markdown documents
-
Version control friendly: Manage diagrams like code, easily tracking change history
-
Zero-dependency collaboration: Team members don't need specialized drawing tools, just a text editor
-
Consistent rendering: Displays correctly across platforms like GitHub, GitLab, Notion, and more
-
Low learning curve: Syntax is concise and intuitive, quick to master
If you want to quickly experience Mermaid's powerful capabilities, visit MermaidKit, an online tool platform specifically designed for Mermaid diagrams.
Spec-Driven Development Process Overview
Core Principles of SDD
Spec-Driven Development emphasizes clarifying the following content through detailed specification documents before coding:
-
Requirements Specification: User requirements, business processes, functional boundaries
-
Architecture Specification: System architecture, module division, technology selection
-
Interface Specification: API definitions, data structures, interaction protocols
-
Testing Specification: Test cases, acceptance criteria, quality metrics
Typical SDD Workflow
Let's use a Mermaid flowchart to illustrate a complete SDD process:
graph TB Start([Project Initiation]) --> Requirements[Requirements Analysis & Spec] Requirements --> Architecture[Architecture Design & Spec] Architecture --> API[Interface Design & Spec] API --> Review{Spec Review} Review -->|Approved| Development[Development Implementation] Review -->|Needs Revision| Requirements Development --> Testing[Testing & Validation] Testing --> Validate{Meets Specification?} Validate -->|Yes| Deploy[Deployment] Validate -->|No| Development Deploy --> End([Project Complete]) style Requirements fill:#e1f5ff style Architecture fill:#e1f5ff style API fill:#e1f5ff style Development fill:#fff4e1 style Testing fill:#ffe1e1In this workflow, each phase can use Mermaid diagrams to visualize specification content, ensuring the team has a unified understanding of requirements and design.
Mermaid in Requirements Specification Phase
Requirements specification is the starting point of SDD. Clear requirement visualization helps teams accurately understand business objectives.
User Journey Diagram
User journey diagrams show the complete process of user interaction with the system, helping us understand user experience and key touchpoints.
journey title User Registration and Login Flow section Visit Website Open Homepage: 5: User Browse Features: 4: User section Register Account Click Register Button: 5: User Fill Registration Info: 3: User Email Verification: 3: User, System Registration Success: 5: User section First Login Enter Credentials: 4: User System Validation: 3: System Enter Dashboard: 5: UserSystem Boundaries & Processes (Flowchart)
Flowcharts define system functional boundaries and business logic:
flowchart TD User[User] --> WebApp[Web Application] WebApp --> AuthService[Authentication Service] WebApp --> BusinessService[Business Service] AuthService --> Database[(User Database)] BusinessService --> Database BusinessService --> Cache[(Redis Cache)] BusinessService --> MessageQueue[Message Queue] MessageQueue --> EmailService[Email Service] MessageQueue --> NotificationService[Notification Service] subgraph "System Boundary" AuthService BusinessService Database Cache MessageQueue end subgraph "Third-party Services" EmailService NotificationService endState Machine Design (State Diagram)
For features with complex state transitions, state diagrams are the best choice:
stateDiagram-v2 [*] --> Inactive Inactive --> Active: Email Verified Active --> Normal: First Login Normal --> Frozen: Violation Normal --> Deleted: User Cancellation Frozen --> Normal: Appeal Successful Frozen --> Banned: Severe Violation Deleted --> [*] Banned --> [*]Mermaid in Architecture Design Phase
Architecture design specifications need to clearly show the system's structural hierarchy and component relationships.
System Architecture Diagram (Graph)
Using Mermaid's graph syntax to display overall system architecture:
graph TB subgraph "Frontend Layer" WebUI[Web Interface] MobileApp[Mobile App] end subgraph "API Gateway Layer" Gateway[API Gateway] end subgraph "Service Layer" UserService[User Service] OrderService[Order Service] PaymentService[Payment Service] NotifyService[Notification Service] end subgraph "Data Layer" MySQL[(MySQL)] Redis[(Redis)] MongoDB[(MongoDB)] end subgraph "Infrastructure" RabbitMQ[Message Queue] ElasticSearch[Search Engine] end WebUI --> Gateway MobileApp --> Gateway Gateway --> UserService Gateway --> OrderService Gateway --> PaymentService UserService --> MySQL UserService --> Redis OrderService --> MySQL OrderService --> RabbitMQ PaymentService --> MySQL RabbitMQ --> NotifyService NotifyService --> ElasticSearchComponent Relationship Diagram (Class Diagram)
Class diagrams are not only suitable for object-oriented design but can also show module and component dependencies:
classDiagram class AuthenticationModule { +login(credentials) +logout() +refreshToken() +validateToken() } class UserModule { +getProfile() +updateProfile() +deleteAccount() } class OrderModule { +createOrder() +getOrderList() +cancelOrder() } class PaymentModule { +processPayment() +refund() +getPaymentHistory() } class DatabaseAdapter { +query() +insert() +update() +delete() } class CacheAdapter { +get() +set() +delete() +expire() } AuthenticationModule --> DatabaseAdapter AuthenticationModule --> CacheAdapter UserModule --> DatabaseAdapter UserModule --> CacheAdapter OrderModule --> DatabaseAdapter OrderModule --> PaymentModule PaymentModule --> DatabaseAdapterData Flow Diagram (Flowchart)
Showing how data flows through the system:
flowchart LR Client[Client Request] --> Gateway[API Gateway] Gateway --> Auth{Authentication} Auth -->|Failed| Error401[Return 401] Auth -->|Success| RateLimit{Rate Limiting} RateLimit -->|Exceeded| Error429[Return 429] RateLimit -->|Passed| Router[Route Dispatch] Router --> Service[Business Service] Service --> Cache{Cache Query} Cache -->|Hit| Response[Return Result] Cache -->|Miss| Database[(Database)] Database --> UpdateCache[Update Cache] UpdateCache --> Response Response --> Logger[Logging] Logger --> Monitor[Monitoring] Monitor --> ClientMermaid in API Specification Phase
API specifications serve as the bridge for frontend-backend collaboration. Clear API documentation can significantly improve development efficiency.
API Interaction Flow (Sequence Diagram)
Sequence diagrams are the best tool for showing API call sequences:
sequenceDiagram participant Client as Client participant Gateway as API Gateway participant Auth as Auth Service participant User as User Service participant DB as Database Client->>Gateway: POST /api/login activate Gateway Gateway->>Auth: Verify Credentials activate Auth Auth->>DB: Query User Info activate DB DB-->>Auth: Return User Data deactivate DB alt Verification Success Auth->>Auth: Generate JWT Token Auth-->>Gateway: Return Token deactivate Auth Gateway-->>Client: 200 OK + Token else Verification Failed Auth-->>Gateway: Authentication Failed Gateway-->>Client: 401 Unauthorized end deactivate Gateway Note over Client,DB: Subsequent requests carry Token Client->>Gateway: GET /api/user/profile Client->>Gateway: Header: Authorization: Bearer {token} activate Gateway Gateway->>Auth: Validate Token activate Auth Auth-->>Gateway: Token Valid deactivate Auth Gateway->>User: Get User Info activate User User->>DB: Query Data activate DB DB-->>User: Return Data deactivate DB User-->>Gateway: User Info deactivate User Gateway-->>Client: 200 OK + User Data deactivate GatewayState Transitions (State Diagram)
For business scenarios with state transitions like orders or tickets:
stateDiagram-v2 [*] --> Pending: Create Order Pending --> Cancelled: Timeout/User Cancel Pending --> Processing: Payment Success Processing --> Cancelled: Refund Request Processing --> Shipping: Merchant Ships Shipping --> Completed: Confirm Receipt Shipping --> Refunding: Request Return Refunding --> Refunded: Refund Success Refunding --> Shipping: Refund Rejected Cancelled --> [*] Completed --> [*] Refunded --> [*] note right of Pending Auto-cancel if unpaid within 15 min end note note right of Shipping Auto-confirm after 7 days end noteEntity Relationship Diagram (ER Diagram)
Visualizing database design and API data models:
erDiagram USER ||--o{ ORDER : places USER { int user_id PK string email UK string username string password_hash datetime created_at datetime updated_at } ORDER ||--|{ ORDER_ITEM : contains ORDER { int order_id PK int user_id FK decimal total_amount string status datetime created_at } ORDER_ITEM }o--|| PRODUCT : references ORDER_ITEM { int item_id PK int order_id FK int product_id FK int quantity decimal price } PRODUCT { int product_id PK string name text description decimal price int stock } USER ||--o{ PAYMENT : makes PAYMENT ||--|| ORDER : for PAYMENT { int payment_id PK int order_id FK int user_id FK decimal amount string method string status datetime paid_at }Mermaid in Development & Testing Phase
Development and testing phases also require clear specification guidance.
Test Case Flow (Flowchart)
Visualizing test cases to ensure complete test coverage:
flowchart TD Start([Begin Testing]) --> SetupEnv[Setup Test Environment] SetupEnv --> CreateUser[Create Test User] CreateUser --> Test1{Test 1: Normal Login} Test1 -->|Pass| Test2{Test 2: Wrong Password} Test1 -->|Fail| LogError1[Log Error] Test2 -->|Pass| Test3{Test 3: Non-existent Account} Test2 -->|Fail| LogError2[Log Error] Test3 -->|Pass| Test4{Test 4: Token Refresh} Test3 -->|Fail| LogError3[Log Error] Test4 -->|Pass| Test5{Test 5: Logout Function} Test4 -->|Fail| LogError4[Log Error] Test5 -->|Pass| Cleanup[Cleanup Test Data] Test5 -->|Fail| LogError5[Log Error] LogError1 --> Cleanup LogError2 --> Cleanup LogError3 --> Cleanup LogError4 --> Cleanup LogError5 --> Cleanup Cleanup --> Report[Generate Test Report] Report --> End([Testing Complete])Project Timeline (Gantt Chart)
Using Gantt charts to plan development and testing schedules:
gantt title User Authentication System Development Plan dateFormat YYYY-MM-DD section Requirements & Design Requirements Analysis :done, req1, 2024-01-01, 3d Architecture Design :done, arch1, 2024-01-04, 3d Interface Design :done, api1, 2024-01-07, 2d Design Review :crit, done, review1, 2024-01-09, 1d section Development Phase Database Design :active, db1, 2024-01-10, 2d User Module Development : dev1, 2024-01-12, 4d Auth Module Development : dev2, 2024-01-14, 5d API Gateway Integration : dev3, 2024-01-19, 3d section Testing Phase Unit Testing : test1, 2024-01-16, 6d Integration Testing : test2, 2024-01-22, 3d Load Testing :crit, test3, 2024-01-25, 2d section Deployment Deployment Preparation : deploy1, 2024-01-27, 2d Production Deployment :crit, deploy2, 2024-01-29, 1d Post-deployment Testing : verify1, 2024-01-30, 1dGit Branching Strategy (Git Graph)
Visualizing team Git workflow:
gitGraph commit id: "Initialize project" branch develop checkout develop commit id: "Setup dev environment" branch feature/user-module checkout feature/user-module commit id: "Create user model" commit id: "Implement user CRUD" checkout develop branch feature/auth-module checkout feature/auth-module commit id: "Implement login logic" commit id: "Implement JWT validation" checkout develop merge feature/user-module commit id: "Merge user module" checkout feature/auth-module commit id: "Add token refresh" checkout develop merge feature/auth-module commit id: "Merge auth module" branch release/v1.0 checkout release/v1.0 commit id: "Prepare v1.0 release" commit id: "Fix pre-release bugs" checkout main merge release/v1.0 tag: "v1.0.0" checkout develop merge release/v1.0 commit id: "Sync main fixes"Complete SDD Project Case Study: User Authentication System
Let's demonstrate how to apply Mermaid diagrams throughout the entire SDD process through a complete user authentication system project.
Step 1: Requirements Specification
Requirements Overview: Build an authentication system supporting email registration, login, and token refresh.
The user journey diagram was shown earlier. Here's a supplementary functional requirements state machine:
stateDiagram-v2 [*] --> Unregistered Unregistered --> Registered_Inactive: Submit Registration Registered_Inactive --> Active: Click Email Verification Link Registered_Inactive --> Unregistered: Activation Link Expired Active --> LoggedIn: Enter Correct Credentials LoggedIn --> Active: Logout LoggedIn --> LoggedIn: Refresh TokenStep 2: Architecture Design
System adopts microservices architecture with independently deployed authentication service:
graph TB subgraph "Client Side" WebClient[Web Frontend] MobileClient[Mobile App] end subgraph "Gateway Layer" Gateway[Nginx + API Gateway] end subgraph "Authentication Service" AuthAPI[Auth API] TokenService[Token Service] EmailService[Email Service] end subgraph "Data Storage" PostgreSQL[(PostgreSQL<br>User Data)] Redis[(Redis<br>Session & Token)] end WebClient --> Gateway MobileClient --> Gateway Gateway --> AuthAPI AuthAPI --> TokenService AuthAPI --> EmailService AuthAPI --> PostgreSQL TokenService --> Redis EmailService --> RedisStep 3: Interface Design
Registration Interface Sequence:
sequenceDiagram participant C as Client participant A as Auth Service participant D as Database participant R as Redis participant E as Email Service C->>A: POST /api/auth/register<br>{email, password, username} activate A A->>D: Check if email exists activate D D-->>A: Email not registered deactivate D A->>A: Generate password hash A->>D: Insert user record (status=inactive) activate D D-->>A: User created successfully deactivate D A->>A: Generate activation token A->>R: Store activation token (TTL=24h) activate R R-->>A: Storage successful deactivate R A->>E: Send activation email activate E E-->>A: Email sent deactivate E A-->>C: 201 Created<br>{message: "Please check email to activate"} deactivate AData Model:
erDiagram USERS { uuid id PK string email UK string username string password_hash enum status timestamp email_verified_at timestamp created_at timestamp updated_at } SESSIONS { uuid session_id PK uuid user_id FK string access_token string refresh_token timestamp expires_at timestamp created_at } USERS ||--o{ SESSIONS : hasStep 4: Development Implementation
Core Authentication Flow:
flowchart TD Start[Receive Login Request] --> ValidateInput{Validate Input Format} ValidateInput -->|Invalid| Return400[Return 400 Error] ValidateInput -->|Valid| QueryUser[Query User] QueryUser --> UserExists{User Exists?} UserExists -->|No| Return401[Return 401 Error] UserExists -->|Yes| CheckPassword{Verify Password} CheckPassword -->|Incorrect| Return401 CheckPassword -->|Correct| CheckStatus{Check Account Status} CheckStatus -->|Inactive| Return403[Return 403 Error] CheckStatus -->|Banned| Return403 CheckStatus -->|Normal| GenerateTokens[Generate Tokens] GenerateTokens --> StoreSession[Store Session] StoreSession --> Return200[Return 200 + Tokens] Return400 --> End[End] Return401 --> End Return403 --> End Return200 --> EndStep 5: Testing & Validation
Test Case Coverage:
mindmap root((Auth System Testing)) Registration Normal registration flow Email already exists Password strength validation Email sending verification Login Correct credentials Wrong password Non-existent account Inactive account Banned account Token Management Access Token validation Refresh Token renewal Token expiration handling Concurrent token requests Security Testing SQL injection protection XSS protection Brute force protection CSRF protectionStep 6: Deployment
Deployment Architecture:
graph TB subgraph "Load Balancing" LB[Load Balancer] end subgraph "Application Servers" App1[Auth Service - 1] App2[Auth Service - 2] App3[Auth Service - 3] end subgraph "Database Cluster" Primary[(PostgreSQL<br>Primary)] Replica1[(PostgreSQL<br>Replica 1)] Replica2[(PostgreSQL<br>Replica 2)] end subgraph "Cache Cluster" RedisM[(Redis Master)] RedisS1[(Redis Slave 1)] RedisS2[(Redis Slave 2)] end LB --> App1 LB --> App2 LB --> App3 App1 --> Primary App2 --> Primary App3 --> Primary Primary --> Replica1 Primary --> Replica2 App1 --> RedisM App2 --> RedisM App3 --> RedisM RedisM --> RedisS1 RedisM --> RedisS2Through this complete project case study, we can see how Mermaid spans the entire SDD process, from requirements to deployment, with corresponding visualization diagrams supporting each phase.
Conclusion
Spec-Driven Development combined with Mermaid diagrams provides us with an efficient and maintainable software development methodology:
-
Reduced Communication Costs: Diagrams are more intuitive than text, reducing misunderstandings
-
Improved Collaboration Efficiency: Plain text format facilitates version control and team collaboration
-
Ensured Development Quality: Clear specifications guide development, reducing rework
-
Easier Knowledge Transfer: Visualized documentation is easier for new members to understand
In practice, it's recommended to embed Mermaid diagrams into the project's documentation system (such as README.md, Wiki, etc.), keeping specifications "alive" in the code repository and evolving with the code.
If you want to create and manage Mermaid diagrams more efficiently, visit MermaidKit to experience visualization editing and collaboration features designed specifically for Mermaid. Let's build better software systems together through visualization!