If you've ever tried to explain how a user logs into an app, how a payment processes through multiple services, or how two systems exchange data, you know that plain text gets messy fast. Sequence diagrams solve this by showing interactions step by step, and diagram codes let you create those visuals with text instead of dragging boxes around. This syntax reference covers the building blocks you need to write sequence diagrams in popular diagram-as-code tools like Mermaid and PlantUML so you can document real workflows without leaving your text editor.
What Is a Sequence Diagram, and Why Write It as Code?
A sequence diagram shows how objects or actors communicate over time. Each participant sits at the top, vertical lines drop down to represent their lifeline, and horizontal arrows between them show messages. Think of it like a timeline of a conversation between parts of a system.
Writing sequence diagrams as code means you describe those interactions using plain text syntax instead of drawing them manually. The diagram tool reads your code and renders the visual. This matters for a few practical reasons:
- Your diagrams live in version control alongside your code, so they're tracked and reviewable.
- You can update a flow by editing a few lines of text rather than rearranging shapes in a GUI.
- Team members can read and suggest changes through pull requests, just like any other file.
- You avoid inconsistencies that creep in when diagrams are maintained separately from the codebase.
For a broader look at how different tools compare, see our comparison of Mermaid, PlantUML, and Graphviz.
Which Tools Support Sequence Diagram Code Syntax?
Two tools dominate this space:
- Mermaid built into GitHub, GitLab, Notion, and many documentation platforms. It uses a lightweight syntax that's quick to learn.
- PlantUML a mature Java-based tool that supports a wider range of diagram types and more advanced sequence diagram features.
Both tools take plain text input and produce SVG or PNG output. If you already use Mermaid for flowcharts, the shift to sequence diagrams is small you just change the diagram type keyword and learn a few new arrow styles.
How Do You Define Participants in a Sequence Diagram?
Participants are the actors or components in your diagram. You declare them at the top of your code block.
Mermaid Syntax
In Mermaid, you start the block with the sequenceDiagram keyword. Participants are created automatically when you use them in a message, or you can declare them explicitly for ordering and aliasing:
sequenceDiagram
participant U as User
participant A as Auth Service
participant D as Database
The as keyword lets you set a display name that differs from the internal alias. The order you declare participants determines their left-to-right position in the rendered diagram.
PlantUML Syntax
PlantUML uses @startuml and @enduml to wrap the diagram. You declare participants with dedicated keywords:
@startuml
actor User
participant "Auth Service" as A
database "Database" as D
@enduml
PlantUML lets you choose participant types like actor, participant, database, queue, and control. Each type changes the shape of the box in the rendered output, which helps readers identify what kind of component they're looking at.
How Do You Draw Messages Between Participants?
Messages are the arrows between lifelines. The core syntax is straightforward: specify the sender, an arrow, the receiver, and a label.
Solid and Dashed Arrows
A solid arrow with a filled head represents a synchronous or regular call. A dashed arrow with an open head represents a return or response.
In Mermaid:
sequenceDiagram
User->>Auth Service: Send credentials
Auth Service->>Database: Query user
Database-->>Auth Service: Return user data
Auth Service-->>User: Auth token
The >> syntax creates a solid arrow. The -->> syntax creates a dashed arrow. PlantUML uses a similar pattern:
@startuml User -> Auth Service : Send credentials Auth Service -> Database : Query user Database --> Auth Service : Return user data Auth Service --> User : Auth token @endumlIn PlantUML,
->is solid and-->is dashed. The number of arrow heads is cosmetic PlantUML uses single characters while Mermaid uses doubled ones.Synchronous vs. Asynchronous Calls
If you need to show an asynchronous message (one where the sender doesn't wait for a response), PlantUML supports the
->>arrowhead style for asynchronous calls. Mermaid doesn't distinguish this visually by default, but you can annotate the message label to clarify intent.How Do You Show Loops, Conditions, and Alternatives?
Real workflows aren't linear. Sequence diagram syntax includes grouping constructs for control flow.
Loops
Both Mermaid and PlantUML use
loopblocks to repeat a section:sequenceDiagram User->>Server: Poll for status loop Every 5 seconds Server-->>User: Status update endConditions (alt / else)
Use
altto show conditional branching, withelsefor the alternate path:sequenceDiagram User->>Auth: Login request alt Valid credentials Auth-->>User: Success token else Invalid credentials Auth-->>User: 401 error endYou can also use
optfor optional blocks (executed only if a condition is true) andparfor parallel execution. Here's a quick reference:
- loop repeat a section
- alt / else conditional branching
- opt optional execution
- par parallel messages
- break exit from a loop early
- critical a section that must complete without failure
Notes and Annotations
You can attach notes to participants to add context:
sequenceDiagram
User->>Server: Request
Note right of Server: Validate payload
Server-->>User: Response
PlantUML also supports note left of and floating notes with note over. Use notes sparingly they're useful for explaining why something happens, not what the arrow already says.
How Do You Show Self-Calls and Nested Activations?
Sometimes a component calls a method on itself or activates internally. Both tools handle this.
A self-call in Mermaid:
sequenceDiagram
participant S as Server
S->>S: Validate token internally
PlantUML shows activation bars (thin rectangles on the lifeline) to indicate when a participant is actively processing. You control these with activate and deactivate:
@startuml
User -> Server : Request
activate Server
Server -> Database : Query
activate Database
Database --> Server : Result
deactivate Database
Server --> User : Response
deactivate Server
@enduml
Mermaid automatically handles activation bars in most cases, but PlantUML gives you explicit control when the flow gets complex.
What Are the Most Common Mistakes with Sequence Diagram Code?
After working with these tools across many projects, these errors come up repeatedly:
- Forgetting the diagram type keyword. In Mermaid, starting with
participantbeforesequenceDiagramcauses a render failure. Always declare the diagram type first. - Mismatched arrow syntax. Mermaid uses
-->>for dashed arrows. Using-->(common in PlantUML habits) breaks Mermaid's parser. Know which tool you're writing for. - Not closing blocks. Every
loop,alt,opt, andparneeds a matchingend. Missing one creates cryptic errors. - Overloading a single diagram. If your sequence diagram has 10+ participants or 30+ messages, it becomes unreadable. Split it into focused sub-diagrams.
- Inconsistent participant aliases. If you use
participant A as AuthServicein one place and referenceAuthlater without the alias, the tool creates a second participant with a confusingly similar name. - Ignoring return messages. Showing only requests without responses gives a half picture. Include return arrows even for simple acknowledgments.
When Should You Use a Sequence Diagram Instead of a Flowchart?
Flowcharts excel at showing decision logic and branching paths. Sequence diagrams excel at showing who talks to whom, and in what order.
Use a sequence diagram when you need to show:
- API request/response flows between services
- Authentication and authorization handshakes
- Multi-step user interactions across a UI and backend
- Event-driven communication in microservices
- Protocol-level exchanges (OAuth flows, webhook callbacks)
Use a flowchart instead when you're mapping decision trees, onboarding steps, or process logic where the main concern is branching conditions, not inter-component messaging. Our guide on creating diagram codes for flowcharts covers that syntax in detail.
Quick Reference: Mermaid vs. PlantUML Sequence Syntax
Here's a side-by-side look at the most-used constructs:
- Diagram start: Mermaid uses
sequenceDiagram. PlantUML uses@startuml. - Participant: Mermaid uses
participant A as Name. PlantUML usesparticipant "Name" as Aor typed keywords likeactor,database. - Solid arrow: Mermaid uses
->>. PlantUML uses->. - Dashed arrow: Mermaid uses
-->>. PlantUML uses-->. - Self-call: Mermaid uses
A->>A: label. PlantUML usesA -> A : label. - Loop: Both use
loop ... end. - Alt/else: Both use
alt ... else ... end. - Note: Mermaid uses
Note right of A: text. PlantUML usesnote right of A : text. - Diagram end: Mermaid needs nothing. PlantUML needs
@enduml.
For a full tool-by-tool feature breakdown, check our detailed comparison article.
What Are Real-World Examples of Sequence Diagram Code?
User Login Flow (Mermaid)
sequenceDiagram
actor User
participant Client as Web App
participant Auth as Auth Service
participant DB as Database
User->>Client: Enter email and password
Client->>Auth: POST /login {credentials}
Auth->>DB: SELECT user WHERE email = ?
DB-->>Auth: User record
alt Password matches
Auth-->>Client: 200 {token}
Client-->>User: Redirect to dashboard
else Password incorrect
Auth-->>Client: 401 {error}
Client-->>User: Show error message
end
Webhook Callback Flow (PlantUML)
@startuml
participant "Payment Gateway" as PG
participant "Your Server" as S
database "Orders DB" as DB
PG -> S : POST /webhook/payment-completed
activate S
S -> DB : Update order status to "paid"
activate DB
DB --> S : OK
deactivate DB
S --> PG : 200 OK
deactivate S
@enduml
How Can You Integrate Sequence Diagrams into Your Workflow?
The biggest payoff comes when diagram code is part of your regular process, not an afterthought:
- In pull requests: When you change an API flow, update the sequence diagram in the same PR. Reviewers see both the code change and the visual representation of the flow.
- In documentation repos: Store diagram source files in a
/docs/diagramsfolder. CI pipelines can render them to images automatically using the Mermaid CLI or PlantUML's Docker image. - In README files: GitHub and GitLab render Mermaid blocks natively. Paste your code directly into a fenced
mermaidcode block and it displays as an image on the page. - In architecture decision records (ADRs): Pair your design rationale with a sequence diagram showing the chosen interaction pattern.
Practical Checklist Before You Share a Sequence Diagram
Before you commit or share your diagram code, run through these items:
- ✅ Every participant is used at least once in a message
- ✅ All
loop,alt,opt,par, andcriticalblocks have a matchingend - ✅ Return/response messages are shown (not just requests)
- ✅ Participant aliases are consistent throughout the code
- ✅ The diagram has fewer than 8 participants and 25 messages split it otherwise
- ✅ You've tested the render in your target tool's live editor before committing
- ✅ Notes add context without repeating what arrows already communicate
Start by picking one real flow from your project a login, a checkout, an API integration and write it out as a sequence diagram in the tool you already use. You'll have a working diagram in under 10 minutes, and you'll have syntax patterns to reuse on every diagram after that.
How to Create Diagram Codes for Flowcharts Using Diagram Generation Tools
Mermaid vs Plantuml vs Graphviz: Diagram Code Comparison Guide
Best Diagram Codes Generator Tools for Software Architects 2025
Uml Class Diagram Cheat Sheet: Essential Codes and Syntax Guide
Api Call Flow Sequence Diagram Markup
Understanding Sequence Diagram Symbols and Their Meanings