Mermaid Sequence Diagram Syntax
A Sequence diagram is an interaction diagram that shows how processes operate with one another and in what order.
Mermaid renders Sequence Diagrams natively from text syntax.
1. Basic Structure & Participants
Define participants using participant or actor keywords:
Syntax Code:
```mermaid
sequenceDiagram
autonumber
actor User as Student
participant Browser as Client Browser
participant Server as Web Server
participant DB as Database
User->>Browser: Click Submit
activate Browser
Browser->>Server: POST /api/submit
activate Server
Server->>DB: INSERT into records
activate DB
DB-->>Server: OK (id: 1042)
deactivate DB
Server-->>Browser: HTTP 200 Success
deactivate Server
Browser-->>User: Display Confirmation
deactivate Browser
```
2. Message Types & Arrows
| Type | Syntax | Description |
|---|---|---|
| Solid line without arrow | A->B: Text | Plain synchronous message |
| Solid line with arrowhead | A->>B: Text | Synchronous request |
| Dotted line with arrowhead | A-->>B: Text | Synchronous response / return value |
| Solid line with open arrow | A-)B: Text | Asynchronous event / notification |
| Dotted line with cross | A--xB: Text | Failed / dropped message |
3. Conditional Flow (alt / else / opt)
Use alt and else to model branching logic and conditional checks:
Syntax Code:
```mermaid
sequenceDiagram
autonumber
actor Client
participant Auth as Auth Service
participant Resource as Resource Service
Client->>Auth: Validate Token
Auth-->>Client: Token Valid?
alt Token is Valid
Client->>Resource: Fetch Protected Data
Resource-->>Client: 200 OK (Data payload)
else Token is Invalid / Expired
Client-->>Client: Log error
Client->>Resource: Denied
Resource-->>Client: 401 Unauthorized
end
```
4. Loops & Repetition
Use loop blocks to indicate repeated actions:
Syntax Code:
```mermaid
sequenceDiagram
actor Worker
participant Queue as Job Queue
participant Processor as Batch Processor
loop Every 5 seconds
Worker->>Queue: Poll for new jobs
Queue-->>Worker: Return pending jobs
opt When jobs exist
Worker->>Processor: Process batch
Processor-->>Worker: Completed
end
end
```
5. Asynchronous Events & Event Bus
To represent publish-subscribe patterns and message brokers: