Mermaid Sequence Diagrams: Syntax, UML Meaning, and Best Practices

From Qiki
Jump to navigation Jump to search

1) Introduction

What is a sequence diagram?

A sequence diagram shows how things talk to each other over time. Each “thing” (a person, system, service, object) is drawn as a lifeline. Messages (arrows) go back and forth to show the order of actions. In UML, sequence diagrams are a kind of interaction diagram.

Why use Mermaid?

Mermaid lets you write diagrams as text. This is great for code reviews, docs, wikis, and version control. Mermaid supports sequence diagrams with many useful features (notes, loops, branches, parallel parts, and more).



2) Mermaid basics: participants, messages, lifelines

  • Participants / Actors

    sequenceDiagram
      participant User
      participant App

    UML meaning: each participant (or actor) becomes a lifeline in UML—an entity that can send/receive messages. Actors can be people or external systems. Mermaid orders them by first appearance, unless you list them first.

  • Messages (arrows)

    sequenceDiagram
      User->>App: click "Login"
      App-->>User: show login form

    UML meaning: arrows are messages between lifelines. Solid arrowheads usually show a call/interaction; dashed lines are often used for returns/replies in UML. (UML uses solid arrowheads for synchronous calls, open arrowheads for asynchronous calls, and dashed lines for replies.)

  • Lifelines & activation The thin vertical line under a participant is its lifeline. Narrow rectangles on it are activations (also called execution specifications): time spent running or waiting due to a message.



3) Core syntax elements — syntax → UML meaning → example

Use/remember: Mermaid syntax draws the picture; UML terms explain what the picture means.

3.1 Participants & aliases

Mermaid syntax

sequenceDiagram
  participant U as "End User"
  actor A as "Auth Service"
  participant DB as "User DB"

UML meaning Each line declares a lifeline. actor uses a stick‑figure style; participant uses a box. The as part is just a label/alias. (Mermaid can also style participants as boundary/control/entity/database/collection/queue with JSON config, matching common UML stereotypes.)

Rendered meaning Three lifelines: an end user, an auth service, and a database.



3.2 Arrow types (messages)

Mermaid arrow syntaxes (v11 adds bidirectional forms)

->      solid line (no head)
-->     dotted line (no head)
->>     solid line with arrowhead
-->>    dotted line with arrowhead
<<->>   solid line with arrowheads on both ends (v11+)
<<-->>  dotted line with arrowheads on both ends (v11+)
-x      solid line with an “X” at end
--x     dotted line with an “X” at end
-)      solid line with open arrow (often used for async)
--)     dotted line with open arrow (often used for async)

UML meaning (typical reading)

  • ->> / -->>: directed messages. Teams often use -->> for reply/return.
  • -) / --): asynchronous style (open arrowhead). In UML, an open arrowhead indeed means asynchronous.
  • -x / --x: message ending with an X; in UML a lifeline can be destroyed (shown with an “X” on the lifeline).
  • Bidirectional <<->> / <<-->> (v11+): Mermaid shortcut for “two directions at once”. UML normally prefers two separate messages instead of a single “double‑headed” arrow.

Example

sequenceDiagram
  participant Client
  participant API
  Client->>API: GET /users        %% call
  API-->>Client: 200 OK           %% reply/return
  Client-)API: fire-and-forget    %% async style

Rendered meaning Client calls API, API returns, then Client sends a non‑blocking/async signal.



3.3 Activation (focus of control)

Mermaid syntax

sequenceDiagram
  participant A
  participant B
  A->>+B: doWork()        %% '+' activates B
  B-->>-A: done           %% '-' deactivates B

Or with explicit commands:

sequenceDiagram
  A->>B: doWork()
  activate B
  B-->>A: done
  deactivate B

UML meaning The narrow rectangle is an activation/execution specification: B is running (or waiting) because A called it. You can stack activations if one call triggers another.



3.4 Notes (comments on the diagram)

Mermaid syntax

sequenceDiagram
  participant A
  participant B
  A->>B: request
  Note right of B: Validate input
  Note over A,B: End-to-end encryption

UML meaning A note is an attached comment. over A,B spans two lifelines. Line breaks are allowed in notes and messages; long names can use aliases.

Rendered meaning Shows helpful commentary near the relevant interaction.



3.5 Loops

Mermaid syntax

sequenceDiagram
  loop Retry up to 3 times
    Client->>API: attempt()
    API-->>Client: result
  end

UML meaning This is a combined fragment of type loop—a repeated sequence with a condition/counter.



3.6 Branches: alt / opt

Mermaid syntax

sequenceDiagram
  alt Password is correct
    App-->>User: Login success
  else Wrong password
    App-->>User: Show error
  end

  opt Remember me selected
    App->>Store: Save token
  end

