Welcome back. In our last lesson, we focused on translating runtime scenarios into Mermaid sequence diagrams, covering synchronous calls, asynchronous messages, and activation periods. You learned how to represent the "happy path" of an interaction, where every step succeeds as expected.
This lesson builds directly on that foundation by introducing control flow. Real-world systems are rarely linear; they involve conditional logic, error handling, and repetition. Our goal is to model these conditional and repeated interactions using UML's standard "interaction fragments." Specifically, you will learn to use the alt, opt, and loop keywords in Mermaid to create far more realistic and comprehensive sequence diagrams.
Conceptual Overview: Modeling Logic in Diagrams
Before we dive into the Mermaid syntax, let's establish a conceptual understanding of what we're trying to achieve. In programming, you use constructs like if/else, if, and for/while loops to control the flow of execution. Sequence diagrams have equivalent visual constructs called combined fragments.
The following short video from the "Passionate Business Analyst" channel provides an excellent high-level introduction to these fragments in UML.
Learn UML Sequence Diagram Under 10 minutes [Tutorial] for Business Analyst
Watch the segment explaining combined fragments. It introduces the purpose of the alt, opt, loop, and par (parallel) fragments.
Focus on the definitions provided from this section. This will give you a clear mental model for each type of fragment before we tackle the syntax.
As the video explains, these fragments are visual containers drawn around a group of messages to show that they execute under special conditions. Now, let's see how to write them in Mermaid.
The Building Blocks of Control Flow
Mermaid provides simple, block-based syntax for the most common fragments. A block starts with a keyword (alt, opt, or loop) and ends with end.
The "Mermaid Sequence Diagram Syntax" guide offers a clear and concise reference for these blocks. We'll work through them one by one.
alt: Alternative Paths (if/else)
The alt fragment is used for mutually exclusive choices, just like an if-else statement in code. The block is divided into two or more sections by the else keyword. Only one of these sections will ever be executed.
Mermaid Sequence Diagram Syntax: Arrows, Activations, Loops (Examples) | MacMD Viewer
First, read the brief description of the alt block to understand its purpose and syntax. Then, review the FAQ entry that clarifies the distinction between alt and opt.
Please read the section on Conditional Blocks for the syntax and a clear login example. Then, find the FAQ section at the end of the page and read the answer to the question comparing alt and opt.
opt: Optional Sequences (if)
The opt fragment models a sequence of messages that is optional. If the specified condition is met, the interactions inside the block occur; otherwise, they are skipped entirely. This is equivalent to an if statement without an else block.
Mermaid Sequence Diagram Syntax: Arrows, Activations, Loops (Examples) | MacMD Viewer
Now, let's look at the opt block in the same guide.
Read the section on Optional Blocks. The "Cache miss" scenario is a perfect, practical example of an optional interaction.
loop: Repetitive Sequences (for/while)
Finally, the loop fragment is used to show that a sequence of messages can be repeated multiple times, such as when polling an endpoint or iterating over a collection.
Mermaid Sequence Diagram Syntax: Arrows, Activations, Loops (Examples) | MacMD Viewer
The last fundamental block is the loop.
Read the short section on Loops. The "Heartbeat ping" example clearly illustrates a repetitive action.
Case Study: A "Place Order" Scenario
Now that you've seen the individual building blocks, let's analyze how they combine to document a realistic workflow. The following diagram models a user placing an order.

This single diagram effectively communicates a complex set of business rules:
loop [for each order item]: The process begins by iterating through each item in the customer's order. The messages inside this block will execute once for every item. This is the outer container for the core logic.alt [Member Type = VIP] / [Member Type = Ordinary]: Inside the loop, for each item, the system checks the member's status.- If the member is a
VIP, adispatchmessage is sent to theCourierparticipant. - Otherwise (the
elsecase), thedispatchmessage is sent to theMailparticipant.
Thisaltblock ensures that only one of these two dispatch paths is taken for each order item.
- If the member is a
opt [needs confirmation]: After the loop completes, the system checks if a confirmation is required. If it is, aconfirmmessage is sent to theNotificationservice. If not, this step is skipped entirely.
Here is the Mermaid code that generates the "Place Order Scenario" diagram. You can see how the loop, alt, and opt blocks are nested to represent the logic.
Feel free to copy this code into a Mermaid editor to see it render and to experiment with changes.
Your Turn: Modeling a Polling Mechanism
Let's apply what you've learned. Consider the following scenario:
A front-end
Clientstarts a long-running data processingJobon aServer. TheClientthen needs to poll theServerevery 5 seconds to check the job's status.
- If the server responds with a status of
'in_progress', the client does nothing and waits for the next poll.- If the server responds with
'completed', the client sends a final request to get theJob Resultand then stops polling.- If the server responds with
'failed'-, the client logs an error and stops polling.
Your task is to create a Mermaid sequence diagram that models this polling flow.
Hints:
- Use a
loopfor the polling action. - Inside the loop, use an
altblock to handle the three possible statuses ('in_progress','completed','failed'). - The official Mermaid syntax includes a
breakkeyword, which can be used inside a loop to show that the loop terminates.
Click to see one possible solution
Breakdown of the solution:
- An outer
loopis labeled "Every 5s" to describe the repetition. - An
altblock handles the "completed" case. Inside it, the client makes a final call for the result and then abreakblock terminates the loop. - An
elseclause handles the "failed" case, also ending with abreak. - A final
elseclause covers the "in_progress" case, where the server simply responds and the loop continues naturally.
Conclusion
In this lesson, you've added the crucial dimension of control flow to your sequence diagrams. By mastering interaction fragments, you can now move beyond simple, linear "happy paths" and create diagrams that accurately document the complex, real-world logic of the systems you build.
Our key takeaways are:
altfor Alternatives: Usealtwithelseto modelif-elselogic, where exactly one of several paths must be taken.optfor Optionals: Useoptto modeliflogic without anelse, for actions that might be skipped entirely.loopfor Repetition: Useloopto show repeating sequences of messages, like polling, iteration, or heartbeat checks.- Nesting: These fragments can be nested to represent complex, multi-layered business rules and technical protocols.
This lesson concludes our module on sequence diagrams. You now have the tools to model complex runtime interactions, from simple API calls to intricate, conditional workflows.
In our next lesson, we will shift our perspective. Instead of modeling the interactions between different components, we will begin our study of State Diagrams, which are used to model the internal lifecycle of a single component as it transitions between different states in response to events.
Can't find a good explanation? Sign up and we'll make it for you
Sign up