# Mermaid Diagram Guide ## Overview This guide helps you choose the right Mermaid diagram type for your documentation and provides examples for common use cases. ## Quick Reference | Diagram Type | Use For | Complexity | |----------------------|------------------------|---------------------------| | **Flowchart** | Workflows, decision trees | | | **Sequence Diagram** | API interactions, request flows | | | **Class Diagram** | Code structure, patterns | | | **Graph** | System architecture, dependencies | | | **ER Diagram** | Database schema | | | **Gantt** | Timeline, project schedule | | | **C4 Diagram** | System context, containers | | --- ## 1. Flowcharts ### When to Use Use flowcharts for: - Step-by-step guides and workflows (e.g., **"Onboarding process"**) - Decision trees and conditional logic (e.g., **"Discount calculation"**) - Process flows with multiple branches (e.g., **"Order fulfillment"**) - Troubleshooting procedures (e.g., **"Login issue diagnosis"**) ### Basic Flowchart ```mermaid flowchart TD Start([Start]) --> Input[Get Input] Input --> Check{Valid?} Check -->|Yes| Process[Process Data] Check -->|No| Error[Show Error] Process --> Output[Return Result] Output --> End([End]) Error --> End style Start fill:#2C3E50,stroke:#34495E,stroke-width:2px,color:#ECF0F1 style End fill:#27AE60,stroke:#229954,stroke-width:2px,color:#ECF0F1 style Check fill:#F39C12,stroke:#D68910,stroke-width:2px,color:#ECF0F1 style Error fill:#C0392B,stroke:#A93226,stroke-width:2px,color:#ECF0F1 style Process fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1 style Input fill:#34495E,stroke:#2C3E50,stroke-width:2px,color:#ECF0F1 style Output fill:#34495E,stroke:#2C3E50,stroke-width:2px,color:#ECF0F1 ``` **Explanation**: A basic flowchart starting with an input, followed by a validation check. If valid, it proceeds to processing and returns a result; otherwise, it shows an error and ends. **Code**: ````markdown ```mermaid flowchart TD Start([Start]) --> Input[Get Input] Input --> Check{Valid?} Check -->|Yes| Process[Process Data] Check -->|No| Error[Show Error] Process --> Output[Return Result] Output --> End([End]) Error --> End style Start fill:#2C3E50,stroke:#34495E,stroke-width:2px,color:#ECF0F1 style End fill:#27AE60,stroke:#229954,stroke-width:2px,color:#ECF0F1 style Check fill:#F39C12,stroke:#D68910,stroke-width:2px,color:#ECF0F1 style Error fill:#C0392B,stroke:#A93226,stroke-width:2px,color:#ECF0F1 ``` ```` ### Advanced Flowchart with Subgraphs ```mermaid flowchart LR A[Client Request] --> B{Auth?} B -->|No| C[401 Unauthorized] B -->|Yes| D[Process] subgraph Processing["Request Processing"] D --> E[Validate Input] E --> F[Execute Logic] F --> G[Format Response] end G --> H[Return 200 OK] C --> I[End] H --> I style Processing fill:#34495E,stroke:#2C3E50,stroke-width:2px,color:#ECF0F1 style A fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1 style B fill:#F39C12,stroke:#D68910,stroke-width:2px,color:#ECF0F1 style C fill:#C0392B,stroke:#A93226,stroke-width:2px,color:#ECF0F1 style D fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1 style E fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1 style F fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1 style G fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1 style H fill:#27AE60,stroke:#229954,stroke-width:2px,color:#ECF0F1 style I fill:#2C3E50,stroke:#34495E,stroke-width:2px,color:#ECF0F1 ``` **Explanation**: A flowchart featuring an authorization check and a dedicated **Subgraph** for detailed request processing steps. --- ## 2. Sequence Diagrams ### When to Use Use sequence diagrams for: - API communication flows (e.g., **"New order creation API"**) - Authentication/authorization flows (e.g., **"OAuth2 login flow"**) - Service-to-service interactions (e.g., **"Microservices sync/async calls"**) - Request/response cycles (e.g., **"Checkout process"**) ### Basic Sequence Diagram ```mermaid sequenceDiagram participant Client participant API participant Service participant DB Client->>API: POST /login API->>Service: authenticate(credentials) Service->>DB: findUser(email) DB-->>Service: user Service->>Service: verifyPassword() Service-->>API: JWT token API-->>Client: 200 OK {token} ``` **Explanation**: A login sequence illustrating the interaction between the Client, API, Service Layer, and Database, including password verification. **Code**: ````markdown ```mermaid sequenceDiagram participant Client participant API participant Service participant DB Client->>API: POST /login API->>Service: authenticate(credentials) Service->>DB: findUser(email) DB-->>Service: user Service->>Service: verifyPassword() Service-->>API: JWT token API-->>Client: 200 OK {token} ``` ```` ### Advanced with Alt/Opt/Loop ```mermaid sequenceDiagram participant Client participant API participant Cache participant DB Client->>API: GET /users/:id API->>Cache: get(key) alt Cache Hit Cache-->>API: cached data API-->>Client: 200 OK (from cache) else Cache Miss Cache-->>API: null API->>DB: SELECT * FROM users DB-->>API: user data API->>Cache: set(key, data, ttl) API-->>Client: 200 OK (from DB) end ``` **Explanation**: A data retrieval sequence using **Alt/Else** blocks to handle both Cache Hit and Cache Miss scenarios. --- ## 3. Class Diagrams ### When to Use Use class diagrams for: - Design patterns and code structure (e.g., **"Singleton Pattern for Logger"**) - Object-oriented architecture (e.g., **"Domain-Driven Design (DDD) models"**) - Inheritance and relationships (e.g., **"Repository base and concrete classes"**) - Module dependencies (e.g., **"Service layer dependencies"**) ### Basic Class Diagram ```mermaid classDiagram class BaseRepository { #prisma: PrismaClient #modelName: string +findById(id: string) T +findAll(options: QueryOptions) T[] +create(data: CreateDto) T +update(id: string, data: UpdateDto) T +delete(id: string) void } class UserRepository { +findByEmail(email: string) User +findByUsername(username: string) User } class FeatureRepository { +findByName(name: string) Feature +toggleStatus(id: string) Feature } BaseRepository <|-- UserRepository BaseRepository <|-- FeatureRepository ``` **Explanation**: A class diagram showing inheritance relationships between a generic `BaseRepository` and specific repository implementations. --- ## 4. Graph Diagrams ### When to Use Use graph diagrams for: - System architecture overview (e.g., **"Microservices Architecture"**) - Component relationships (e.g., **"Service-to-database mapping"**) - Data flow diagrams (e.g., **"Request processing pipeline"**) - Dependency graphs (e.g., **"Package to package dependencies"**) ### System Architecture ```mermaid graph TD Client[Web Client] --> Gateway[Traefik Gateway] Gateway --> Auth[Auth Service] Gateway --> IAM[IAM Service] Gateway --> User[User Service] Auth --> DB[(PostgreSQL)] IAM --> DB User --> DB User --> Cache[(Redis Cache)] style Client fill:#34495E,stroke:#2C3E50,stroke-width:2px,color:#ECF0F1 style Gateway fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1 style Auth fill:#8E44AD,stroke:#7D3C98,stroke-width:2px,color:#ECF0F1 style IAM fill:#8E44AD,stroke:#7D3C98,stroke-width:2px,color:#ECF0F1 style User fill:#8E44AD,stroke:#7D3C98,stroke-width:2px,color:#ECF0F1 style DB fill:#F39C12,stroke:#D68910,stroke-width:2px,color:#ECF0F1 style Cache fill:#E67E22,stroke:#CA6F1E,stroke-width:2px,color:#ECF0F1 ``` **Explanation**: A high-level view of the system architecture showing how the Gateway routes requests to different services, all connected to a shared Database and Cache. ### Data Flow ```mermaid graph LR Input[User Input] --> Validation[Zod Validation] Validation --> Controller[Controller] Controller --> Service[Service Layer] Service --> Repository[Repository] Repository --> Prisma[Prisma ORM] Prisma --> DB[(Database)] Service --> Cache[(Redis Cache)] style Input fill:#34495E,stroke:#2C3E50,stroke-width:2px,color:#ECF0F1 style Validation fill:#27AE60,stroke:#229954,stroke-width:2px,color:#ECF0F1 style Controller fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1 style Service fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1 style Repository fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1 style Prisma fill:#8E44AD,stroke:#7D3C98,stroke-width:2px,color:#ECF0F1 style DB fill:#F39C12,stroke:#D68910,stroke-width:2px,color:#ECF0F1 style Cache fill:#E67E22,stroke:#CA6F1E,stroke-width:2px,color:#ECF0F1 ``` **Explanation**: A detailed data flow showing Input going through Validation -> Controller -> Service -> Repository -> ORM -> DB, while also interacting with the Cache. --- ## 5. ER Diagrams ### When to Use Use ER diagrams for: - Database schema documentation (e.g., **"User and IAM tables"**) - Entity relationships (e.g., **"One-to-many between User and Sessions"**) - Data modeling (e.g., **"Designing new feature entities"**) - Prisma schema visualization (e.g., **"Mapping code entities to DB tables"**) ### Database Schema ```mermaid erDiagram User ||--o{ Session : has User ||--o{ RefreshToken : has User ||--o{ UserRole : has Role ||--o{ UserRole : has Role ||--o{ RolePermission : has Permission ||--o{ RolePermission : has User { string id PK string email UK string passwordHash boolean mfaEnabled datetime createdAt datetime updatedAt } Session { string id PK string userId FK string token UK string deviceId string ipAddress datetime expiresAt } Role { string id PK string name UK string description datetime createdAt } Permission { string id PK string code UK string resource string action string scope } ``` **Explanation**: An Entity-Relationship diagram illustrating a typical IAM schema with Users, Sessions, Roles, and Permissions. --- ## 6. Gantt Charts ### When to Use Use Gantt charts for: - Project timelines - Implementation phases - Migration schedules - Deployment plans ### Project Timeline ```mermaid gantt title Documentation Update Project Timeline dateFormat YYYY-MM-DD section Phase 1 Analysis & Research :done, p1, 2024-01-01, 1d section Phase 2 Templates & Strategy :active, p2, 2024-01-02, 0.5d section Phase 3 High Priority Docs :p3, 2024-01-03, 2d section Phase 4 Remaining Docs :p4, 2024-01-05, 3d section Phase 5 QA & Verification :p5, 2024-01-08, 1d ``` --- ## 7. C4 Diagrams ### When to Use Use C4 diagrams for: - System context (highest level) - Container diagrams (services, databases) - Component diagrams (modules within services) - Code diagrams (classes, functions) ### System Context ```mermaid C4Context title System Context Diagram for IAM System Person(user, "User", "System user needing authentication") Person(admin, "Admin", "System administrator") System(iam, "IAM System", "Identity and Access Management") System_Ext(email, "Email Service", "SendGrid/AWS SES") System_Ext(oauth, "OAuth Providers", "Google, Facebook, GitHub") Rel(user, iam, "Authenticates with", "HTTPS") Rel(admin, iam, "Manages users and permissions", "HTTPS") Rel(iam, email, "Sends emails", "SMTP/API") Rel(iam, oauth, "OAuth login", "OAuth 2.0") ``` --- ## Color Palette Reference ### Dark Theme Color System Our diagrams use a consistent dark color palette based on professional design principles: ```mermaid graph LR subgraph Primary[" Primary Colors"] A1["Dark Blue
#2980B9"] A2["Purple
#8E44AD"] A3["Green
#27AE60"] end subgraph Secondary[" Secondary Colors"] B1["Orange
#E67E22"] B2["Yellow
#F39C12"] B3["Red
#C0392B"] end subgraph Neutrals[" Neutral Colors"] C1["Dark Gray
#2C3E50"] C2["Medium Gray
#34495E"] C3["Light Text
#ECF0F1"] end style A1 fill:#2980B9,stroke:#1F618D,stroke-width:3px,color:#ECF0F1 style A2 fill:#8E44AD,stroke:#7D3C98,stroke-width:3px,color:#ECF0F1 style A3 fill:#27AE60,stroke:#229954,stroke-width:3px,color:#ECF0F1 style B1 fill:#E67E22,stroke:#CA6F1E,stroke-width:3px,color:#ECF0F1 style B2 fill:#F39C12,stroke:#D68910,stroke-width:3px,color:#ECF0F1 style B3 fill:#C0392B,stroke:#A93226,stroke-width:3px,color:#ECF0F1 style C1 fill:#2C3E50,stroke:#1C2833,stroke-width:3px,color:#ECF0F1 style C2 fill:#34495E,stroke:#2C3E50,stroke-width:3px,color:#ECF0F1 style C3 fill:#ECF0F1,stroke:#BDC3C7,stroke-width:3px,color:#2C3E50 ``` ### Color Usage Guidelines | Color | Hex Code | Use For | Example | |-------|----------|---------|---------| | **Dark Blue** | `#2980B9` | Services, Processing, APIs | User Service, API Gateway | | **Purple** | `#8E44AD` | Core Components, ORM | Prisma, IAM Service | | **Green** | `#27AE60` | Success, Validation, End States | Success Flow, Validated Data | | **Orange** | `#E67E22` | Cache, Warning States | Redis Cache, Warnings | | **Yellow** | `#F39C12` | Database, Important Decisions | PostgreSQL, Decision Nodes | | **Red** | `#C0392B` | Errors, Failures, Alerts | Error States, Failed Operations | | **Dark Gray** | `#2C3E50` | Start/End, Neutral Elements | Start Node, End Node | | **Medium Gray** | `#34495E` | Subgraphs, Background | Processing Groups, Containers | | **Light Text** | `#ECF0F1` | Text Color (always use) | All node text | ### Standard Style Pattern Always include these three properties for professional appearance: ```markdown style NodeName fill:#HexColor,stroke:#DarkerShade,stroke-width:2px,color:#ECF0F1 ``` **Components:** - `fill`: Main background color - `stroke`: Border color (typically darker shade of fill) - `stroke-width`: Border thickness (use `2px` for standard, `3px` for emphasis) - `color`: Text color (always use `#ECF0F1` for dark backgrounds) ### Node Type Color Patterns | Node Type | Fill Color | Stroke Color | Use Case | |-----------|------------|--------------|----------| | **Services** | `#2980B9` | `#1F618D` | Auth Service, User Service | | **API/Gateway** | `#2980B9` | `#1F618D` | Traefik, API Gateway | | **Database** | `#F39C12` | `#D68910` | PostgreSQL, MySQL | | **Cache** | `#E67E22` | `#CA6F1E` | Redis, Memcached | | **ORM/Framework** | `#8E44AD` | `#7D3C98` | Prisma, TypeORM | | **Success/End** | `#27AE60` | `#229954` | Success Flow, Completion | | **Error/Failure** | `#C0392B` | `#A93226` | Error States, Failures | | **Decision** | `#F39C12` | `#D68910` | Validation, Conditionals | | **Start** | `#2C3E50` | `#1C2833` | Entry Point | | **Process** | `#34495E` | `#2C3E50` | General Processing | ### Quick Color Selection Guide **Choose colors based on node function:** **Blue (`#2980B9`)** → Services, APIs, Controllers **Purple (`#8E44AD`)** → Core Systems, ORM, Frameworks **Green (`#27AE60`)** → Success, Validation, Completion **Orange (`#E67E22`)** → Cache, Memory, Storage **Yellow (`#F39C12`)** → Databases, Decisions, Important Actions **Red (`#C0392B`)** → Errors, Failures, Critical Issues **Dark Gray (`#2C3E50`)** → Start/End, Neutral States **Medium Gray (`#34495E`)** → Containers, Subgraphs, Groups --- ## Best Practices ### Guidelines 1. **Keep it Simple**: Don't overcomplicate diagrams 2. **Use Consistent Styling**: Apply color scheme consistently 3. **Add Legends**: Explain symbols and colors when needed 4. **Limit Complexity**: Break into multiple diagrams if too complex 5. **Test Rendering**: Always test diagrams render correctly 6. **Dark Theme**: Always use dark color palette for professional appearance 7. **Text Contrast**: Always use `color:#ECF0F1` for text on dark backgrounds --- ## Common Pitfalls ### Too Complex ```mermaid graph TD A --> B A --> C B --> D B --> E C --> F C --> G D --> H E --> H F --> I G --> I H --> J I --> J ``` ### Simplified with Subgraphs ```mermaid graph TD A[Start] --> B[Process A] B --> C[Process B] subgraph Detailed["Detailed Processing"] C --> D[Step 1] D --> E[Step 2] end E --> F[End] style Detailed fill:#34495E,stroke:#2C3E50,stroke-width:2px,color:#ECF0F1 style A fill:#2C3E50,stroke:#1C2833,stroke-width:2px,color:#ECF0F1 style F fill:#27AE60,stroke:#229954,stroke-width:2px,color:#ECF0F1 style B fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1 style C fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1 style D fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1 style E fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1 ``` --- ## Testing Diagrams Always test your diagrams before committing: ```bash # Install mermaid-cli npm install -g @mermaid-js/mermaid-cli # Test render (SVG) mmdc -i your-doc.md -o test-output.svg # Render high-quality PNG with dark theme mmdc -i your-doc.md -o test-output.png -b black -t dark -s 3 # Render ALL diagrams in a markdown file mmdc -i your-doc.md # Parameter Explanations: # -i: Input file (.md or .mmd) # -o: Output file (format based on extension .svg, .png, .pdf) # -b: Background color (hex code or color names like black, white, transparent) # -t: Theme (default, forest, dark, neutral) # -s: Scale (increase resolution, e.g., 3 for sharper images) ``` --- ## Quick Tips ### Mermaid Common Issues **Issue**: Diagram not rendering - Check for syntax errors (missing arrows, brackets) - Ensure proper indentation in subgraphs - Validate special characters are escaped **Issue**: Colors not applying - Place style commands after all node definitions - Use exact node IDs in style statements - Ensure hex colors include `#` prefix **Issue**: Text overlapping - Use shorter labels or `
` for line breaks - Adjust diagram direction (TD, LR, RL, BT) - Increase spacing between nodes ### Color Pattern Quick Reference ```markdown // Services & APIs style Node fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1 // Database style Node fill:#F39C12,stroke:#D68910,stroke-width:2px,color:#ECF0F1 // Cache style Node fill:#E67E22,stroke:#CA6F1E,stroke-width:2px,color:#ECF0F1 // Success/End style Node fill:#27AE60,stroke:#229954,stroke-width:2px,color:#ECF0F1 // Error/Failure style Node fill:#C0392B,stroke:#A93226,stroke-width:2px,color:#ECF0F1 // Decision Points style Node fill:#F39C12,stroke:#D68910,stroke-width:2px,color:#ECF0F1 // Start/Neutral style Node fill:#2C3E50,stroke:#1C2833,stroke-width:2px,color:#ECF0F1 ``` ### Visual Indicators Use emojis to enhance diagram readability: - Services & APIs - Core Systems - Success Paths - Databases - Cache/Storage - Errors - Neutral/Start/End - Warnings - Validated - Failed --- ## Resources - [Mermaid Official Documentation](https://mermaid.js.org/) - Complete reference - [Mermaid Live Editor](https://mermaid.live/) - Test diagrams online - [Mermaid CheatSheet](https://jojozhuang.github.io/tutorial/mermaid-cheat-sheet/) - Quick reference --- **Last Updated**: 2026-01-08