UML meaning alt is a combined fragment (alternative) with branches; opt is a single optional branch.



4) Advanced features

4.1 Parallel (par)

Mermaid syntax

sequenceDiagram
  par Fetch profile
    App->>API: GET /profile
  and Fetch settings
    App->>API: GET /settings
  end

UML meaning A parallel combined fragment: branches can happen at the same time. You can nest par blocks.



4.2 Critical region (criticaloption …)

Mermaid syntax

sequenceDiagram
  critical Update account
    App->>DB: write changes
  option DB timeout
    App-->>User: please retry
  end

UML meaning A critical region marks steps that must be executed atomically, with optional options for handling conditions. (This corresponds to UML’s critical combined fragment.)



4.3 Break (break)

Mermaid syntax

sequenceDiagram
  break Too many failed logins
    App-->>User: lock account
  end

UML meaning A break combined fragment: when its guard is true, normal flow stops here. Often used for errors/exceptions.



4.4 Create / destroy participants

Mermaid syntax

sequenceDiagram
  participant A
  create participant S as "Session"
  A->>S: initialize
  destroy S

UML meaning create starts a new lifeline at that moment (a UML createMessage). destroy ends a lifeline with an X (a UML deleteMessage / destruction event). Mermaid’s rule: only the recipient can be created; sender or recipient may be destroyed. If you see a persistent error about create/destroy, ensure Mermaid v10.7.0+ is used.



4.5 Grouping / boxes

Mermaid syntax

sequenceDiagram
  box Aqua Client tier
    participant User
    participant Browser
  end
  box rgb(33,66,99) Backend
    participant API
    participant DB
  end

Meaning Just a visual group to separate tiers/teams. Helpful for readability; not a special UML construct.



4.6 Background highlights

Mermaid syntax

sequenceDiagram
  rect rgba(0, 0, 255, .1)
    User->>API: critical operation
  end

Meaning A soft background to highlight a stretch of flow. Visual only.



4.7 Sequence numbers

Mermaid syntax

sequenceDiagram
  autonumber
  A->>B: first
  B-->>A: second

Or enable globally:

<script>
  mermaid.initialize({ sequence: { showSequenceNumbers: true } });
</script>

Meaning Shows 1, 2, 3… on messages to emphasize order. (You can turn it on per diagram with autonumber or by configuration.)



4.8 Clickable menus on actors

Mermaid syntax

sequenceDiagram
  participant API
  link API: Health Dashboard @ https://status.example.com

Meaning Adds a small popup menu on a participant (links to docs, dashboards, etc.). There’s also a JSON form via links API: { ... }.



4.9 Participant stereotypes (visual types)

Mermaid can draw participant shapes commonly used with UML stereotypes like Boundary, Control, Entity, Database, Queue, etc. (set via JSON config). In UML analysis, Boundary/Control/Entity (BCE) reflect typical roles: boundaries talk to actors/external systems, controls coordinate logic, entities hold domain data.



5) Best practices & tips (simple and practical)

  1. Pick clear arrow styles. Use ->> for normal calls and -->> for returns/replies; use -) for async “fire‑and‑forget” messages. (In UML, open arrowheads mean asynchronous.)
  2. Use activations (+ / -). They make “who is busy now?” obvious.
  3. Keep branches obvious. Prefer alt/else with short labels like alt Success / else Failure.
  4. Limit width. Too many participants makes the diagram hard to read. Group with box if needed.
  5. Explain with notes. Leave a small Note over A,B: to explain tricky parts.
  6. Show numbers when order matters (autonumber or global showSequenceNumbers).
  7. Model creation/destruction explicitly if it matters (create / destroy). In UML the created lifeline begins at the message; destroyed ones end with an X.
  8. Avoid single “double‑headed” arrows in formal UML; prefer two arrows (request + response). Mermaid supports <<->> (v11+), but teams often keep two separate messages for clarity.
  9. Escaping & comments. Use %% for comments; use entity codes if you need special characters. (Example: #59; for ; inside text.)
  10. Beware the word end. In some contexts, a raw end token can interfere; put it in quotes or brackets if it must appear as text.



6) Complete example (with step‑by‑step meaning)

Scenario: A user logs in. The app verifies credentials and, on success, creates a session and loads the dashboard. There’s a retry loop and a lockout break.

