Back to blog
|12 min read|Docsio

Sequence Diagram Example: 6 Real Flows in Mermaid

sequence-diagramumldiagramsdocumentation
Sequence Diagram Example: 6 Real Flows in Mermaid

Sequence Diagram Example: 6 Real Flows in Mermaid

A sequence diagram shows how the parts of a system talk to each other over time: who sends which message, in what order, and what comes back. This guide walks through six sequence diagram examples you can copy, all written in Mermaid syntax so they live as text in your repo instead of screenshots in a wiki.

Most tutorials on this topic show you static images you can look at but never reuse. Every example here is real code. Paste it into any Mermaid-enabled tool and you get a rendered diagram you can edit, version, and drop into your docs. We cover a login flow, a password reset, an API webhook callback, a checkout, a microservice order pipeline, and a CI/CD deploy.

Before the examples, a quick tour of the notation, because every arrow and box means something specific.

What Is a Sequence Diagram?

A sequence diagram is one of the interaction diagrams defined in UML, the Unified Modeling Language. It models a single scenario: one login attempt, one checkout, one deploy. Participants sit across the top, time flows down the page, and arrows between vertical lines show messages passing back and forth.

That vertical time axis is the whole point. A UML sequence diagram answers "what happens first, and then what?" in a way an architecture box diagram never can. If you want to show static structure instead, containers, components, and how they nest, reach for the C4 model rather than a sequence diagram.

Teams use sequence diagrams to design a flow before writing code, to explain an existing flow to a new engineer, and to pin down integration contracts between services. They shine anywhere the order of operations matters: auth handshakes, payment flows, retry logic, event fan-out.

Sequence Diagram Notation: The Five Parts That Matter

UML defines dozens of notation details. You need five of them to read or write almost any diagram.

  • Actor. A human or external system that kicks off the interaction. Drawn as a stick figure. In Mermaid you declare it with the actor keyword.
  • Lifeline. The vertical dashed line under each participant. It represents that object's existence for the duration of the scenario.
  • Message arrows. Horizontal arrows between lifelines. A solid arrowhead is a synchronous message (the sender waits for a reply). An open arrowhead is asynchronous (the sender fires and moves on). Dashed arrows are replies.
  • Activation bar. The thin rectangle sitting on a lifeline. It marks the span where that participant is actively processing. Mermaid draws these when you use activate and deactivate.
  • Fragments. Labeled boxes that wrap part of the flow. alt models if/else branches, opt models a step that only sometimes happens, loop models repetition, and par models things running in parallel.

Here is how those map to Mermaid syntax:

ConceptUML meaningMermaid syntax
Synchronous messageSender waits for responseA->>B: message
Reply messageResponse returning to callerB-->>A: response
Asynchronous messageSender does not waitA--)B: event
Activation barParticipant is busyactivate B / deactivate B
Alternative fragmentIf/else branchingalt / else / end
Optional fragmentConditional stepopt / end
Loop fragmentRepeated interactionloop / end
Parallel fragmentConcurrent branchespar / and / end

That is enough vocabulary. On to the worked examples.

Six Sequence Diagram Examples in Mermaid

Each sequence diagram example below models a flow you have probably built or consumed. Copy the code block, then adapt the participants and messages to your own system.

1. User Login and Authentication

The classic starter. One actor, three system participants, and an alt fragment for the success and failure branches.

sequenceDiagram
    actor User
    participant Web as Web App
    participant Auth as Auth Service
    participant DB as User Database
    User->>Web: Submit email and password
    Web->>Auth: POST /login
    activate Auth
    Auth->>DB: Look up user record
    DB-->>Auth: User row with password hash
    Auth->>Auth: Verify hash
    alt Credentials valid
        Auth-->>Web: 200 OK with session token
        Web-->>User: Redirect to dashboard
    else Credentials invalid
        Auth-->>Web: 401 Unauthorized
        Web-->>User: Show error message
    end
    deactivate Auth

Read it top to bottom. The user submits credentials, the web app forwards them, and the auth service owns the decision. The self-message (Auth->>Auth) shows internal work: hashing and comparing. The activation bar on the auth service spans the whole decision, and the alt fragment makes both outcomes explicit instead of hiding the failure path.

2. Password Reset Flow

This one introduces asynchronous messages. The email leaves the system and comes back on its own schedule, which the open-arrow --) notation captures.

