If you've ever tried to model real-world application logic in a UML sequence diagram, you know that simple straight-line interactions rarely tell the full story. Programs loop through data, branch on conditions, and handle errors. The loop and alt combined fragments are the tools that let you express all of that in a sequence diagram and knowing how to write them as code (especially in tools like PlantUML) saves you hours of manual diagramming. This article walks through practical code examples, explains the syntax, and covers the mistakes that trip people up.
What Are Loop and Alt Fragments in a Sequence Diagram?
In UML sequence diagrams, a combined fragment is a box that wraps a group of interactions and applies logic to them. The two most common combined fragments you'll encounter are:
- loop repeats a set of messages a specific number of times or until a condition is met.
- alt (alternative) models an if/else branch where one of several alternatives executes based on a condition.
You can nest these fragments, combine them, and use them alongside other operators like opt, break, and par. If you're new to the full syntax, our PlantUML sequence diagram syntax reference covers all the operators in detail.
How Do You Write a Loop Fragment in PlantUML Code?
A loop fragment in PlantUML uses the loop keyword followed by an optional condition in brackets. Here's a basic example:
@startuml
participant Client
participant Server
Client -> Server: Request items
loop every item in cart
Server -> Database: Fetch item details
Database --> Server: Item data
Server --> Client: Send item info
end
Client --> Server: Confirm order
@enduml
This draws a rectangular region labeled loop [every item in cart] around the repeated messages. The text inside the brackets appears as the loop guard it tells anyone reading the diagram what drives the repetition.
Loop with a Fixed Iteration Count
If you want to show a specific number of iterations rather than a condition, you can write:
@startuml
actor User
participant System
User -> System: Start batch process
loop 10 times
System -> Worker: Process batch chunk
Worker --> System: Chunk complete
end
System --> User: All batches done
@enduml
The label on the loop fragment will read loop [10 times], which communicates clearly that this is a fixed-count loop.
How Do You Write an Alt Fragment in PlantUML Code?
An alt fragment models conditional branching. It works like an if/else statement. You separate each branch with the else keyword:
@startuml
participant Browser
participant API
Browser -> API: Login request
alt credentials are valid
API -> Database: Store session
Database --> API: Session stored
API --> Browser: 200 OK + token
else credentials are invalid
API --> Browser: 401 Unauthorized
else account is locked
API --> Browser: 403 Forbidden
end
@enduml
Each branch appears as a separate box within the larger alt rectangle. The conditions display in the top-left corner of each section, making it easy to trace the logic.
Can You Combine Loop and Alt Fragments Together?
Yes and this is where sequence diagrams start modeling real application behavior. Nesting an alt inside a loop (or vice versa) is common in login retry logic, data validation pipelines, and payment processing flows.
@startuml
participant Client
participant AuthServer
Client -> AuthServer: Attempt login
loop retry up to 3 times
alt authentication succeeds
AuthServer --> Client: 200 OK + session
else authentication fails
AuthServer --> Client: 401 Failed
Client -> AuthServer: Retry login
end
end
@enduml
In this example, the loop retries up to three times, and inside each iteration the alt fragment determines whether the attempt succeeded. The diagram shows both the retry behavior and the branching logic in one place.
Nesting Alt Inside a Loop for Data Processing
@startuml
participant Scheduler
participant Processor
participant Storage
participant ErrorHandler
Scheduler -> Processor: Process records batch
loop for each record
Processor -> Processor: Validate record
alt record is valid
Processor -> Storage: Save record
Storage --> Processor: Saved
else record is invalid
Processor -> ErrorHandler: Log error
ErrorHandler --> Processor: Error logged
end
end
Processor --> Scheduler: Batch complete
@enduml
This pattern appears in almost every ETL pipeline or batch processing system. The loop iterates over records while the alt handles valid vs. invalid cases. Understanding the arrow symbols used in these interactions helps you choose between synchronous calls, return messages, and asynchronous signals correctly.
What Other Combined Fragments Pair Well with Loop and Alt?
Beyond loop and alt, PlantUML supports several other fragment operators that you'll often use alongside them:
- opt a single optional block that only executes if a condition is true (like an if without else).
- break exits the enclosing loop early when a condition is met.
- par shows parallel execution of multiple interaction fragments.
- critical marks a section that must complete atomically, with optional else for failure.
- ref references another sequence diagram (useful for keeping diagrams readable).
You can nest any of these inside a loop or alt fragment. For example, placing a break inside a loop is a clean way to show early termination:
@startuml
participant Client
participant API
Client -> API: Search items
loop scan through results
API -> API: Check item
break item matches criteria
API --> Client: Return matching item
end
end
@enduml
What Common Mistakes Do People Make with These Fragments?
After working with many diagrams, these errors come up repeatedly:
- Missing the
endkeyword. Every combined fragment must close withend. Forgetting it produces a syntax error or a garbled diagram. - Wrong nesting order. If you open a
loopthen analt, you must close thealtbefore closing theloop. Think of it like matching parentheses. - Empty condition brackets. Writing
loop []without a meaningful condition leaves diagram readers guessing. Always write a clear guard. - Confusing
altwithopt. Usealtwhen you have two or more branches. Useoptwhen something either happens or doesn't no alternative path. - Overloading one diagram. Combining too many nested fragments in a single diagram makes it unreadable. Use
refto break complex flows into separate diagrams.
When Should You Use Loop and Alt Fragments Instead of Plain Messages?
Not every interaction needs combined fragments. Use them when:
- The behavior depends on a runtime condition (alt) that changes which messages get sent.
- An interaction repeats (loop) and showing each iteration individually would be impractical.
- You want to communicate error handling paths alongside the happy path in one view.
- You're documenting batch or retry logic for a code review or technical specification.
If the interaction is a simple request-response with no branching or repetition, plain messages without fragments are clearer and less cluttered.
Quick Reference: Loop vs. Alt Syntax in PlantUML
| Fragment | Syntax | Use Case |
|---|---|---|
| loop | loop [condition] | Repeated interactions |
| alt | alt [condition] ... else [condition] ... end | If/else branching |
| opt | opt [condition] ... end | Optional single path |
| break | break [condition] ... end | Early exit from loop |
Practical Checklist Before You Finalize Your Diagram
- ☑ Every
loop,alt, andoptblock has a matchingend. - ☑ Nesting order is correct inner fragments close before outer ones.
- ☑ All condition labels are written in plain, readable language.
- ☑ The diagram has a clear entry point and exit point.
- ☑ You've tested the PlantUML code in a renderer to confirm it produces the expected output.
- ☑ Complex flows are split across multiple diagrams using
reffragments where needed. - ☑ You've chosen the right fragment type alt for branches, loop for repetition, opt for optional steps.
Start by writing the happy path as plain messages first. Then add fragments only where branching or repetition genuinely exists. This keeps your diagrams honest and easy to read which is the whole point of drawing them.
Online Code Editor for Sequence Diagrams with Real-Time Preview
Generate Sequence Diagrams From Java Source Code
Plantuml Sequence Diagram Syntax Reference
Uml Sequence Diagram Arrow Symbols and Their Meanings Explained
Uml Diagram Codes Complete Reference Guide and Cheat Sheet
Uml Class Diagram Example with Java Code