Why Diagrams-as-Code Matters

Image-based diagrams (exported PNGs from draw.io or Lucidchart) have a fundamental problem: they go stale. Nobody updates the diagram when the architecture changes because it requires opening the tool, editing, re-exporting, and re-uploading. Mermaid diagrams live as text in your repo — they get reviewed in pull requests, diff cleanly, and are updated alongside the code they describe.

Flowchart

Processes, decision trees, control flow, deployment pipelines

Sequence

API call flows, auth handshakes, microservice interactions

ER Diagram

Database schemas, entity relationships, data models

Gantt Chart

Project timelines, sprint planning, release schedules

Class Diagram

OOP class hierarchies, interface relationships

State Diagram

Finite state machines, UI states, order lifecycles

Flowcharts: The Workhorse

flowchart TD
    A([User submits form]) --> B{Validate input}
    B -->|Valid| C[Call Auth API]
    B -->|Invalid| D[Show field errors]
    C -->|Success| E[Store JWT in httpOnly cookie]
    C -->|401 - Bad credentials| F[Show login error]
    C -->|500 - Server error| G[Show retry message]
    E --> H([Redirect to dashboard])

Direction keywords: TD (top-down), LR (left-right), BT (bottom-top), RL (right-left). Node shapes: [] rectangle, () rounded, {} diamond (decision), (()) circle, ([ stadium. Edge labels go in |text| after the arrow.

Sequence Diagrams: API Flows Made Clear

sequenceDiagram
    autonumber
    participant C as Client App
    participant G as API Gateway
    participant A as Auth Service
    participant D as Database

    C->>G: POST /api/login {email, password}
    G->>A: validateCredentials(email, password)
    A->>D: SELECT user WHERE email = ?
    D-->>A: User record
    A->>A: bcrypt.compare(password, hash)
    A-->>G: {userId, roles}
    G->>G: sign JWT (HS256, 15min)
    G-->>C: 200 OK + Set-Cookie: token=...

    Note over C,G: Subsequent requests include cookie automatically

->> is a synchronous call (solid arrow). -->> is a response (dashed arrow). Note over A,B: adds an annotation spanning participants. autonumber adds step numbers to every arrow automatically.

Entity-Relationship Diagrams

erDiagram
    USER {
        string id PK
        string email UK
        string name
        string role
        datetime createdAt
    }
    ORDER {
        string id PK
        string userId FK
        decimal totalAmount
        string status
        datetime placedAt
    }
    ORDER_ITEM {
        string id PK
        string orderId FK
        string productId FK
        int quantity
        decimal unitPrice
    }
    PRODUCT {
        string id PK
        string name
        decimal price
        int stock
    }

    USER ||--o{ ORDER : "places"
    ORDER ||--|{ ORDER_ITEM : "contains"
    PRODUCT ||--o{ ORDER_ITEM : "included in"

Relationship notation: ||--|| (exactly one to exactly one), ||--o{ (one to zero-or-many), }|--|{ (one-or-more to one-or-more). PK, FK, UK labels mark key types.

State Diagrams: Order Lifecycle Example

stateDiagram-v2
    [*] --> Pending : Order placed
    Pending --> Confirmed : Payment verified
    Pending --> Cancelled : Payment failed / Timeout
    Confirmed --> Processing : Warehouse picks items
    Processing --> Shipped : Carrier collected
    Shipped --> Delivered : Confirmed delivery
    Shipped --> ReturnRequested : Customer files return
    Delivered --> ReturnRequested : Within return window
    ReturnRequested --> Refunded : Return received
    Cancelled --> [*]
    Delivered --> [*]
    Refunded --> [*]

GitHub and GitLab: Native Rendering

Both GitHub and GitLab render Mermaid diagrams natively in Markdown files, README.md, issues, and pull request descriptions. Simply wrap your diagram in a fenced code block with the mermaid language tag:

```mermaid
flowchart LR
    A --> B --> C
```

No plugins required on GitHub/GitLab. The diagram renders automatically for every visitor. This makes it ideal for architecture decision records (ADRs), onboarding docs, and API design specs checked directly into the repository.

✅ Best Practices for Production Diagrams
  • Keep diagrams focused — one concept per diagram. A 50-node flowchart helps nobody.
  • Use %% for comments within the diagram source: %% This path is deprecated
  • Name your diagram files descriptively: docs/auth-flow.md, docs/order-states.md
  • Review diagram changes in PRs alongside the code they document — requires updating together
  • For complex ER diagrams, only show the entities relevant to the feature being discussed