Create your own
Lesson illustration

Modeling Logic in Interaction Diagrams

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 diagram shows a complete order process, using a `loop` to process items, an `alt` to handle different member types, and an `opt` for an optional confirmation step.

This single diagram effectively communicates a complex set of business rules:

  1. 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.
  2. 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, a dispatch message is sent to the Courier participant.
    • Otherwise (the else case), the dispatch message is sent to the Mail participant.
      This alt block ensures that only one of these two dispatch paths is taken for each order item.
  3. opt [needs confirmation]: After the loop completes, the system checks if a confirmation is required. If it is, a confirm message is sent to the Notification service. 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 Client starts a long-running data processing Job on a Server. The Client then needs to poll the Server every 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 the Job Result and 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 loop for the polling action.
  • Inside the loop, use an alt block to handle the three possible statuses ('in_progress', 'completed', 'failed').
  • The official Mermaid syntax includes a break keyword, 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 loop is labeled "Every 5s" to describe the repetition.
  • An alt block handles the "completed" case. Inside it, the client makes a final call for the result and then a break block terminates the loop.
  • An else clause handles the "failed" case, also ending with a break.
  • A final else clause 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:

  • alt for Alternatives: Use alt with else to model if-else logic, where exactly one of several paths must be taken.
  • opt for Optionals: Use opt to model if logic without an else, for actions that might be skipped entirely.
  • loop for Repetition: Use loop to 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