When you model real software behavior, simple message arrows between objects don't cut it. You need conditional branches and repeated actions the kind of logic every developer deals with daily. That's exactly where UML sequence diagram code examples with alt and loop fragments come in. They let you express "if this, then that" and "do this N times" directly inside your diagram, turning a flat message flow into something that actually reflects how your system works.
What do alt and loop fragments mean in a sequence diagram?
In UML sequence diagrams, fragments are interaction operators that wrap a section of messages inside a labeled box. Two of the most commonly used are:
- alt (alternative) Models conditional logic, similar to an if/else statement. The sequence splits into one or more operands separated by dashed lines. Only one operand executes, depending on the condition.
- loop Models repetition. Messages inside the loop fragment repeat based on a condition or a set number of iterations, much like a for or while loop.
These fragments live inside a rectangular frame at the top-left corner of the box, labeled with the operator keyword (like alt or loop) followed by an optional condition in square brackets.
How do you write an alt fragment in code?
Here's a practical alt fragment using PlantUML syntax. This models a login flow where a user either succeeds or fails authentication:
@startuml
actor User
participant "Auth Service" as Auth
participant Database as DB
User -> Auth: login(username, password)
Auth -> DB: queryUser(username)
DB --> Auth: userData
alt password is correct
Auth --> User: 200 OK (token)
else password is incorrect
Auth --> User: 401 Unauthorized
end
@enduml
The alt keyword starts the fragment. Each operand is separated by a line beginning with else. The end keyword closes the fragment. The conditions appear in square brackets in the rendered diagram.
You can add as many else branches as needed. For example, a third branch could handle an account-locked scenario.
How do you write a loop fragment in code?
Suppose a service needs to retry a failed API call up to three times. Here's how that looks as a loop fragment:
@startuml
participant Client
participant "Payment Gateway" as PG
Client -> PG: processPayment(orderId, amount)
loop retry up to 3 times
PG --> Client: timeout / error
Client -> PG: processPayment(orderId, amount)
end
alt payment successful
PG --> Client: 200 OK (receiptId)
else all retries failed
PG --> Client: 500 Payment Failed
end
@enduml
The condition after the loop keyword describes the iteration rule. In the rendered diagram, it appears inside brackets next to the "loop" label in the fragment's top-left corner.
If you're working with Mermaid syntax for REST API call flows, the approach is similar but uses a slightly different structure with loop and alt blocks directly in the Mermaid code.
Can you combine alt and loop fragments in the same diagram?
Absolutely and you should when the scenario requires it. Real-world processes rarely have just one kind of branching or repetition. Here's an example of nested fragments in PlantUML that models an order processing system:
@startuml
participant "Order Service" as Order
participant Inventory
participant "Shipping Service" as Ship
Order -> Inventory: checkStock(items)
loop for each item in order
Inventory -> Inventory: verifyQuantity(item)
alt item in stock
Inventory --> Order: available(item)
else item out of stock
Inventory --> Order: unavailable(item)
end
end
alt all items available
Order -> Ship: createShipment(orderId)
Ship --> Order: trackingNumber
Order --> Order: 200 OK
else partial or no availability
Order --> Order: 409 Conflict
end
@enduml
Notice how the inner alt sits completely inside the loop block. This nesting tells the reader: "for each item, check if it's in stock, then branch on the result." The outer alt happens after the loop finishes and acts on the overall result.
This kind of nested structure is common in microservices architecture diagrams, where multiple services interact with conditional and repeated calls.
What other fragments pair well with alt and loop?
While alt and loop cover most use cases, UML defines several other interaction operators worth knowing:
- opt Optional execution (like an
ifwithout anelse). Messages inside only run when the condition is true. - par Parallel execution. Two or more message sequences happen at the same time.
- break Interrupts the enclosing fragment when a condition is met, skipping remaining messages.
- critical Marks a section as atomic; no interleaving with other messages is allowed.
- ref References another sequence diagram (useful for decomposing complex flows).
Each of these uses the same framing syntax: a rectangle with the operator name in the top-left corner, conditions in brackets, and dashed lines separating operands. You can find more on the full sequence diagram syntax reference for additional operators and markup rules.
What are common mistakes with alt and loop fragments?
These errors show up frequently, especially when people start modeling more complex flows:
- Missing the
endkeyword. Every fragment that opens withalt,loop,opt, etc. must close withend. Forgetting this breaks the rendering entirely. - Overlapping fragments instead of nesting. If an inner fragment doesn't close before the outer one closes, the diagram won't render correctly. Fragments must be fully contained within one another, not partially overlapping.
- Vague or missing conditions. Writing
alt successwithout specifying what "success" means makes the diagram hard to interpret. Be precise:alt statusCode == 200is clearer. - Using alt when opt would be simpler. If there's no
elsebranch just an optional message useoptinstead. It reads cleaner and signals intent better. - Too many nested levels. More than two or three levels of nesting makes a diagram nearly unreadable. If you're going that deep, consider splitting the flow across multiple diagrams using
reffragments.
Practical tips for writing clear alt and loop fragments
- Write the condition text as if it were code.
alt user.role == "admin"is better thanalt user is admin. Precision reduces ambiguity during reviews. - Order operands by likelihood. Put the most common path first (the main success scenario), then list error or edge cases as
elsebranches. - Keep loop boundaries tight. Only include the messages that actually repeat. If some messages happen before or after the repeated section, pull them outside the loop frame.
- Use combined fragments for readability. In PlantUML, you can group alt and loop together with surrounding messages in a single diagram to tell the full story of a use case.
- Test your code in a renderer before sharing. Tools like PlantUML's online server or a local Mermaid preview catch syntax errors fast.
A quick checklist before you share your diagram
- Every
alt,loop, andoptblock has a matchingend. - Conditions are written in brackets with specific, readable text.
- Fragments are properly nested no overlapping boundaries.
- Loop counts or conditions are explicit (
loop 5 timesorloop while retryCount < 3). - The diagram renders without errors in your chosen tool.
- Someone unfamiliar with the system can follow the flow without guessing.
Start by picking one real scenario from your codebase a payment retry, a conditional approval workflow, or a batch processing loop and model just that flow with the appropriate fragments. Once the first diagram is clean and accurate, you'll find it much faster to model the next one.
Sequence Diagram Syntax Reference Guide for Software Architects
Plantuml Microservices Sequence Diagram Code and Markup Guide
Sequence Diagram as Code Best Practices with Text-Based Tools
Mermaid Sequence Diagram Code Snippet for Rest Api Call Flow
Best Architecture Diagram Tools for Developers: a Comparison Guide
How to Generate Architecture Diagrams From Code