sequenceDiagram
    actor User
    participant App
    participant Auth as Auth Service
    participant Mail as Email Service
    User->>App: Request password reset
    App->>Auth: POST /password-reset
    Auth->>Auth: Generate one-time token
    Auth--)Mail: Queue reset email
    Auth-->>App: 202 Accepted
    Note over Mail,User: Email arrives out of band
    Mail--)User: Reset link
    User->>App: Open link with token
    App->>Auth: POST /password-reset/confirm
    alt Token valid and unexpired
        Auth-->>App: Password updated
    else Token expired
        Auth-->>App: 410 Gone, request new link
    end

Notice the auth service returns 202 Accepted before the email is ever sent. That is the honest picture: the HTTP request succeeds even if delivery takes a minute. The Note over annotation flags the time gap. Diagramming this flow often surfaces a real design question: what happens when the token expires? The alt fragment forces an answer.

3. API Request With Webhook Callback

Async APIs confuse people precisely because the response and the result arrive separately. A sequence diagram is the clearest way to show that split, which is why they belong in any guide on documenting webhooks.

sequenceDiagram
    participant Client as Your App
    participant API as Payments API
    participant Q as Job Queue
    Client->>API: POST /charges
    API-->>Client: 202 Accepted with charge_id
    API--)Q: Enqueue charge processing
    Q->>Q: Process charge
    Note over Q,Client: Seconds or minutes later
    Q--)Client: POST /webhooks (charge.succeeded)
    Client-->>Q: 200 OK acknowledged
    opt Verify before fulfilling
        Client->>API: GET /charges/charge_id
        API-->>Client: status: succeeded
    end

Two things to point out. First, the webhook arrow flows right to left, back into the client. Sequence diagrams handle that direction change without any special notation. Second, the opt fragment models the verification call that careful integrators make and lazy ones skip. Putting it in the diagram documents the recommendation without mandating it.

4. Checkout and Payment

A payment flow with an external provider and a bank. This is the diagram to sketch before you touch a payment integration, because the token handoff order is easy to get wrong.

sequenceDiagram
    actor Shopper
    participant Store as Storefront
    participant Pay as Payment Provider
    participant Bank
    Shopper->>Store: Click Pay Now
    Store->>Pay: Create payment intent
    Pay-->>Store: Client secret
    Store->>Pay: Confirm payment with card details
    Pay->>Bank: Authorize charge
    alt Authorized
        Bank-->>Pay: Approval code
        Pay-->>Store: Payment succeeded
        Store-->>Shopper: Order confirmation page
    else Declined
        Bank-->>Pay: Decline code
        Pay-->>Store: Payment failed
        Store-->>Shopper: Prompt for another card
    end

The two-step dance at the top (create intent, then confirm) is the pattern Stripe and most modern providers use. Seeing it as a sequence makes the reason obvious: the client secret has to exist before the browser can submit card details. The decline branch is not an edge case here. It is a first-class path your UI has to handle.

5. Microservice Order Processing

More participants, nested fragments, and event fan-out. This is where sequence diagrams earn their keep, because prose descriptions of five-service interactions collapse under their own weight.

sequenceDiagram
    participant GW as API Gateway
    participant Order as Order Service
    participant Inv as Inventory Service
    participant Pay as Payment Service
    participant Ship as Shipping Service
    GW->>Order: POST /orders
    Order->>Inv: Reserve stock
    Inv-->>Order: Reservation ID
    Order->>Pay: Charge customer
    alt Payment confirmed
        Pay-->>Order: Charge ID
        par Notify shipping
            Order--)Ship: order.created event
        and Confirm reservation
            Order--)Inv: reservation.confirmed event
        end
        Order-->>GW: 201 Created
    else Payment failed
        Pay-->>Order: Error code
        Order->>Inv: Release stock
        Order-->>GW: 402 Payment Required
    end

The par fragment inside the success branch shows the two events firing concurrently rather than in sequence, which matters for anyone debugging ordering assumptions later. The failure branch documents the compensating action: released stock. If your diagram of a distributed flow has no failure branch, the diagram is fiction.

6. CI/CD Pipeline

Sequence diagrams are not just for request/response systems. Here is a deploy pipeline, with a loop fragment for the test suites.

sequenceDiagram
    actor Dev as Developer
    participant Git as Git Host
    participant CI as CI Runner
    participant Reg as Registry
    participant Prod as Production
    Dev->>Git: git push
    Git--)CI: Push event webhook
    CI->>CI: Install dependencies and build
    loop Each test suite
        CI->>CI: Run tests
    end
    alt All checks pass
        CI->>Reg: Push container image
        Reg-->>CI: Image digest
        CI->>Prod: Deploy new version
        Prod-->>CI: Health check OK
        CI--)Dev: Deploy succeeded
    else Any check fails
        CI--)Dev: Build failed with logs
    end

