All posts
MermaidDocumentationBest PracticesCommunication

Mermaid Notes & Annotations: Document Diagram Intent & Context

6 min readThe MermaidCreator team

A diagram with great structure but no context leaves readers guessing: Why does this flow choose this path? What happens if this step fails? Is this synchronous or async? Mermaid's notes and annotations let you bake intent, rationale, and assumptions directly into the visual—so your diagram is complete without needing a separate explanation.

Why Annotations Matter

Good annotations:

  • Answer the "why" — document a decision boundary or rule in one sentence
  • Flag assumptions — mark async steps, parallel work, or dependencies
  • Provide examples — show a concrete input/output or edge case
  • Surface constraints — timeout, retry policy, or data format
  • Reduce cognitive load — readers understand the diagram without consulting external docs

Sequence Diagram Notes (Most Common)

Sequence diagrams are the home of annotations. Notes label interactions, highlight timing, and explain actor behavior.

Inline Notes

sequenceDiagram
    actor User
    participant Web as Web App
    participant Auth as Auth Service
    participant DB as Database

    User->>Web: Login Request
    
    Note over Web: Validate input (email format, password length)
    Web->>Auth: POST /auth/login
    
    Note over Auth: Bcrypt comparison (constant-time)
    Auth->>DB: Query user by email
    DB-->>Auth: User record
    Auth->>Auth: Compare hashed password
    
    Note over Auth,DB: Session created in cache (1 hour TTL)
    Auth-->>Web: JWT token
    
    Note over Web: Store in httpOnly cookie
    Web-->>User: Redirect to dashboard

Syntax:

  • Note over Actor: Text — single actor
  • Note over Actor1,Actor2: Text — spans multiple actors
  • Note left of Actor: Text — position left
  • Note right of Actor: Text — position right

Timing & Async Notes

sequenceDiagram
    participant Client
    participant Queue as Job Queue
    participant Worker

    Client->>Queue: Enqueue batch job
    Note over Queue: Async processing starts
    Queue-->>Client: Job ID (202 Accepted)
    
    Note right of Client: Client polls /jobs/{id} every 5s
    
    Queue->>Worker: Dispatch
    Note over Worker: Long-running task (may take minutes)
    
    Worker->>Worker: Process 10,000 records
    Worker-->>Queue: Mark complete
    
    Queue->>Client: Webhook: job complete
    Note over Client: Client cancels polling, updates UI

Use this for: pub-sub, async operations, long-running tasks.

Flowchart & State Diagram Annotations

Not all diagram types have native Note syntax, but you can annotate via comments and strategic labeling.

Comment Blocks (Flowchart)

flowchart TD
    Start([Request]) --> Validate
    
    %% Input validation layer
    Validate["Validate Schema"]
    Validate --> Format{Valid Format?}
    
    %% Rejection path
    Format -->|No| Reject["Reject (400)"]
    
    %% Core business logic
    Format -->|Yes| Enrich["Enrich with Context"]
    Enrich --> Process["Process"]
    
    %% Completion
    Process --> Success["Send 200 OK"]
    Reject --> End([Close])
    Success --> End
    
    style Validate fill:#e8f5e9
    style Process fill:#fff9c4
    style Success fill:#c8e6c9

Syntax:

  • %% Comment — adds a comment line (not rendered, helps maintainers)
  • Use comments to mark phases: %% Phase 1: Validation, %% Phase 2: Processing

Styled Labels for Emphasis

flowchart LR
    Start([Start]) --> Cache{Cache Hit?}
    
    Cache -->|Yes| CacheHit["<b>⚡ Return cached</b><br/>(0ms)"]
    Cache -->|No| Query["Query Database"]
    Query --> Network["<b>🌐 Network I/O</b><br/>(avg 150ms)"]
    
    CacheHit --> Response["Send Response"]
    Network --> Response
    Response --> End([End])

Use <b>, <br/>, and emoji to highlight critical paths, bottlenecks, or performance notes.

State Diagram Intent

stateDiagram-v2
    [*] --> Idle
    
    Idle --> Active: user_action
    
    note right of Idle
        Ready to accept input.
        Idle timeout = 30min.
    end note
    
    Active --> Processing: validate()
    
    note right of Processing
        Long-running task—up to 5min.
        If timeout, rollback and retry.
    end note
    
    Processing --> Idle: success
    Processing --> Error: failure
    
    Error --> Idle: reset()
    
    note right of Error
        Transient errors auto-retry.
        Permanent errors require user action.
    end note

