Skip to content

Instantly share code, notes, and snippets.

@GingerGraham
Last active August 4, 2025 15:58
Show Gist options
  • Save GingerGraham/66a1e586fe2addbc6375b1fba1d2818c to your computer and use it in GitHub Desktop.
Save GingerGraham/66a1e586fe2addbc6375b1fba1d2818c to your computer and use it in GitHub Desktop.
A comprehensive starter guide for mermaid diagrams

Mermaid Fundamentals Tutorial

Table of Contents

Setup

How to set up Mermaid live preview in VS Code:

  • Install Required Extensions
    • Mermaid Markdown Syntax Highlighting (by bpruitt-goddard)
      • Provides syntax highlighting for Mermaid code blocks
    • Markdown Preview Mermaid Support (by Matt Bierner)
      • Enables Mermaid rendering in the built-in markdown preview
    • Mermaid Editor (by tomoyukim) - Optional but useful
      • Provides a dedicated Mermaid editor with live preview

Basic Setup

After installing the extensions, you can immediately preview Mermaid diagrams in markdown files:

  • Create or open a .md file
  • Add a Mermaid diagram:
```mermaid
flowchart TD
    A[Start] --> B[Process]
    B --> C[End]
```
  • Open the markdown preview: Ctrl+Shift+V or click the preview icon. The Mermaid diagram will render in the preview pane

Enhanced Workflow

For side-by-side editing and preview:

  • Open your markdown file
  • Use Ctrl+K V to open preview to the side
  • Edit your Mermaid code and see changes update live

Optional: Dedicated Mermaid Files If you installed the Mermaid Editor extension, you can work with .mmd files directly:

Create a file with .mmd extension Write pure Mermaid syntax (no markdown code blocks needed) Use Ctrl+Shift+P and search for "Mermaid: Preview" to open live preview

Basic Syntax Structure

All Mermaid diagrams follow this basic pattern:

diagramType
    diagram content here

The diagram type tells Mermaid what kind of diagram you're creating, and everything indented below defines the diagram structure.

Diagram Types

Core Diagram Types:

  • flowchart - Flowcharts and process diagrams
  • sequenceDiagram - Sequence/interaction diagrams
  • classDiagram - Class diagrams for object-oriented design
  • stateDiagram or stateDiagram-v2 - State transition diagrams
  • erDiagram - Entity relationship diagrams
  • gantt - Gantt charts for project timelines
  • pie - Pie charts
  • journey - User journey maps

Specialized Types:

  • graph - Legacy flowchart syntax (use flowchart instead)
  • mindmap - Mind maps
  • timeline - Timeline diagrams
  • sankey - Sankey diagrams for flow visualization
  • requirement - Requirements diagrams
  • quadrantChart - Quadrant/matrix charts
  • gitgraph - Git flow visualization
  • c4Context - C4 architecture diagrams (context level)

Note: Some of these have varying support across different Mermaid versions and renderers. The most reliable and widely supported are flowchart, sequenceDiagram, classDiagram, stateDiagram, erDiagram, gantt, and pie charts.

Adding Comments

You can add comments to document your diagrams using %% syntax:

flowchart TD
    %% This is a comment explaining the overall flow
    A[Start Process] --> B{Check Status}
    
    %% Decision branches
    B -->|Active| C[Continue Processing]
    B -->|Inactive| D[Send Alert]
    
    %% Final steps
    C --> E[Complete]
    D --> F[Log Error]
    
    %% Apply styling to make it look professional
    classDef errorClass fill:#ffebee,stroke:#d32f2f
    class D,F errorClass
Loading

Comments are useful for:

  • Explaining complex logic
  • Documenting styling choices
  • Adding TODO notes for future updates
  • Describing business rules or constraints

1. Flowcharts - Logic Flow Design

Basic Syntax

flowchart TD
    A --> B
    B --> C
Loading

Direction Options

  • TD or TB - Top Down
  • BT - Bottom Top
  • LR - Left Right
  • RL - Right Left

Node Shapes

flowchart TD
    A[Rectangle]
    B(Rounded)
    C([Stadium])
    D[[Subroutine]]
    E[(Database)]
    F((Circle))
    G{Diamond}
    H{{Hexagon}}
    I[/Parallelogram/]
    J[\Alt Parallelogram\]
Loading

Connecting Nodes

flowchart TD
    A --> B
    A --- C
    A -.-> D
    A ==> E
    A --o F
    A --x G
Loading

Labels on Connections

flowchart TD
    A -->|Yes| B
    A -->|No| C
    D -.->|maybe| E
    F ==>|always| G
Loading

