Mermaid Sequence Diagram Loop and Control Flow Explained

··8 min read
mermaidsequence-diagramcontrol-flowsoftware-design

A Mermaid sequence diagram loop is useful when an interaction repeats, but real system behavior usually needs more than repetition. Retries need a stopping rule, alternatives need explicit outcomes, parallel work must be genuinely independent, and fatal failures should end the normal path. A Mermaid sequence diagram loop can combine loop, alt, opt, par, critical, and break blocks for those jobs.

This Mermaid sequence diagram loop tutorial focuses on choosing and combining those control-flow blocks. For participants, arrows, activations, and notes, begin with the Mermaid Sequence Diagram tutorial. Every example below is compatible with the Mermaid 11.17.2 runtime currently used by OnUML.

Choose a Mermaid Sequence Diagram Loop Block

A Mermaid sequence diagram loop should match the behavior readers need to verify, not merely decorate a set of messages.

Behavior to explainMermaid blockQuestion it answers
A bounded retry, poll, or repeated itemloopWhat repeats, and when does it stop?
One of several outcomesalt / elseWhich mutually exclusive path occurs?
One optional stepoptWhat may happen without an alternative branch?
Independent concurrent workpar / andWhich interactions may overlap?
Protected work with failure handlingcritical / optionWhat must finish, and what can go wrong?
An early exitbreakWhich condition stops the normal interaction?

The Mermaid sequence diagram loop label is part of the design, not decoration. Write a condition such as Up to 3 attempts or Token is valid instead of a vague label such as Retry or Success path.

Model a Bounded Mermaid Sequence Diagram Loop

A bounded Mermaid sequence diagram loop uses loop <stopping rule>, followed by messages and a matching end. Put the limit, cadence, or completion condition in the label so the diagram does not imply an infinite retry.

sequenceDiagram
    participant Worker
    participant API

    Worker->>API: POST /exports
    API-->>Worker: 202 Accepted (job-42)
    loop Every 2 seconds, up to 5 checks
        Worker->>API: GET /exports/job-42
        API-->>Worker: Current status
    end
    API-->>Worker: Download URL

Verify the Mermaid Sequence Diagram Loop Exit Rule

This Mermaid sequence diagram loop explains the observable polling contract. It does not claim that every check returns the same status or that the fifth request always succeeds. If those outcomes matter, add an alt block inside the loop.

Add Outcomes Inside a Mermaid Sequence Diagram Loop

sequenceDiagram
    participant Client
    participant Gateway

    loop Up to 3 attempts
        Client->>Gateway: Authorize payment
        alt Authorization approved
            Gateway-->>Client: Authorization ID
        else Temporary gateway error
            Gateway-->>Client: Retryable error
        else Payment declined
            Gateway-->>Client: Decline reason
        end
    end

The Mermaid sequence diagram loop source is valid, but the reader still needs to know whether an approval ends the real retry loop. A Mermaid sequence diagram loop describes interactions; it is not an executable control-flow program. State the actual exit rule in the label or surrounding text instead of expecting the rendering to enforce it.

Add alt to a Mermaid Sequence Diagram Loop

A Mermaid sequence diagram loop uses alt when exactly one branch should describe the result. Add else for each additional outcome and close the group with end.

sequenceDiagram
    actor User
    participant App
    participant Auth

    User->>App: Open account page
    App->>Auth: Validate access token
    alt Token is valid
        Auth-->>App: User claims
        App-->>User: Show account
    else Token is expired
        Auth-->>App: Expired token
        App-->>User: Ask user to sign in again
    else Token is malformed
        Auth-->>App: Invalid token
        App-->>User: Show access error
    end

Mermaid sequence diagram loop branch labels should be testable conditions. Token is valid tells a reviewer what selects the path; Happy path only describes how the author feels about it.

Add opt to a Mermaid Sequence Diagram Loop

A Mermaid sequence diagram loop can use an opt block for an alternative without an else. It works well for notifications, cache writes, audit records, and feature-dependent behavior that does not replace the main outcome.

sequenceDiagram
    actor Member
    participant Profile
    participant Email

    Member->>Profile: Save settings
    opt Email address changed
        Profile-)Email: Queue verification message
    end
    Profile-->>Member: Settings saved

A Mermaid sequence diagram loop should not use opt for a failure that changes the response. If the request returns different outcomes, use alt so both results remain visible.

Add par to a Mermaid Sequence Diagram Loop

A Mermaid sequence diagram loop starts a parallel group with par, adds more branches with and, and finishes with end. The branches should be able to overlap without one requiring the result of another.