Syntax:

  • note right of State: Text / note left of State: Text
  • Multi-line notes use end note

Best Practices for Annotations

1. Be Concise

Good:

Note over Auth: JWT expiry = 1 hour

Bad:

Note over Auth: The authentication token will expire after one hour from the time of issue, and the client will need to refresh it by calling the refresh endpoint.

2. Use Icons for Patterns

Async: 🔄, ⏱️
Error: ❌, ⚠️
Parallel: ⚡, 🔀
Caching: 💾, ⚙️
External: 🌐, 📡

sequenceDiagram
    Client->>API: GET /data
    Note over API: ⚙️ Check cache first
    API->>Cache: GET key
    Cache-->>API: Hit (3ms)
    Note over API: ⚡ Return immediately
    API-->>Client: 200 OK

3. Annotate Decision Points

flowchart TD
    Request --> Auth{Authenticated?}
    
    Auth -->|No| Challenge["Send Challenge"]
    Challenge --> Reject
    
    Auth -->|Yes| Role{Authorization: Viewer+?}
    Role -->|No| Forbidden["403 Forbidden"]
    Role -->|Yes| Allow["Grant Access"]

Add context above each diamond:

flowchart TD
    Request --> Auth
    
    Note over Auth, "User has valid JWT<br/>and proof of identity"
    Auth{Authenticated?}
    
    Auth -->|No| Challenge

4. Document Assumptions & Constraints

sequenceDiagram
    participant Client
    participant API as Payment API
    participant Bank as Bank

    Client->>API: POST /charge {amount, card}
    
    Note over API: Assumption: Card validated client-side<br/>Constraint: Max $10k per transaction<br/>SLA: Resolve in 30s
    
    API->>Bank: Route via Visa/MC network
    Bank-->>API: Success or decline
    API-->>Client: {"status": "success", "receipt_id": "..."}

Common Patterns

Retry Logic Annotation

sequenceDiagram
    App->>Service: Request (attempt 1)
    
    Note over Service: Timeout or 5xx
    Service-->>App: Error
    
    Note over App: Wait 1s, then retry
    App->>Service: Request (attempt 2)
    Service-->>App: Success

Caching & Invalidation

sequenceDiagram
    Client->>CDN: GET /asset
    Note over CDN: Cache TTL = 1 hour
    CDN-->>Client: 200 OK (cached)
    
    Admin->>Origin: Update asset
    Note over Origin: Cache invalidation webhook fired
    Origin->>CDN: Purge cache key
    CDN-->>Client: Cache expired

Cross-Service Communication

sequenceDiagram
    Order Service->>Inventory: Reserve quantity
    Note over Inventory: Transactional—all-or-nothing
    
    Inventory-->>Order Service: Reserved
    Order Service->>Payment: Charge
    
    Note over Payment: Async confirmation via webhook
    Payment-->>Order Service: 202 Accepted

Testing Annotations

Include test scenarios in diagrams so engineers know what should be tested:

flowchart TD
    Login["User Login"] --> Input{Validate Email}
    
    Input -->|Valid| Auth["Authenticate"]
    Input -->|Invalid| Error1["Show Error"]
    
    Note over Error1: "Test: invalid email formats (missing @, spaces, etc.)"
    
    Auth --> Check{Password Correct?}
    Check -->|No| Error2["Lock account after 3 attempts"]
    Check -->|Yes| Session["Create Session"]
    
    Note over Error2: "Test: account lockout + unlock flow"

FAQ

Can I add notes to class diagrams? Mermaid class diagrams don't have native note syntax, but you can use comments (%%) to document the class structure. For complex OOP diagrams, a sequence or flowchart companion is clearer.

Do notes appear in PNG/SVG exports? Yes, all notes render in exported images. Plan annotation placement accordingly if exporting for slides.

Should I annotate every decision? No—annotate only:

  • Non-obvious transitions
  • Business rules or domain constraints
  • Timing/performance-critical sections
  • Error handling or edge cases

Keep the diagram readable; too many notes is noise.

Can I reference external docs in notes? Yes, but use short references:

Note over Auth: See RFC 7235 for HTTP auth semantics

Then link to the doc separately in your knowledge base.

Master annotations and your diagrams become self-documenting. Start adding notes to existing diagrams—your teammates will immediately understand them better. Try building your next diagram in MermaidCreator's editor with annotations from day one.

Related posts