Color Control

CSS Classes (Most Flexible)

flowchart TD
    A[Development] --> B[Testing]
    B --> C[Staging]
    C --> D[Production]
    
    classDef devClass fill:#e3f2fd,stroke:#1976d2,stroke-width:2px
    classDef testClass fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px
    classDef prodClass fill:#e8f5e8,stroke:#388e3c,stroke-width:2px
    
    class A devClass
    class B,C testClass
    class D prodClass
Loading

Direct Style Application

flowchart TD
    A[Node A] --> B[Node B]
    
    style A fill:#f9f,stroke:#333,stroke-width:4px
    style B fill:#bbf,stroke:#f66,stroke-width:2px,color:#fff
Loading

Position Control with Subgraphs

flowchart TD
    subgraph "Development Environment"
        A[Local Dev] --> B[Unit Tests]
    end
    
    subgraph "CI/CD Pipeline"
        C[Build] --> D[Integration Tests]
    end
    
    subgraph "Production"
        E[Live Environment]
    end
    
    B --> C
    D --> E
Loading

Practical Example - Deployment Pipeline

flowchart TD
    A[Code Commit] --> B{Tests Pass?}
    B -->|Yes| C[Build Image]
    B -->|No| D[Notify Developer]
    C --> E{Security Scan}
    E -->|Pass| F[Deploy to Staging]
    E -->|Fail| G[Block Deployment]
    F --> H[Run Integration Tests]
    H -->|Pass| I[Deploy to Production]
    H -->|Fail| J[Rollback]
Loading

2. Sequence Diagrams - System Interactions

Basic Syntax

sequenceDiagram
    participant A as User
    participant B as API
    participant C as Database
    
    A->>B: Request
    B->>C: Query
    C-->>B: Data
    B-->>A: Response
Loading

Message Types

  • A->>B: Solid arrow (synchronous)
  • A-->>B: Dashed arrow (asynchronous response)
  • A-xB: Cross ending (lost message)
  • A-)B: Open arrow

Activation Boxes

sequenceDiagram
    participant U as User
    participant A as API
    participant D as Database
    
    U->>+A: Login Request
    A->>+D: Validate Credentials
    D-->>-A: User Data
    A-->>-U: Login Success
Loading

Notes and Loops

sequenceDiagram
    participant A as Client
    participant B as Server
    
    Note over A,B: Authentication Flow
    
    A->>B: Connect
    loop Every 30 seconds
        A->>B: Heartbeat
        B-->>A: Ack
    end
    
    Note right of B: Connection maintained
Loading

3. Class Diagrams - Object Structure

Basic Class Definition

classDiagram
    class User {
        +String name
        +String email
        -String password
        +login()
        +logout()
        #validateEmail()
    }
Loading

Visibility Modifiers

  • + Public
  • - Private
  • # Protected
  • ~ Package/Internal

Relationships

classDiagram
    class Animal {
        +String name
        +makeSound()
    }
    
    class Dog {
        +bark()
    }
    
    class Cat {
        +meow()
    }
    
    class Owner {
        +String name
        +addAnimal()
    }
    
    Animal <|-- Dog
    Animal <|-- Cat
    Owner --> Animal : owns
Loading

Relationship Types

  • <|-- Inheritance (extends)
  • *-- Composition
  • o-- Aggregation
  • --> Association
  • -- Link (solid)
  • ..> Dependency
  • ..|> Realization
  • --|> Implementation

Note: Mermaid doesn't support UML cardinality notation like ||--o{. Use simple arrows with labels instead.

4. Git Flow Diagrams

Git graphs can be inconsistent in Mermaid across different versions. Here are reliable alternatives:

Simple Git Workflow (Process Flow)

flowchart TD
    A[main branch] --> B[create feature branch]
    B --> C[develop feature]
    C --> D[commit changes]
    D --> E{more work?}
    E -->|yes| C
    E -->|no| F[create PR]
    F --> G[code review]
    G --> H{approved?}
    H -->|no| I[address feedback]
    I --> G
    H -->|yes| J[merge to main]
    J --> K[delete feature branch]
Loading

Complex Git Branch Timeline

