Mermaid Sequence Diagram Syntax: A Comprehensive Technical Reference
Reserved Keywords and Comment Syntax
When defining nodes or labels in Mermaid sequence diagrams, certain terms require special handling. The keyword end serves as a structural terminator for blocks (loops, alts, opt, etc.). Using end as literal text without delimiters causes parsing errors. Encapsulate reserved terms using parentheses, quotation marks, or brackets: (end), "end", {end}, or [end].
Comments utilize double percent signs %% and must occupy dedicated lines. The parser ignores all content following %% until the line termination.
sequenceDiagram
Client->>Server: Request data
%% This comment explains the authentication step
Server-->>Client: Response (end)
Special characters employ HTML entity codes. For example, hearts use #9829;.
Participant Declaration
Define interacting entities using participant for standard objects or actor for human/role-based representations. Explicit declaration controls the visual ordering from left to right, overriding the default appearance-based sequencing.
sequenceDiagram
participant API as REST_API
actor Admin
participant DB as PostgreSQL
Admin->>API: POST /users
API->>DB: INSERT query
DB-->>API: Confirmation
API-->>Admin: 201 Created
Aliases improve readability using the as keyword. The declaration participant API as REST_API renders "REST_API" in the diagram while referencing "API" in code.
Dynamic Object Lifecycle
Version 10.3.0+ supports explicit creation and destruction of participants during runtime visualization. The create keyword instantiates objects mid-sequence, while destroy terminates them, displaying an X-mark at the lifeline endpoint.
sequenceDiagram
App->>Pool: Request connection
create participant Conn as Connection
Pool->>Conn: Initialize
Conn-->>App: Handle ready
App->>Conn: Execute query
Conn-->>App: Return results
App->>Pool: Release connection
destroy Conn
Pool-->>App: Acknowledge
Participant Grouping
Organize related entities into visual containers using box and end delimiters. Color specifications accept named colors, RGB values rgb(33,66,99), or transparency via transparent.
sequenceDiagram
box rgb(230,245,255) Authentication Layer
participant Auth
participant IdP
end
box rgb(255,245,230) Data Layer
participant Cache
participant DB
end
Client->>Auth: Validate token
Auth->>IdP: Verify JWT
IdP-->>Auth: Claims returned
Auth->>Cache: Check permissions
Cache-->>Auth: Cache miss
Auth->>DB: Query roles
Message Types and Arrow Syntax
Mermaid supports eight arrow variants representing different communication semantics:
| Syntax | Description |
|---|---|
-> |
Solid line without arrowhead |
--> |
Dashed line without arrowhead |
->> |
Solid line with arrowhead (synchronous) |
-->> |
Dashed line with arrowhead (return/response) |
-x |
Solid line with X (deletion/failure) |
--x |
Dashed line with X |
-) |
Solid line with hollow arrow (async) |
--) |
Dashed line with hollow arrow (async) |
sequenceDiagram
participant C as Client
participant S as Server
participant Q as Queue
C->>S: Synchronous call
S-->>C: Return value
C-)Q: Async event
Q--xC: Failure notice
C->>C: Self-processing
Lifeline Activation
Activation bars indicate when objects perform operations. Automatic activation occurs on message receipt, but manual control uses activate and deactivate keywords. Shorthand notation appends + (start) and - (end) to arrowheads, supporting nested activations.
sequenceDiagram
participant UI
participant Logic
participant Store
UI->>+Logic: Submit form
Logic->>+Store: Begin transaction
Store-->>-Logic: Transaction ID
Logic->>Store: Validate data
Store-->>Logic: Valid
Logic->>Logic: Compute checksum
Logic-->>-UI: Success response
Annotations and Notes
Add contextual explanations using note declarations. Positioning options include right of, left of, or over multiple participants. HTML line breaks <br/> format multi-line text.
sequenceDiagram
participant Browser
participant CDN
participant Origin
Browser->>CDN: GET /assets
note right of CDN: Edge cache check
CDN-->>Browser: Return cached content
note over Browser, CDN: Cache hit<br/>No origin request needed
Control Flow Structures
Loops: Repeat sequences using loop and end with descriptive labels.
sequenceDiagram
participant Poller
participant API
loop Every 30 seconds
Poller->>API: Health check
API-->>Poller: Status 200
end
Optional Paths: The opt block indicates conditional execution for single-branch scenarios.
sequenceDiagram
Client->>Server: Request resource
opt Requires authentication
Server->>Client: 401 Unauthorized
Client->>Server: Include token
end
Server-->>Client: Resource payload
Alternative Branches: The alt structure handles mutually exclusive condtiions with else delimiters.
sequenceDiagram
participant Validator
participant Processor
Validator->>Processor: Input data
alt Valid format
Processor->>Processor: Transform JSON
else Schema mismatch
Processor->>Processor: Log error
else Timeout
Processor->>Processor: Retry operation
end
Parallel Execution
The par keyword visualizes concurrent operations. Each branch within the block executes simultaneously, converging at the end terminator.
sequenceDiagram
participant Scheduler
participant WorkerA
participant WorkerB
Scheduler->>Scheduler: Distribute job
par Parallel processing
Scheduler->>WorkerA: Task chunk 1
WorkerA-->>Scheduler: Result A
and
Scheduler->>WorkerB: Task chunk 2
WorkerB-->>Scheduler: Result B
end
Scheduler->>Scheduler: Aggregate results
Critical Sections
The critical block denotes mutual exclusion zones where resource access requires serialization. This prevents race conditions in concurrent environments.
sequenceDiagram
participant T1 as Thread_1
participant T2 as Thread_2
participant File
critical File write lock
T1->>File: Open for writing
T1->>File: Append data
T1->>File: Close handle
end
note over File: Lock released
T2->>File: Read contents
Flow Interruption
The break statement terminates the current flow when preconditions fail, preventing subsequent message processing.
sequenceDiagram
participant Gateway
participant Service
Gateway->>Gateway: Parse request
alt Invalid signature
break Security violation
Gateway--xService: Reject connection
end
end
Gateway->>Service: Forward payload
Service-->>Gateway: Processed result
Background Highlighting
The rect keyword creates colored rectangular backgrounds spanning designated interactions. Color values support RGB rgb(255,0,0) or RGBA rgba(0,0,255,0.1) for transparency.
sequenceDiagram
participant Client
participant Gateway
participant Backend
Client->>Gateway: API request
rect rgb(240,248,255)
Gateway->>Backend: Authenticate
Backend-->>Gateway: Token validated
Gateway->>Backend: Route request
Backend-->>Gateway: JSON response
end
Gateway-->>Client: HTTP 200 OK
Automatic Sequence Numbering
Enable autonumber to prefix messages with incremental integers, facilitating step-by-step reference in documentation or debugging sessions.
sequenceDiagram
autonumber
participant Mobile
participant LoadBalancer
participant AppServer
Mobile->>LoadBalancer: HTTPS request
LoadBalancer->>AppServer: Proxy connection
AppServer-->>LoadBalancer: Session data
LoadBalancer-->>Mobile: Encrypted payload
Interactive Actor Menus
Associate clickable context menus with participants using link for individual entries or links for JSON-style multiple definitions. These render as dropdown menus in supported viewers.
sequenceDiagram
participant WebApp
participant AuthService
link WebApp: Dashboard @ https://monitor.example.com
link WebApp: Logs @ https://logs.example.com
links AuthService: {"Metrics": "https://metrics.io", "Docs": "https://docs.io"}
WebApp->>AuthService: Verify session
AuthService-->>WebApp: Claims payload