Skip to content

Mermaid Cheatsheet

Published: March 13, 2026

A practical reference for Mermaid diagram syntax — the five diagram types you actually use in documentation.

The 30-Second Version

markdown
```mermaid
graph LR
  A[Request] --> B[Service]
  B --> C[(Database)]
  C --> B
  B --> A
```

Mermaid diagrams live in fenced code blocks with the mermaid language identifier. They render automatically in VitePress, GitHub, GitLab, and most documentation platforms.

Flowchart

The most common diagram type. Use graph or flowchart followed by a direction.

Directions

KeywordFlow
TB / TDTop to bottom
BTBottom to top
LRLeft to right
RLRight to left

Node Shapes

SyntaxShapeUse for
A[text]RectangleServices, components
A(text)Rounded rectangleProcesses, actions
A([text])StadiumBroad categories
A[[text]]SubroutineExternal systems
A[(text)]CylinderDatabases, storage
A((text))CircleEvents, start/end
A{text}DiamondDecisions, conditions
AHexagonSetup steps
See rendered shapes

Edge Types

SyntaxStyle
-->Solid arrow
---Solid line (no arrow)
-.->Dotted arrow
==>Thick arrow
<-->Bidirectional
-->|label|Arrow with label
-- label -->Arrow with label (alt)

Chaining: A --> B --> C draws A to B to C in one line.

Branching: A --> B & C draws edges from A to both B and C.

Subgraphs

markdown
```mermaid
graph TB
    subgraph api["API Layer"]
        direction LR
        REST[REST] --> GQL[GraphQL]
    end
    subgraph db["Data Layer"]
        PG[(PostgreSQL)]
    end
    api --> db
```
See rendered diagram

Subgraphs can have their own direction. Edges can connect to subgraphs directly.

WARNING

If any node inside a subgraph links to an outside node, the subgraph's direction is ignored.

Styling

classDef primary fill:#7c4dff,stroke:#333,color:#fff
A:::primary --> B

Apply classes with :::className after a node. Use classDef default for all unstyled nodes.

Style individual links by index: linkStyle 0 stroke:#ff3,stroke-width:2px

TIP

Keep styling minimal. The rendering theme handles colors. Only use classDef to distinguish categories (e.g., external vs internal services).

Gotchas

  • The word end in lowercase breaks the parser — use End or END
  • Node IDs starting with o or x can be misread as edge markers — capitalize them
  • Special characters in labels need quotes: A["Label with (parens)"]

Sequence Diagram

Best for request/response flows and multi-service interactions.

markdown
```mermaid
sequenceDiagram
    participant C as Client
    participant S as Server
    participant DB as Database
    C->>+S: POST /orders
    S->>DB: INSERT order
    DB-->>S: order_id
    S-->>-C: 201 Created
```
See rendered diagram

Participants

SyntaxMeaning
participant A as LabelBox (system/service)
actor A as LabelStick figure (human)

Order in the diagram follows declaration order.

Message Types

SyntaxStyle
->>Solid arrow (sync call)
-->>Dotted arrow (response)
-)Open arrow (async, fire-and-forget)
--)Dotted open arrow (async response)
-xSolid with X (failed)
--xDotted with X (failed response)

Activations

Show when a participant is processing:

C->>+S: Request      %% + activates S
S-->>-C: Response    %% - deactivates S

Or use explicit activate S / deactivate S blocks.

Control Flow

alt Success
    A->>B: 200 OK
else Failure
    A->>B: 500 Error
end

opt If cached
    A->>B: Return cache
end

par Task 1
    A->>B: Request 1
and Task 2
    A->>C: Request 2
end

loop Every 30s
    A->>B: Heartbeat
end
BlockPurpose
alt / else / endConditional branches
opt / endOptional step
par / and / endParallel execution
loop / endRepeated action
critical / option / endCritical section with fallback
break / endBreak out of a flow

Notes

Note right of A: Side note
Note over A,B: Spans both participants

Numbering

Add autonumber after sequenceDiagram to auto-number all messages.

State Diagram

Best for lifecycle flows, status machines, and workflow stages. Always use stateDiagram-v2.

markdown
```mermaid
stateDiagram-v2
    [*] --> Draft
    Draft --> Review: submit
    Review --> Published: approve
    Review --> Draft: reject
    Published --> [*]
```
See rendered diagram
  • [*] represents start and end states
  • Labels go after : on transitions

Composite States

markdown
```mermaid
stateDiagram-v2
    state Review {
        [*] --> PeerReview
        PeerReview --> TechReview
        TechReview --> [*]
    }
```
See rendered diagram

Special State Types

state decision <<choice>>
state fork_point <<fork>>
state join_point <<join>>
TypeSyntaxUse for
Choice<<choice>>Conditional branching
Fork<<fork>>Split into parallel
Join<<join>>Rejoin parallel paths

Concurrency

Use -- inside a composite state to show parallel regions:

state Active {
    [*] --> Processing
    --
    [*] --> Monitoring
}

Notes

note right of Draft: Initial state
note right of Review
    Requires human
    approval
end note

Class Diagram

Best for domain models, type hierarchies, and API schemas.

markdown
```mermaid
classDiagram
    class Order {
        +String id
        +OrderStatus status
        +place()
        +confirm()
    }
    class OrderItem {
        +String productId
        +int quantity
    }
    Order "1" --> "*" OrderItem : contains
```
See rendered diagram

Visibility

SymbolMeaning
+Public
-Private
#Protected
~Package/internal

Methods use parentheses (+place()), attributes do not (+String id).

Suffixes: * = abstract, $ = static.

Relationships

SyntaxType
A <|-- BInheritance (B extends A)
A *-- BComposition (lifecycle bound)
A o-- BAggregation (independent lifecycle)
A <-- BAssociation
A <.. BDependency
A ..|> BRealization (implements)

Add cardinality: A "1" --> "*" B : label

Annotations & Generics

class Shape {
    <<interface>>
    +draw() void
}
class List~T~ {
    +add(T item)
}

Use ~T~ for generics — not <T>.

Common annotations: <<interface>>, <<abstract>>, <<service>>, <<enumeration>>.

Entity Relationship Diagram

Best for database schemas and data models. Uses crow's foot notation.

markdown
```mermaid
erDiagram
    CUSTOMER ||--o{ ORDER : places
    ORDER ||--|{ LINE_ITEM : contains
    ORDER {
        int id PK
        string status
        date created_at
    }
```
See rendered diagram

Cardinality Markers

Each side has two characters: outer = maximum, inner = minimum.

MarkerMeaning
||Exactly one
o|Zero or one
|{One or more
o{Zero or more

Relationship Lines

SyntaxType
--Identifying (solid line) — child can't exist without parent
..Non-identifying (dashed line) — independent entities

Attributes

Format: type name [PK\|FK\|UK] ["comment"]

CUSTOMER {
    int id PK
    string email UK "must be unique"
    string name
}

TIP

Relationship labels are required — always include : label at the end.

Quick Reference

TaskSyntax
Flowchart (horizontal)graph LR
Flowchart (vertical)graph TD
Sequence diagramsequenceDiagram
State diagramstateDiagram-v2
Class diagramclassDiagram
ER diagramerDiagram
Sync message->>
Async message-)
Response-->>
Subgraphsubgraph id ["Title"] ... end
Style a nodeA:::className
Define a classclassDef name fill:#fff,stroke:#333
Comment%% comment text
Direction inside subgraphdirection LR