Mermaid Sequence Diagram Guide: From Beginner to Pro
Sequence diagrams explain how people, services, and data stores interact over time. They are especially useful for API request lifecycles, authentication, background jobs, microservice orchestration, and failure analysis because the order of each interaction is visible.
This guide moves from Mermaid's core sequence syntax to production-ready patterns. You will learn how to model actors, messages, activation, conditions, parallel work, critical regions, and dynamically created participants, then combine those ideas in a practical API example.
Why Use Mermaid for Sequence Diagrams?
Mermaid stores a diagram as readable text, so it fits naturally in Markdown, code review, and version control. A short login flow already communicates the participants, direction, and result:
sequenceDiagram
actor User
participant Web as Web App
participant API
participant DB as Database
User->>Web: Submit credentials
Web->>API: POST /sessions
API->>DB: Find user
DB-->>API: User record
API-->>Web: Session token
Web-->>User: Show dashboard
Use a sequence diagram when order matters. If you primarily need to explain a decision tree or business process, a Mermaid flowchart may be clearer. If you need strict UML coverage or extensive styling, compare Mermaid and PlantUML for sequence diagrams.
Basic Structure
Every Mermaid sequence diagram begins with sequenceDiagram. Participants appear horizontally, time moves downward, and each message adds a new step.
sequenceDiagram
participant Browser
participant API
Browser->>API: GET /profile
API-->>Browser: 200 OK
Indentation is optional but helps reviewers understand nested blocks. Put one interaction on each line and choose aliases that match the vocabulary used in your code and documentation.
Participants and Actors
Declare a system component with participant and a person or external role with actor. An alias keeps the source concise while the diagram displays a descriptive label.
sequenceDiagram
actor C as Customer
participant UI as Checkout UI
participant Orders as Order Service
participant DB as Orders Database
C->>UI: Confirm order
UI->>Orders: POST /orders
Orders->>DB: Insert order
Explicit declarations also control left-to-right order. Declare the primary actor first, then arrange internal services in the approximate direction of the request. Avoid generic names such as System1 when Inventory Service would tell the reader more.
For a large architecture, group related participants with box:
sequenceDiagram
actor User
box Web tier
participant UI as Web App
participant BFF as Backend for Frontend
end
box Data tier
participant API as Profile Service
participant DB as Profile Database
end
User->>UI: Open profile
UI->>BFF: Load profile
BFF->>API: GET /profiles/me
API->>DB: Read profile
Message Types and Activations
Arrow styles describe the intent of a message. Use them consistently instead of treating every interaction as the same kind of call.
| Syntax | Meaning | Typical use |
|---|---|---|
->> | Solid line with arrowhead | Synchronous request or command |
-->> | Dashed line with arrowhead | Return value or response |
-) | Solid line with open arrowhead | Asynchronous event or queued work |
--x | Dashed line ending in a cross | Failed delivery or rejected response |
sequenceDiagram
participant Client
participant API
participant Queue
Client->>API: POST /reports
API-)Queue: Enqueue report job
API-->>Client: 202 Accepted
Activations show how long a participant is processing work. Use activate and deactivate, or the compact + and - markers:
sequenceDiagram
Client->>+API: POST /orders
API->>+DB: Insert order
DB-->>-API: Order ID
API-->>-Client: 201 Created
Keep activation pairs balanced. Unclosed activations make the rendered lifeline misleading and often signal that a response or exit path is missing from the source.
Number Messages with autonumber
Add autonumber immediately after sequenceDiagram when people will discuss steps in a review, ticket, or incident report. Mermaid numbers messages in render order, including messages inside conditions.
sequenceDiagram
autonumber
Client->>API: POST /exports
API->>DB: Save export request
DB-->>API: Export ID
API-->>Client: 202 Accepted
Automatic numbering is easier to maintain than typing numbers into labels. If an interaction moves, every later number updates with it.
Add Context with Notes
Notes record constraints that affect the interaction but are not separate messages. Place a note to the left or right of one participant, or span several participants with over.
sequenceDiagram
Client->>API: POST /payments
Note right of API: Idempotency key required
API->>Gateway: Authorize payment
Note over Client,Gateway: Request timeout: 10 seconds
Use notes sparingly. If a note becomes a paragraph, link the diagram to the detailed design decision instead of shrinking the whole chart around explanatory text.
Conditional and Repeated Flows
alt and else
Use alt for mutually exclusive outcomes. Add one or more else branches and close the block with end.
sequenceDiagram
Client->>API: Request protected resource
alt Token is valid
API-->>Client: 200 OK
else Token is expired
API-->>Client: 401 Unauthorized
end
opt
Use opt when a step may happen but does not need an alternative branch.
sequenceDiagram
User->>Profile: Save settings
opt Email address changed
Profile-)Email: Send verification message
end
Profile-->>User: Settings saved
loop
Use loop for retries, polling, pagination, or work repeated for every item. Put the stopping rule in the label.
sequenceDiagram
Worker->>API: Fetch job status
loop Every 2 seconds until complete
Worker->>API: GET /jobs/42
API-->>Worker: Current status
end
par and and
Use par when independent interactions can occur concurrently. Start additional branches with and.
sequenceDiagram
Gateway->>Orders: Confirm order
par Reserve inventory
Orders->>Inventory: Reserve items
Inventory-->>Orders: Reserved
and Notify customer
Orders-)Email: Queue confirmation
and Record analytics
Orders-)Events: Publish OrderConfirmed
end
Only use par for genuinely independent work. If one call requires the result of another, show them sequentially so the diagram does not promise concurrency the implementation cannot provide.
Critical Regions, Breaks, and Background Grouping
Use critical for work that must complete as one protected region. option documents alternative failure handling inside that region.
sequenceDiagram
Checkout->>Payments: Confirm payment
critical Persist a single payment result
Payments->>DB: Commit payment record
DB-->>Payments: Committed
option Database unavailable
Payments->>Queue: Store recovery event
end
Payments-->>Checkout: Final payment status
A break block ends the normal interaction when its condition is met. It is useful for validation failures, circuit breakers, and unrecoverable responses.
sequenceDiagram
Client->>API: POST /orders
API->>Inventory: Check stock
Inventory-->>API: Availability
break Product is unavailable
API-->>Client: 409 Out of stock
end
API->>Payments: Authorize payment
Use rect to give a related group of messages a subtle background. This can separate phases without adding another participant:
sequenceDiagram
Client->>API: Start checkout
rect rgb(239, 246, 255)
API->>Inventory: Reserve items
Inventory-->>API: Reservation ID
API->>Payments: Authorize total
Payments-->>API: Authorization ID
end
API-->>Client: Checkout ready
Prefer one or two meaningful regions. Too many colors and nested blocks compete with the message order, which should remain the primary signal.
Create and Destroy Participants
Some participants exist only during the interaction, such as a temporary worker, session, or container. Use create participant before its first message and destroy when its lifetime ends.
sequenceDiagram
participant API
participant Queue
API->>Queue: Submit export job
create participant Worker as Export Worker
Queue->>Worker: Deliver job
Worker->>Worker: Generate archive
Worker-->>API: Export ready
destroy Worker
Worker-xQueue: Job complete
Dynamic lifecycles are most useful when creation or termination is important to the design. Do not use them merely to shorten a lifeline.
Practical API Example: Idempotent Order Creation
The following example combines aliases, automatic numbering, activation, a parallel branch, retry logic, and success or failure outcomes. It models an API that creates an order, reserves stock, authorizes payment, and publishes follow-up work.
sequenceDiagram
autonumber
actor C as Customer
participant UI as Checkout UI
participant API as Order API
participant DB as Orders DB
participant Stock as Inventory API
participant Pay as Payment Gateway
participant Events as Event Bus
C->>UI: Confirm purchase
UI->>+API: POST /orders (Idempotency-Key)
API->>DB: Find order by key
DB-->>API: No existing order
par Validate inventory
API->>+Stock: Reserve items
Stock-->>-API: Reservation ID
and Create pending order
API->>DB: Insert pending order
DB-->>API: Order ID
end
API->>+Pay: Authorize total
alt Payment approved
Pay-->>-API: Authorization ID
API->>DB: Mark order confirmed
API-)Events: Publish OrderConfirmed
API-->>-UI: 201 Created
UI-->>C: Show confirmation
else Temporary gateway error
loop Up to 2 retries
API->>Pay: Retry authorization
Pay-->>API: Gateway status
end
deactivate Pay
API->>DB: Mark order pending review
API-->>-UI: 202 Accepted
UI-->>C: Show processing status
else Payment declined
Pay-->>-API: Decline reason
API->>Stock: Release reservation
API->>DB: Mark order failed
API-->>-UI: 422 Payment declined
UI-->>C: Request another payment method
end
This diagram deliberately focuses on the order-creation story. Fraud checks, email delivery, and fulfillment can each have a separate diagram. Keeping those concerns separate makes failures easier to reason about and updates easier to review.
Troubleshooting Mermaid Sequence Diagrams
The diagram does not render
- Confirm the first line is
sequenceDiagram. - Check that every
alt,opt,loop,par,critical,break,rect, andboxhas a matchingend. - Verify that message arrows use supported characters and that the sender and receiver both have names.
- Remove the most recently added block, preview again, and restore it one interaction at a time.
Labels or participants are hard to read
- Give long service names short aliases, such as
participant Billing as Subscription Billing Service. - Shorten message labels to an action and move protocol details into a note or linked document.
- Split one large diagram into a happy-path diagram and one or more failure-path diagrams.
Activations continue too far
Match each + with a later -, including every conditional exit. For complicated branches, explicit activate Service and deactivate Service lines may be easier to audit than shorthand.
The rendered order is surprising
Declare participants explicitly in the desired left-to-right order. Then review nested par and alt blocks from top to bottom; Mermaid follows source order even when calls are conceptually concurrent.
Preview changes in the OnUML editor before publishing. A small rendering check catches missing end statements and overly long labels before they reach documentation.
Maintaining Sequence Diagrams
Treat diagram source like code:
- Keep it beside the API specification, architecture decision, or feature document it explains.
- Use participant names that map to real services, modules, or external actors.
- Update the diagram in the same change that updates an endpoint or event contract.
- Ask reviewers to verify both the happy path and the most important failure path.
- Remove details that no longer influence the reader's decision.
Text-based diagrams are easy to diff, but a syntactically valid diff can still describe outdated behavior. Add an owner or review date to important architecture documentation, and validate the diagram during incident reviews or major interface changes.
Frequently Asked Questions
What is the difference between a participant and an actor?
Both can send and receive messages. actor visually identifies a person or external role, while participant is the usual choice for an application, service, database, queue, or other system component.
Should responses always use dashed arrows?
Using -->> for responses is not mandatory, but it creates a predictable visual distinction between calls and returns. Adopt one convention across a documentation set and use notes for exceptions.
How many participants should one diagram contain?
There is no fixed limit. In practice, if labels become cramped or readers must trace more than one independent story, split the diagram by use case or system boundary.
Can Mermaid model asynchronous events?
Yes. Use an open arrow such as -) for an event or queued command, then show the consumer as a separate participant. Add a note when delivery guarantees, retry policy, or ordering constraints matter.
When should I use a sequence diagram instead of a flowchart?
Choose a sequence diagram when the order of interactions between participants is the main question. Choose a flowchart when decisions and process steps matter more than ownership. Browse the diagram examples to compare patterns before choosing.
Next Steps
Start with one request or user action, declare only the participants it touches, and add alternatives after the happy path is clear. You can build and preview the source in the OnUML editor, explore more UML diagram examples, or continue with the Mermaid Flowchart Guide.