Almost every message here is asynchronous or self-directed, which reflects reality: nobody blocks waiting for a build. Diagramming your actual pipeline like this is a fast way to spot missing feedback, like a deploy that never reports back to the developer who triggered it.

One practical note on where these diagrams should live. A diagram in a slide deck is dead within a month. Inside your published docs, next to the endpoint or flow it explains, it stays visible and gets fixed when it drifts. Docsio generates a documentation site where Mermaid blocks render natively, so every example above can go straight into a docs page as plain text, no image exports involved.

How to Draw a Sequence Diagram in 6 Steps

Knowing how to draw a sequence diagram is mostly knowing what to decide before you draw anything. The drawing itself is the easy part.

  1. Pick one scenario. A sequence diagram models a single path, not a whole system. "User logs in with valid credentials" is a scenario. "Authentication" is not.
  2. List the participants. Every actor, service, and datastore that sends or receives a message in this scenario. If you list more than six or seven, your scenario is too big. Split it.
  3. Write the happy path as plain steps. One line per message, in order, before touching any tool. This step catches most confusion early.
  4. Convert steps to messages. Each line becomes an arrow. Decide for each one: does the sender wait (synchronous) or fire and forget (asynchronous)?
  5. Add the branches. Wrap failure cases in alt fragments, conditional steps in opt, and repetition in loop. If you cannot name the failure branch, you have found a design gap.
  6. Prune. Delete any participant or message a reader does not need to understand the scenario. Getters, loggers, and internal helpers usually go.

The same discipline applies whether you sketch on a whiteboard or write Mermaid in a design doc template. Decide first, draw second.

Common Sequence Diagram Mistakes

A few failure patterns show up in almost every team's diagrams.

  • Modeling the whole system in one diagram. Twelve lifelines and forty messages is not a diagram, it is a debugging session. One scenario per diagram, always.
  • Only drawing the happy path. The failure branches are where the design decisions live. A diagram without an alt fragment usually means nobody has thought about errors yet.
  • Using the wrong diagram type. If you are showing where data lives and how it moves between stores rather than message order, you want a data flow diagram instead. If you are showing structure, use C4.
  • Wrong arrow types. Marking an async event as a synchronous call misleads readers about blocking behavior, which is exactly the thing this diagram type exists to communicate.
  • Diagrams as images. Screenshots from a drawing tool rot silently. Text-based formats diff in code review and get updated because updating them is cheap.

Which Sequence Diagram Tool Should You Use?

Four tools cover nearly everyone. The split is text-based versus drag-and-drop.

ToolTypeBest forPrice
MermaidText-basedDiagrams in Markdown docs, GitHub, docs sitesFree
PlantUMLText-basedComplex UML with full notation supportFree
LucidchartDrag-and-dropPolished diagrams for presentationsFree tier, paid plans
draw.ioDrag-and-dropFree visual editing, offline useFree

For flows that live in documentation, text-based wins. Mermaid renders natively in GitHub, GitLab, Notion, Docusaurus, and most modern docs platforms, so the diagram source sits in the same file as the prose around it. PlantUML supports more of the UML spec (found messages, timing constraints, entity stereotypes) at the cost of a rendering server or plugin.

Drag-and-drop tools produce prettier output for slide decks and stakeholder reviews. The tradeoff is that the result is an image, with all the maintenance problems images bring. Most engineering teams end up with Mermaid for docs and something visual for the occasional executive diagram.

Sequence Diagram Example FAQ

How do you draw a sequence diagram?

Pick a single scenario, list every participant involved, and write the messages between them as ordered steps. Place participants across the top, draw lifelines down, and add arrows for each message in time order. Wrap branches in alt or opt fragments, then remove anything a reader does not need.

What is the best tool for creating sequence diagrams?

For diagrams that live in documentation, Mermaid is the strongest choice because it is free, text-based, and renders in GitHub and most docs platforms, including sites generated by Docsio. PlantUML suits heavy UML users. Lucidchart and draw.io work better for polished, presentation-grade visuals.

Can ChatGPT create sequence diagrams?

Yes. ChatGPT, Claude, and similar assistants can generate Mermaid or PlantUML code from a plain-language description of a flow, and the output usually renders correctly. Always review the result against your real system, because models guess at participants and message order when your description leaves gaps.

How do you create a sequence diagram in Excel?

You can approximate one with shapes and connectors, but Excel has no notion of lifelines, activation bars, or fragments, so everything is manual. Visio includes a proper UML sequence stencil if you are in the Microsoft ecosystem. A free text-based tool like Mermaid is faster and easier to maintain.

Ready to ship your docs?

Generate a complete documentation site from your URL in under 5 minutes.

Get Started Free