flowchart TD
    %% Main branch represents the stable production line
    M1[main: v1.0] --> M2[main: Config update]
    M2 --> M3[main: Hotfix merged]
    M3 --> M4[main: Feature A merged]
    M4 --> M5[main: Feature B merged]
    M5 --> M6[main: v1.1]
    
    %% Feature A: Authentication system
    %% Created early, developed in parallel
    M2 -.-> FA1[feature/auth: Start]
    FA1 --> FA2[feature/auth: Login UI]
    FA2 --> FA3[feature/auth: Backend API]
    FA3 --> FA4[feature/auth: Tests]
    FA4 -.-> M4  %% Merge back to main
    
    %% Feature B: Dashboard feature
    %% Started at same time but took longer
    M2 -.-> FB1[feature/dashboard: Start]
    FB1 --> FB2[feature/dashboard: Layout]
    FB2 --> FB3[feature/dashboard: Charts]
    FB3 -.-> M5  %% Merge back to main
    
    %% Critical hotfix that interrupts normal flow
    %% Gets priority and merges first
    M2 -.-> H1[hotfix/security: Start]
    H1 --> H2[hotfix/security: Fix]
    H2 -.-> M3  %% Emergency merge to main
    
    %% Styling for different branch types
    classDef mainBranch fill:#e1f5fe,stroke:#01579b,stroke-width:3px
    classDef featureBranch fill:#f3e5f5,stroke:#4a148c,stroke-width:2px
    classDef hotfixBranch fill:#fff3e0,stroke:#e65100,stroke-width:2px
    
    class M1,M2,M3,M4,M5,M6 mainBranch
    class FA1,FA2,FA3,FA4,FB1,FB2,FB3 featureBranch
    class H1,H2 hotfixBranch
Loading

Note: Solid arrows show commits within branches, dotted arrows show branch creation and merges.

5. State Diagrams - System States

stateDiagram-v2
    [*] --> Idle
    Idle --> Processing : start
    Processing --> Success : complete
    Processing --> Error : fail
    Success --> [*]
    Error --> Idle : retry
    Error --> [*] : abort
Loading

6. Entity Relationship Diagrams

