Sequence diagrams are one of the most effective tools for visualizing how objects or systems interact over time. Unlike flowcharts that focus on process steps, sequence diagrams emphasize the order of messages exchanged between participants. They are indispensable for API design, system architecture documentation, and debugging distributed systems.
Mermaid makes creating these diagrams remarkably simple. This tutorial walks you through everything from basic syntax to advanced features, with practical examples you can use immediately.
What Is a Sequence Diagram?
A sequence diagram illustrates the interactions between participants in a time-ordered sequence. It consists of four core elements:
- Participants: The entities involved in the interaction (users, services, databases).
- Lifelines: Vertical dashed lines representing a participant's existence over time.
- Messages: Horizontal arrows showing communication between participants.
- Activation Bars: Rectangles on lifelines indicating when a participant is actively processing.
If you have ever drawn a timeline of API calls or mapped out a user login flow, you have essentially created a sequence diagram mentally. Mermaid lets you formalize that mental model in code.
Basic Syntax
Every sequence diagram begins with the sequenceDiagram keyword.
Declaring Participants
Use the participant keyword to define actors in your diagram. Aliases make labels more readable.
sequenceDiagram
participant U as User
participant A as Auth Service
participant D as Database
For human users specifically, use actor to render a stick figure icon:
sequenceDiagram
actor Customer
participant API as Order API
participant DB as Order Database
Sending Messages
Messages follow the pattern Sender ->> Receiver: Message text.
sequenceDiagram
participant A as Client
participant B as Server
A ->> B: GET /api/users
B ->> A: 200 OK (JSON)
Message Arrow Types
Mermaid provides multiple arrow styles to distinguish message semantics.
| Syntax | Visual | Meaning |
|---|---|---|
->> | Solid arrow | Synchronous call |
-->> | Dashed arrow | Return message |
-> | Thin solid arrow | Asynchronous message |
--x | Dashed with X | Lost message |
-x | Solid with X | Destruction |
->>+ | Solid arrow + bar | Activates target participant |
->>- | Solid arrow - bar | Deactivates target participant |
Here is a complete example showing activation and deactivation:
sequenceDiagram
actor User
participant API
participant DB
User ->>+ API: Submit order
API ->>+ DB: INSERT order
DB -->>- API: Order ID returned
API ->>+ DB: UPDATE inventory
DB -->>- API: Stock updated
API -->>- User: Order confirmed
Notice how the + and - symbols automatically create and destroy activation bars, showing exactly when each system is busy processing.
Control Structures
Real-world interactions are rarely linear. Mermaid supports loops, conditions, and parallel execution.
Loops
Use loop to indicate repeated actions:
sequenceDiagram
participant C as Client
participant S as Server
C ->>+ S: Connect
loop Every 30 seconds
C ->> S: Heartbeat ping
S ->> C: Pong
end
C ->> S: Disconnect
deactivate S
Alternative Paths
Use alt for mutually exclusive branches, similar to if/else statements:
sequenceDiagram
actor U as User
participant A as App
participant P as Payment Gateway
U ->> A: Checkout
A ->> P: Charge $50
alt Payment successful
P -->> A: Transaction ID
A -->> U: Order confirmed
else Payment failed
P -->> A: Error: Insufficient funds
A -->> U: Show error, retry?
end
Optional Paths
Use opt for optional steps that may or may not occur:
sequenceDiagram
actor U as User
participant API
participant Cache
participant DB
U ->>+ API: Get profile
API ->>+ Cache: Lookup user:123
opt Cache miss
Cache ->>+ DB: SELECT * FROM users WHERE id=123
DB -->>- Cache: User row
Cache ->> Cache: Store in cache
end
Cache -->>- API: User data
API -->>- U: Profile JSON
Notes and Annotations
Add explanatory notes directly on the diagram to clarify intent:
sequenceDiagram
participant A as Client
participant B as Server
A ->> B: Request
Note over A,B: TLS 1.3 encrypted connection
B -->> A: Response
Note right of B: Response cached for 5 minutes
Note positioning options:
Note right of ParticipantNote left of ParticipantNote over Participant1,Participant2
Complete Real-World Example
Here is a production-grade sequence diagram for an e-commerce order placement flow:
sequenceDiagram
actor Customer
participant Cart
participant OrderAPI
participant Payment
participant Inventory
participant Notification
Customer ->> Cart: Proceed to checkout
Cart ->> OrderAPI: Create order draft
OrderAPI -->> Cart: Draft ID
Customer ->> OrderAPI: Submit order with payment
activate OrderAPI
OrderAPI ->> Payment: Authorize $120.00
alt Authorization approved
activate Payment
Payment -->> OrderAPI: Auth token ABC123
deactivate Payment
OrderAPI ->> Inventory: Reserve items
activate Inventory
Inventory -->> OrderAPI: Reservation confirmed
deactivate Inventory
OrderAPI ->> Payment: Capture funds
activate Payment
Payment -->> OrderAPI: Capture confirmed
deactivate Payment
OrderAPI ->> Notification: Send confirmation email
activate Notification
Notification -->> OrderAPI: Queued
deactivate Notification
OrderAPI -->> Customer: Order #98765 confirmed
else Authorization declined
activate Payment
Payment -->> OrderAPI: Declined: Invalid CVV
deactivate Payment
OrderAPI -->> Customer: Payment failed, please retry
end
deactivate OrderAPI
When to Use Sequence Diagrams vs. Flowcharts
| Scenario | Recommended Diagram | Reason |
|---|---|---|
| API design | Sequence diagram | Shows request/response timing and participants |
| User registration flow | Sequence diagram | Highlights system interactions per step |
| Business process approval | Flowchart | Focuses on decision points and branching |
| Algorithm logic | Flowchart | Better for step-by-step computation |
| Microservice communication | Sequence diagram | Visualizes cross-service calls and failures |
| UI navigation | Flowchart | Maps screen-to-screen transitions |
Pro Tips for Clean Sequence Diagrams
- Limit participants: More than six participants makes diagrams hard to follow. Split complex interactions into multiple focused diagrams.
- Use meaningful aliases:
AuthServiceis clearer thanA. - Align activations carefully: Ensure every
+has a matching-to prevent dangling activation bars. - Group related calls: Use
rectblocks to visually group related operations (e.g., authentication phase, data persistence phase). - Test your syntax: Invalid Mermaid syntax will fail silently on some platforms. Use Mermaid2img's live preview to validate before publishing.
Conclusion
Sequence diagrams are essential for communicating how systems interact over time. Mermaid's concise syntax lets you create these diagrams in code, making them versionable, editable, and perfectly suited for technical documentation.
Whether you are designing a new API, onboarding engineers to a microservice architecture, or documenting a critical user flow, sequence diagrams will help you communicate with precision.
Try creating your first sequence diagram now with Mermaid2img—paste your code, preview instantly, and export to PNG, SVG, or PDF.