Mermaid Sequence Diagram: Syntax and Practical Tutorial
A Mermaid sequence diagram explains how people, services, and data stores interact over time. It is especially useful for API request lifecycles, authentication, background jobs, microservice orchestration, and failure analysis because the order of each interaction is visible.
This Mermaid sequence diagram guide moves from 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.
Use this page as the core tutorial, then continue with the page that matches your task:
| Task | Detailed article |
|---|---|
| Model retries, alternatives, parallel work, and early exits | Loops and control flow |
| Copy complete API, database, queue, webhook, and cache patterns | Sequence diagram examples |
| Improve labels, grouping, highlights, themes, and contrast | Styling and readability |
| Publish diagrams in GitHub, GitLab, and VS Code Markdown | Markdown integration |
Why Use a Mermaid Sequence Diagram?
A Mermaid sequence diagram stores the interaction 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 are still deciding which UML view fits the problem, start with the Mermaid UML support matrix. If you need strict UML coverage or extensive styling, compare Mermaid and PlantUML for sequence diagrams.
Mermaid Sequence Diagram 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.
Mermaid Sequence Diagram Participants and Actors
A Mermaid sequence diagram declares 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
Mermaid Sequence Diagram Message Types and Activations
A Mermaid sequence diagram uses arrow styles to 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 Mermaid Sequence Diagram Messages with autonumber
A Mermaid sequence diagram can 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 Mermaid Sequence Diagram Context with Notes
A Mermaid sequence diagram uses notes for 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.
Mermaid Sequence Diagram Conditional and Repeated Flows
A Mermaid sequence diagram uses control blocks to represent conditional and repeated behavior. For decision rules, nesting patterns, and a complete retry example, use the dedicated Mermaid sequence diagram loops and control-flow tutorial.
Mermaid Sequence Diagram 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
Mermaid Sequence Diagram 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
Mermaid Sequence Diagram 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
Mermaid Sequence Diagram 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.
Mermaid Sequence Diagram Critical Regions and Breaks
A Mermaid sequence diagram uses 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 Mermaid Sequence Diagram Participants
A Mermaid sequence diagram can create participants that 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 Mermaid Sequence Diagram API Example
This Mermaid sequence diagram 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.
For more complete templates that keep authentication, database transactions, background jobs, webhook retries, and cache reads as separate reader tasks, browse the Mermaid sequence diagram examples.
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
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
deactivate Pay
deactivate API
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 a Mermaid Sequence Diagram
Troubleshoot a Mermaid sequence diagram by separating rendering syntax, label readability, activation balance, and participant order.
The Mermaid Sequence 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.
Mermaid Sequence Diagram Labels 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.
Mermaid Sequence Diagram 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.
Mermaid Sequence Diagram 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 Mermaid Sequence Diagram Online Editor before publishing. A small rendering check catches missing end statements and overly long labels before they reach documentation.
Maintaining a Mermaid Sequence Diagram
Treat Mermaid sequence 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.
When the source will live in a README, pull request, wiki, or design document, check the target renderer and version using the Mermaid sequence diagrams in Markdown guide. If the interaction is correct but visually dense, use the styling and readability guide before adding more detail.
Mermaid Sequence Diagram Frequently Asked Questions
These Mermaid sequence diagram answers cover the distinctions that most often affect modeling and review.
Mermaid Sequence Diagram Participant vs 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.
Mermaid Sequence Diagram Response 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.
Mermaid Sequence Diagram Participant Limits
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.
Mermaid Sequence Diagram 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.
Mermaid Sequence Diagram vs 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.
Mermaid Sequence Diagram Next Steps
Start a Mermaid sequence diagram 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 Mermaid Sequence Diagram Online Editor, adapt a complete sequence diagram example, organize complex behavior with the control-flow tutorial, or continue with the Mermaid Flowchart Guide.