sequenceDiagram
    participant Orders
    participant Inventory
    participant Fraud
    participant Profile

    par Reserve inventory
        Orders->>Inventory: Reserve line items
        Inventory-->>Orders: Reservation ID
    and Check fraud signals
        Orders->>Fraud: Score order
        Fraud-->>Orders: Risk score
    and Load delivery preferences
        Orders->>Profile: Get saved address
        Profile-->>Orders: Delivery address
    end
    Orders->>Orders: Decide whether to continue

If the fraud request needs the reservation ID, it is not parallel. A Mermaid sequence diagram loop must draw that request after the inventory response. A diagram that shows false concurrency can be more damaging than no diagram because readers may use it to justify an unsafe implementation.

Add critical to a Mermaid Sequence Diagram Loop

A Mermaid sequence diagram loop uses a critical region to highlight work that must complete as one protected operation. Optional option branches document exceptional circumstances.

sequenceDiagram
    participant Payments
    participant Database
    participant RecoveryQueue

    critical Persist one payment result
        Payments->>Database: Commit payment record
        Database-->>Payments: Commit confirmed
    option Database timeout
        Payments-)RecoveryQueue: Store reconciliation event
    option Constraint violation
        Payments->>Database: Read existing payment
        Database-->>Payments: Existing result
    end

The Mermaid sequence diagram loop block communicates an important invariant, but it does not create a database transaction. Explain isolation, idempotency, and recovery behavior in the surrounding design document when those details affect correctness.

Add break to a Mermaid Sequence Diagram Loop

A Mermaid sequence diagram loop uses break to mark a condition that stops the normal interaction. It is useful for validation failures, unavailable dependencies, rate limits, and circuit breakers.

sequenceDiagram
    actor Buyer
    participant Checkout
    participant Inventory
    participant Payments

    Buyer->>Checkout: Submit order
    Checkout->>Inventory: Check availability
    Inventory-->>Checkout: Out of stock
    break Product is unavailable
        Checkout-->>Buyer: 409 Out of stock
    end
    Checkout->>Payments: Authorize total

The message after the Mermaid sequence diagram loop block represents the normal continuation when the break condition is not met. Keep the break response inside the block so reviewers can see both the exit and the status returned to the caller.

Combine Mermaid Sequence Diagram Loop Blocks

A nested Mermaid sequence diagram loop is useful when it mirrors the real contract. The following example combines an optional idempotency lookup, parallel preparation, a bounded payment retry, mutually exclusive results, and an early exit.

sequenceDiagram
    autonumber
    actor Customer
    participant API as Order API
    participant DB as Orders DB
    participant Stock as Inventory
    participant Pay as Payment Gateway
    participant Events as Event Bus

    Customer->>API: POST /orders
    opt Idempotency key supplied
        API->>DB: Find order by key
        DB-->>API: No existing order
    end

    par Create pending order
        API->>DB: Insert pending order
        DB-->>API: Order ID
    and Reserve items
        API->>Stock: Reserve line items
        Stock-->>API: Reservation ID
    end

    loop Up to 2 attempts for retryable errors
        API->>Pay: Authorize total
        alt Approved
            Pay-->>API: Authorization ID
        else Temporary error
            Pay-->>API: Retryable error
        else Declined
            Pay-->>API: Decline reason
        end
    end

    alt Payment approved
        API->>DB: Mark order confirmed
        API-)Events: Publish OrderConfirmed
        API-->>Customer: 201 Created
    else Payment declined or retries exhausted
        API->>Stock: Release reservation
        API->>DB: Mark order failed
        API-->>Customer: Payment not completed
    end

The final alt in this Mermaid sequence diagram loop is deliberate. The loop shows retry mechanics; the outer decision shows the durable business outcome. Combining both concerns into one set of branches would make it harder to see what the system stores after retries finish.

Debug Mermaid Sequence Diagram Loop Syntax

When a Mermaid sequence diagram loop fails to render, check the structure from the inside out:

  1. Confirm every loop, alt, opt, par, critical, break, and rect has one matching end.
  2. Use else only inside alt; use and only inside par; use option only inside critical.
  3. Temporarily remove the innermost group, render again, and restore one block at a time.
  4. Keep the lowercase word end out of unquoted labels when it could be parsed as a block terminator. Mermaid's official syntax reference recommends wrapping unavoidable uses in quotation marks, parentheses, or brackets.
  5. Make sure activations opened with + are closed with - on every visible exit path.

The official Mermaid sequence diagram reference documents these block forms. Test each Mermaid sequence diagram loop in the Mermaid Sequence Diagram Online Editor against the same runtime used by OnUML.

Reuse a Mermaid Sequence Diagram Loop Template

A Mermaid sequence diagram loop becomes easier to judge inside a complete scenario. Copy the authentication, payment, database, queue, and webhook templates in Mermaid Sequence Diagram Examples, then use the styling and readability guide to make dense branches easier to scan. If the diagram will live in a README or design document, follow the Markdown integration guide before relying on platform-specific syntax.