erDiagram
    USER ||--o{ ORDER : places
    ORDER ||--|{ LINE-ITEM : contains
    PRODUCT ||--o{ LINE-ITEM : includes
    
    USER {
        int user_id PK
        string name
        string email
    }
    
    ORDER {
        int order_id PK
        int user_id FK
        date order_date
    }
Loading

Integration Tips

In Markdown Files

Simply wrap your Mermaid code in triple backticks with mermaid as the language:

```mermaid
flowchart TD
    A --> B
```

GitHub/GitLab

Both platforms render Mermaid diagrams automatically in markdown files, issues, and pull requests.

VS Code

Install the "Mermaid Markdown Syntax Highlighting" extension for syntax highlighting and preview.

Live Editor

Use mermaid.live to test and develop diagrams before adding them to your documentation.

Practical Infrastructure Example

flowchart TD
    subgraph "User Layer"
        U[Users]
    end
    
    subgraph "Load Balancing"
        LB[Application Load Balancer]
    end
    
    subgraph "Application Tier"
        A1[App Server 1]
        A2[App Server 2]
    end
    
    subgraph "Data Tier"
        DB[(Primary Database)]
        CACHE[(Redis Cache)]
    end
    
    U --> LB
    LB --> A1
    LB --> A2
    A1 --> DB
    A2 --> DB
    A1 --> CACHE
    A2 --> CACHE
    
    classDef userClass fill:#e3f2fd,stroke:#1976d2,stroke-width:2px
    classDef lbClass fill:#fff3e0,stroke:#f57c00,stroke-width:2px
    classDef appClass fill:#e8f5e8,stroke:#388e3c,stroke-width:2px
    classDef dataClass fill:#fce4ec,stroke:#c2185b,stroke-width:2px
    
    class U userClass
    class LB lbClass
    class A1,A2 appClass
    class DB,CACHE dataClass
Loading

Built-in Themes

Add this to the top of your diagram:

%%{init: {'theme':'dark'}}%%
flowchart TD
    A --> B
Loading

Available themes: default, dark, forest, neutral

Common Patterns for DevOps/Infrastructure

AWS Architecture

flowchart TD
    User[User] --> ALB[Application Load Balancer]
    ALB --> EC2A[EC2 Instance A]
    ALB --> EC2B[EC2 Instance B]
    EC2A --> RDS[(RDS Database)]
    EC2B --> RDS
    EC2A --> S3[S3 Bucket]
    EC2B --> S3
Loading

Terraform Workflow

flowchart TD
    A[terraform init] --> B[terraform plan]
    B --> C{Review Plan}
    C -->|Approve| D[terraform apply]
    C -->|Reject| E[Modify Code]
    E --> B
    D --> F[Infrastructure Created]
    F --> G[terraform destroy]
Loading

Additional Mermaid Diagram Types

State Diagrams - System States and Transitions

State diagrams show how a system changes between different states based on events or conditions.

Basic State Diagram

stateDiagram-v2
    [*] --> Idle
    Idle --> Processing : start_job
    Processing --> Success : job_complete
    Processing --> Failed : error_occurred
    Success --> [*]
    Failed --> Idle : retry
    Failed --> [*] : abort
Loading

Complex State Diagram - User Authentication

stateDiagram-v2
    [*] --> Unauthenticated
    
    Unauthenticated --> Authenticating : login_attempt
    Authenticating --> Authenticated : valid_credentials
    Authenticating --> Unauthenticated : invalid_credentials
    Authenticating --> Locked : max_attempts_exceeded
    
    Authenticated --> Unauthenticated : logout
    Authenticated --> SessionExpired : timeout
    SessionExpired --> Unauthenticated : confirm_logout
    SessionExpired --> Authenticated : refresh_token
    
    Locked --> Unauthenticated : admin_unlock
    
    note right of Locked
        Account locked after 3
        failed login attempts
    end note
Loading

State with Composite States

stateDiagram-v2
    [*] --> Active
    
    state Active {
        [*] --> Running
        Running --> Paused : pause
        Paused --> Running : resume
        Running --> Stopped : stop
        Paused --> Stopped : stop
    }
    
    Active --> Inactive : deactivate
    Inactive --> Active : activate
    Active --> [*] : terminate
Loading

Entity Relationship Diagrams - Database Design

ER diagrams show the relationships between entities in a database system.

Basic ER Diagram

erDiagram
    USER ||--o{ ORDER : places
    ORDER ||--|{ ORDER_ITEM : contains
    PRODUCT ||--o{ ORDER_ITEM : "ordered in"
    CATEGORY ||--o{ PRODUCT : categorizes
    
    USER {
        int user_id PK
        string username UK
        string email UK
        string password_hash
        datetime created_at
        datetime updated_at
    }
    
    ORDER {
        int order_id PK
        int user_id FK
        decimal total_amount
        string status
        datetime order_date
        datetime shipped_date
    }
    
    ORDER_ITEM {
        int order_item_id PK
        int order_id FK
        int product_id FK
        int quantity
        decimal unit_price
    }
    
    PRODUCT {
        int product_id PK
        int category_id FK
        string name
        text description
        decimal price
        int stock_quantity
        boolean is_active
    }
    
    CATEGORY {
        int category_id PK
        string name
        text description
        int parent_category_id FK
    }
Loading

Relationship Types in ER Diagrams

erDiagram
    %% Different relationship cardinalities
    CUSTOMER ||--o{ ORDER : "1 to many"
    ORDER ||--|| INVOICE : "1 to 1"
    PRODUCT }|--|| SUPPLIER : "many to 1"
    STUDENT }|--|{ COURSE : "many to many"
    
    CUSTOMER {
        int id PK
        string name
    }
    
    ORDER {
        int id PK
        int customer_id FK
    }
    
    INVOICE {
        int id PK
        int order_id FK
    }
    
    PRODUCT {
        int id PK
        int supplier_id FK
    }
    
    SUPPLIER {
        int id PK
        string name
    }
    
    STUDENT {
        int id PK
        string name
    }
    
    COURSE {
        int id PK
        string title
    }
Loading

User Journey Maps - User Experience Flow

Journey diagrams show the steps a user takes to accomplish a task, including their emotions and pain points.

Basic User Journey

journey
    title User Shopping Journey
    section Discovery
      Visit homepage: 5: User
      Browse categories: 4: User
      Search for product: 3: User
      View product details: 4: User
    section Purchase
      Add to cart: 5: User
      Review cart: 3: User
      Enter shipping info: 2: User
      Enter payment info: 1: User
      Confirm order: 3: User
    section Post-Purchase
      Receive confirmation: 4: User
      Track shipment: 5: User
      Receive product: 5: User
      Leave review: 3: User
Loading

Multi-Actor Journey

journey
    title Software Development Lifecycle
    section Planning
      Define requirements: 3: Product Manager, Developer
      Create user stories: 4: Product Manager
      Estimate effort: 2: Developer, Tech Lead
    section Development
      Write code: 5: Developer
      Code review: 3: Tech Lead, Developer
      Run tests: 4: Developer
    section Deployment
      Deploy to staging: 3: DevOps, Developer
      QA testing: 2: QA Engineer
      Deploy to production: 4: DevOps
    section Monitoring
      Monitor metrics: 5: DevOps
      User feedback: 3: Product Manager
Loading

Pie Charts - Data Visualization

Pie charts show proportional data as slices of a circle.

Basic Pie Chart

pie title Server Resource Usage
    "CPU" : 35
    "Memory" : 25
    "Storage" : 30
    "Network" : 10
Loading

Project Time Allocation

pie title Development Time Breakdown
    "Frontend Development" : 40
    "Backend APIs" : 30
    "Database Design" : 15
    "Testing" : 10
    "Documentation" : 5
Loading

Infrastructure Costs

pie title Monthly AWS Costs
    "EC2 Instances" : 45
    "RDS Database" : 25
    "S3 Storage" : 15
    "Load Balancers" : 10
    "CloudWatch/Monitoring" : 5
Loading

Gantt Charts - Project Timeline Management

Gantt charts show project tasks over time, including dependencies and progress.

Basic Project Gantt

gantt
    title Web Application Development
    dateFormat  YYYY-MM-DD
    section Planning
    Requirements Analysis    :done,    req, 2024-01-01, 2024-01-15
    System Design          :done,    design, after req, 10d
    section Development
    Database Setup         :active,  db, 2024-01-20, 2024-01-25
    Backend API           :         api, after db, 20d
    Frontend Development  :         ui, after db, 25d
    section Testing
    Unit Testing          :         test1, after api, 5d
    Integration Testing   :         test2, after ui, 10d
    section Deployment
    Staging Deployment    :         stage, after test2, 3d
    Production Deployment :         prod, after stage, 2d
Loading

Complex Project with Dependencies

gantt
    title Infrastructure Migration Project
    dateFormat  YYYY-MM-DD
    section Phase 1: Assessment
    Current State Analysis     :done, analysis, 2024-02-01, 2024-02-10
    Risk Assessment           :done, risk, 2024-02-05, 2024-02-15
    Migration Strategy        :done, strategy, after risk, 5d
    
    section Phase 2: Preparation
    Setup Target Environment  :active, setup, 2024-02-20, 2024-03-05
    Data Migration Scripts    :        scripts, after analysis, 15d
    Testing Framework        :        testing, after setup, 10d
    
    section Phase 3: Migration
    Pilot Migration          :        pilot, after scripts, 5d
    Full Data Migration      :        migrate, after pilot, 3d
    Application Cutover      :        cutover, after migrate, 1d
    
    section Phase 4: Validation
    System Validation        :        validate, after cutover, 5d
    Performance Testing      :        perf, after validate, 7d
    User Acceptance Testing  :        uat, after perf, 10d
    
    section Phase 5: Go-Live
    Production Deployment    :        golive, after uat, 2d
    Monitoring Setup         :        monitor, after golive, 3d
    Documentation           :        docs, after golive, 7d
Loading

Development Sprint Gantt

gantt
    title Sprint 23 - User Authentication Feature
    dateFormat  YYYY-MM-DD
    
    section Sprint Planning
    Sprint Planning Meeting   :done, planning, 2024-03-01, 1d
    
    section Backend Development
    User Model Creation      :done, model, 2024-03-02, 2d
    Authentication API       :active, auth-api, after model, 3d
    Password Reset Feature   :        reset, after auth-api, 2d
    
    section Frontend Development
    Login Page UI           :done, login-ui, 2024-03-02, 2d
    Registration Form       :active, reg-form, after login-ui, 3d
    User Profile Page       :        profile, after auth-api, 3d
    
    section Testing & QA
    Unit Tests             :        unit, after reset, 2d
    Integration Tests      :        integration, after profile, 2d
    Manual QA Testing      :        qa, after integration, 2d
    
    section Sprint Review
    Demo Preparation       :        demo-prep, after qa, 1d
    Sprint Review Meeting  :        review, after demo-prep, 1d
    Sprint Retrospective   :        retro, after review, 1d
Loading

Usage Tips

State Diagrams:

  • Use for modeling system behavior, user workflows, or application states
  • Great for documenting state machines in your code
  • Useful for API status flows

ER Diagrams:

  • Essential for database design documentation
  • Use relationship notation: ||--o{ (one-to-many), ||--|| (one-to-one), }|--|{ (many-to-many)
  • Include field types and constraints

Journey Maps:

  • Document user experience flows
  • Numbers (1-5) represent satisfaction/ease levels
  • Great for identifying pain points in processes

Pie Charts:

  • Keep to 5-7 slices maximum for readability
  • Good for showing proportional data
  • Useful in reports and dashboards

Gantt Charts:

  • Use dateFormat to specify your date format
  • Status options: done, active, crit (critical)
  • Dependencies with after taskname syntax
  • Great for project planning and tracking

Acknowledgements

Developed with the assistance of Claude AI to help me understand and implement Mermaid diagrams effectively.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment