Learn (Almost) Anything
CatalogDownload course

Diagrams as Code with Mermaid

Model request/response flows: participants vs. actors, sync (->>) and async (-->>) arrows, activations, alt/opt/loop blocks, and notes. Aimed squarely at documenting API calls and service interactions, including how to show auth handshakes and error branches without the diagram turning to noise.

enMini-course6 lessons1 module5
Diagrams as Code with MermaidMermaid Diagrams in Practicemermaiddiagramscodepractice

Sequence Diagrams for APIs

Model request/response flows: participants vs. actors, sync (->>) and async (-->>) arrows, activations, alt/opt/loop blocks, and notes. Aimed squarely at documenting API calls and service interactions, including how to show auth handshakes and error branches without the diagram turning to noise.

Sequence Diagrams for APIs

From space to time

In the previous submodule, you built diagrams where nodes sit in space and edges connect them. Sequence diagrams flip that: participants stand in columns, and messages travel horizontally across *time* — top to bottom. Same Mermaid tooling, very different mental model.

Side-by-side concept: a flowchart with nodes arranged spatially on the left, versus a sequence diagram with vertical lifelines and horizontal time-ordered messages on the right.

Every sequence diagram starts with sequenceDiagram on its own line. Everything after that is either a participant declaration or a message.

Participants and actors

Participants are the columns in your diagram. Declaring them explicitly before any messages is almost always worth it — it fixes the left-to-right column order, which is the first thing that makes or breaks readability:

sequenceDiagram
    participant Client
    participant API
    participant DB

Use actor instead of participant when you want a stick-figure symbol — the right call for a human at one end of the flow:

sequenceDiagram
    actor User
    participant Browser
    participant API

For long names, aliases keep message lines readable:

    participant A as Auth Service
    participant T as Token Store

After the alias, A and T are what you write in message lines. The diagram renders the full display names.

Column order matters. If your flow is Client → API → DB, declare them in that order. Swapping DB before API forces arrows to cross and the diagram immediately becomes confusing.

Arrow types

Four arrows cover almost every API scenario:

ArrowStyleWhen to use
A->>B: msgSolid, open headOutbound call / request
A-->>B: msgDotted, open headReply / response
A-xB: msgSolid, cross headError, cancel, reject
A-)B: msgSolid, half-openFire-and-forget async

The practical convention: solid arrow going *forward*, dotted arrow coming *back*. Client->>API: GET /users and API-->>Client: 200 OK — one type per direction, consistently. --> and -> (filled-head variants) are older aliases; the open-head forms (->>, -->>) are current.

sequenceDiagram participant C as Client participant S as Server Note over C,S: Four arrows you will use constantly C->>S: solid open-head arrow (outbound call) S-->>C: dotted open-head reply (response) C-xS: cross terminus (error or cancel) S-)C: half-arrow (fire-and-forget async)
sequenceDiagram
    participant C as Client
    participant S as Server

    Note over C,S: Four arrows you will use constantly
    C->>S: solid open-head arrow (outbound call)
    S-->>C: dotted open-head reply (response)
    C-xS: cross terminus (error or cancel)
    S-)C: half-arrow (fire-and-forget async)
Arrow type reference — one line per variant, showing how each renders

Activation boxes

Activation boxes show the window during which a participant is actively processing. Append + when sending a call to open the box on the receiver, and - when sending the reply to close it:

sequenceDiagram
    Client->>+API: GET /users
    API->>+DB: SELECT *
    DB-->>-API: rows
    API-->>-Client: 200 OK

When API calls DB while still activated itself, you get stacked boxes on the API column — an accurate visual showing that API is suspended waiting on DB. The +/- shorthand is almost always cleaner than the explicit activate/deactivate keywords.

Stacked activation boxes on the API lifeline, showing API suspended and waiting while DB is actively processing below it.

Alt, opt, and loop

These three blocks map to the control-flow patterns you write code for every day.

alt — branching

alt token valid
    API-->>Client: 200 OK
else token expired
    API-->>Client: 401 Unauthorized
end

opt — optional path (runs only sometimes)

opt cache hit
    API-->>Client: 200 (from cache)
end

loop — repeated messages

loop poll every 2 seconds
    Client->>API: GET /job/status
    API-->>Client: 202 In progress
end

All three share the same structure: keyword label … end. The end keyword that closes each block is why you must never let the word end appear *unquoted* inside a label — exactly the same rule from the flowchart submodule. If your label is call endpoint, write "call endpoint" or rephrase it.

Notes

Notes annotate one participant or span two:

Note right of Client: Stores token in memory
Note over API,DB: Both services must be in the same region

Note right of / Note left of attach to one column. Note over A,B draws a box spanning both — good for constraints that apply to the whole interaction. Keep them to a single short line; anything longer belongs in prose, not the diagram.

Autonumber

Add autonumber right after sequenceDiagram to label every message automatically:

sequenceDiagram
    autonumber
    Client->>+API: GET /profile
    API-->>-Client: 200

This makes cross-referencing easy in written docs — "at step 3, the token is validated." You can start from a given number (autonumber 5) or set an increment (autonumber 1 2 produces 1, 3, 5…), useful when a diagram is the second of two connected diagrams in the same doc.

Worked example: OAuth token exchange

Here's a realistic auth handshake — user, browser, auth service, and resource API — combining most of what's covered above:

sequenceDiagram autonumber actor User participant Browser participant AuthSvc as Auth Service participant ResourceAPI as Resource API User->>Browser: Click Login Browser->>+AuthSvc: POST /oauth/token Note right of AuthSvc: Validates credentials alt valid credentials AuthSvc-->>-Browser: 200 JWT (15 min TTL) Browser->>+ResourceAPI: GET /profile Note right of ResourceAPI: Verifies JWT signature ResourceAPI-->>-Browser: 200 user data else invalid credentials AuthSvc-->>Browser: 401 Unauthorized end
sequenceDiagram
    autonumber
    actor User
    participant Browser
    participant AuthSvc as Auth Service
    participant ResourceAPI as Resource API

    User->>Browser: Click Login
    Browser->>+AuthSvc: POST /oauth/token
    Note right of AuthSvc: Validates credentials

    alt valid credentials
        AuthSvc-->>-Browser: 200 JWT (15 min TTL)
        Browser->>+ResourceAPI: GET /profile
        Note right of ResourceAPI: Verifies JWT signature
        ResourceAPI-->>-Browser: 200 user data
    else invalid credentials
        AuthSvc-->>Browser: 401 Unauthorized
    end
OAuth token exchange — autonumber, activation boxes, alt branch, and notes in a realistic flow

Things to notice:

  • Participants declared explicitly so column order is intentional.
  • Activation boxes on AuthSvc and ResourceAPI show exactly when each is processing.
  • The alt block cleanly separates the success path from the 401 branch without duplicating any arrows.
  • The Note documents the token TTL without cluttering message flow.
  • Message labels avoid slashes and parentheses in the critical node names — zero quoting needed here.
Mermaid Chart: Demo of Sequence Diagrams in the Visual Editor - Official Mermaid Chart channel walkthrough of sequence diagram features in the visual editor — useful to see the arrows and blocks rendered live.

Keeping it from turning to noise

A sequence diagram with more than ~7 participants or ~20 messages becomes unreadable fast. Three practical rules:

1. One scenario per diagram. Show the happy path in one diagram; show error branches in a second. An alt block with four branches is almost always better split into two focused diagrams.

2. Hide internal plumbing from consumer-facing docs. If you're documenting a public API, omit the DB calls — consumers care about the Client↔API contract, not how data is fetched internally.

3. Name participants specifically. Service is noise. PaymentService is useful. Same effort to type, much better to read in six months.

InteractivePick the Right Arrow
Three scenario-based questions to lock in which Mermaid arrow to use for requests, replies, and errors. Select an option to see instant feedback.

Quick check

Try these in mermaid.live:

1. Draw three participants — Browser, API, DB — with +/- activation boxes and autonumber.

2. Add an alt block: cache hit returns directly from API; cache miss queries DB.

3. Deliberately put endpoint unquoted in an alt label — watch the diagram break when the parser sees end. Then quote it to fix.

The next submodule covers class and ER diagrams. The quoting rules and the end gotcha carry over exactly — and you'll use the same participant-declaration thinking when defining entities and relationships.

Self-check

  1. What does using a solid arrow with a cross head (`A-xB`) represent in an API sequence diagram?
  2. Why does the article emphasize explicitly declaring participants at the start of a sequence diagram rather than letting them appear automatically?
  3. In a sequence diagram, what does it mean when you see two activation boxes stacked vertically on the same participant column?
  4. Which statement correctly describes when to use an `alt` block versus an `opt` block in a sequence diagram?
  5. Why does the article warn that you must quote the word 'end' if it appears in an alt/opt/loop label?
  6. According to the article, why is it better to split an alt block with multiple branches into separate diagrams rather than keeping them together?
  7. In a sequence diagram, when should you use `actor` instead of `participant` for a column?
  8. What is the practical difference between using `Note right of Client:` and `Note over Client,API:` in a sequence diagram?

Homework

E-Commerce Order Flowimage

Create a sequence diagram for a simple e-commerce order placement. Include these participants: Customer (as an actor), Web Browser, Order API, and Inventory Service. Show the happy path: customer places an order, browser sends it to the API, API checks inventory, inventory service confirms availability, and API returns the order ID. Use activation boxes to show when each service is processing (especially the API and Inventory Service while they work). Enable autonumber to label each message step.

• Customer is declared as an actor (stick figure), others as participants • Activation boxes (+/-) correctly show when API and Inventory Service are processing • Autonumber is enabled and visible on all messages • Request arrows are solid (->>) going forward, response arrows are dotted (-->>) coming back • Diagram is syntactically valid and renders without errors • Flow is easy to follow top-to-bottom (no confusing arrow crossings)

Order Flow with Inventory Errorimage

Extend your previous diagram to handle the case where inventory is out of stock. Use an `alt` block with two branches: one for success (inventory available, order confirmed) and one for failure (out of stock, order rejected). Add a note (either on Inventory Service or spanning multiple participants) that clarifies what triggers each branch. Feel free to remove autonumber if it becomes cluttered inside the alt block.

• alt block is syntactically correct with at least two branches (success and out-of-stock failure) • Each branch shows the correct messages and responses for that path • Note is present and explains the condition or constraint • No unquoted `end` keywords inside the alt label (e.g., if your label is "check inventory status", it must be quoted to avoid breaking the parser) • Activation boxes are still correctly placed • Diagram renders without syntax errors

Payment API for External Developersdocument

You're documenting a payment processing API for third-party developers. Write the Mermaid code for a sequence diagram showing: Client app → API endpoint → Auth Service (token validation) → Payment Gateway (Stripe or similar). Show the complete flow: client sends payment request, API validates auth token, requests charge from payment gateway, receives success or decline, returns result to client. Intentionally hide internal details: database writes, logging, fraud detection, analytics. After the code, write 2–3 sentences explaining what you left out and why omitting internal plumbing makes the diagram more useful for people integrating with your API.

• Mermaid code is syntactically valid (test in mermaid.live or similar) • Four to five participants are included, each with a specific, descriptive name (not generic "Service") • Auth token validation is shown (either as a separate exchange or as a validation step before the charge) • Success and failure paths for the payment charge are included (using alt block or separate sequence) • Total of roughly 8–12 messages; not more than that • Explanation clearly identifies what internal operations were omitted (e.g., "I hid the database write because the client doesn't care how we store the transaction internally") • Explanation articulates why external API docs benefit from hiding implementation details

Submit and get assignments reviewed in the Learn (Almost) Anything app.

Sources

  1. Sequence Diagram Syntax — Mermaid.js Official Docs
  2. Mermaid Chart: Demo of Sequence Diagrams in the Visual Editor — YouTube