sequenceDiagram
  autonumber

  %% Tier grouping
  box Aqua Client
    actor User
    participant Browser
  end
  box rgb(33,66,99) Server
    participant App as "Web App"
    participant Auth as "Auth Service"
    participant DB as "User DB"
  end

  link Auth: Health @ https://status.example.com

  User->>Browser: Click "Login"
  Browser->>+App: POST /login (user, pass)
  App->>+Auth: verify(user, pass)

  loop up to 3 tries
    Auth->>+DB: loadUser(user)
    DB-->>-Auth: user + hash
    alt hash matches
      Auth-->>App: OK
      create participant S as "Session"
      App->>S: init(user, expiry)
      App-->>Browser: 200 OK (session cookie)
    else wrong password
      Auth-->>App: FAIL
      App-->>Browser: 401 (show error)
    end
  end

  break too many failed attempts
    rect rgba(255,0,0,.08)
      App-->>Browser: 423 (account locked)
    end
  end

  par background fetches
    Browser-)App: fetch /me          %% async
  and
    Browser-)App: fetch /settings    %% async
  end

  Browser->>User: Show dashboard
  destroy S
  App-->>-Browser: (end)              %% return from login handler

What this shows (step by step):

  1. Participants & groups: We group client vs server with box so tiers are clear. (Visual only.)
  2. Login call: Browser calls App; App calls Auth (solid arrowheads).
  3. Loop: Up to 3 attempts (loop … end).
  4. DB call: Auth activates DB and gets data back (activation bars show who is “busy”).
  5. Branch: alt shows Success vs Failure; opt is not needed here.
  6. Create session: On success we create participant S and initialize it, then later destroy S. In UML this corresponds to create/delete messages and a destruction event.
  7. Break: After three failures we break and show a lock message.
  8. Parallel: Two async background fetches using par and -) (open head) to suggest non‑blocking behavior. In UML, open arrowheads indicate async calls.
  9. End: We return from the handler and show the dashboard.



Mermaid ↔ UML cheat sheet (quick mapping)

Tip: “Mermaid syntax” is on the left; “what it means in UML / modeling terms” is on the right.

Mermaid syntax UML / modeling meaning
sequenceDiagram Start of a Sequence Diagram (UML interaction).
participant A / actor A A lifeline (actor is usually an external user/system).
participant Id as "Label" Lifeline with a label/alias (name shown is “Label”).
JSON participant types: Boundary / Control / Entity / Database / Collections / Queue Visual stereotypes matching common UML roles (BCE pattern, databases, queues).
A->>B: msg Message (often treated as a synchronous call). Solid head.
A-->>B: msg Return/reply (dashed). Common UML reading.
A-)B / A--)B Asynchronous signal (open head).
A-x B Message ending with destruction (end of lifeline shown with X). Use with care.
<<->> / <<-->> Two arrowheads (v11+). Shortcut; UML usually prefers two separate messages.
activate B / deactivate B Start/stop activation (execution specification).
A->>+B / B-->>-A Shortcut: activate/deactivate via message suffix + / -.
Note left of A: / Note over A,B: Note/comment attached to one or more lifelines.
loop ... end Loop combined fragment (repeat while condition holds).
alt ... else ... end Alternative combined fragment (if/else).
opt ... end Optional combined fragment (if without else).
par ... and ... end Parallel combined fragment (concurrent branches).
critical ... option ... end Critical region combined fragment (atomic block with options).
break ... end Break combined fragment (interrupts the normal flow).
create participant X Create a lifeline at this point (UML createMessage).
destroy X Delete a lifeline (UML deleteMessage / destruction event).
box COLOR Label ... end Visual grouping of participants (not a UML semantic element).
rect COLOR ... end Visual highlight background.
autonumber / showSequenceNumbers config Show message numbering 1, 2, 3…
link <actor>: <label> @ <url> Add popup menu links on a participant.
%% comment Comment in Mermaid source (ignored in diagram).



Quick reference examples (copy/paste)

Synchronous call + return + activation

sequenceDiagram
  A->>+B: compute()
  B-->>-A: result

Async message

sequenceDiagram
  A-)B: notify()

Loop and branch

sequenceDiagram
  loop each item
    A->>B: process(item)
    alt ok
      B-->>A: done
    else error
      B-->>A: fail
    end
  end

Parallel

sequenceDiagram
  par path 1
    A->>B: step 1
  and path 2
    A->>C: step 2
  end

A note on UML semantics (one‑screen summary)

  • Synchronous vs asynchronous: solid arrowhead (sync) vs open arrowhead (async). Dashed lines are commonly used for replies. Activations show “who is executing/waiting now.”
  • Create / destroy: a lifeline can start at a create message and end with an X (destruction).
  • BCE stereotypes: Boundary / Control / Entity are common roles used in analysis and often reflected in sequence diagrams.



Sources (key ones you may want to bookmark)

  • Mermaid — Sequence diagrams (official syntax and features).
  • Mermaid — sequence numbers, links, rect, comments (sections on this page).
  • UML sequence basics (sync/async arrows, replies, activations).
  • BCE (Boundary/Control/Entity) roles.