UML Sequence Diagrams: A Comprehensive Reference
1. Overview
Sequence diagrams are a fundamental tool in UML (Unified Modeling Language) used to visualize and document the dynamic behavior of systems by modeling the interactions between objects or actors over time. They answer the question: "How do components communicate with each other to achieve a specific goal?"
Purpose: Sequence diagrams capture the temporal ordering of messages exchanged between participants, making them invaluable for understanding complex workflows, API designs, system integrations, and debugging multi-component interactions.
Part of UML Behavioral Diagrams: Sequence diagrams belong to the interaction diagrams family, alongside communication diagrams, timing diagrams, and interaction overview diagrams. They emphasize the chronological flow and message passing rather than structural relationships.
When to Use Sequence Diagrams:
- API Design: Document request-response patterns and payload transformations
- System Integration: Model interactions between microservices, third-party systems, or legacy components
- Debugging Complex Flows: Trace execution paths in multi-threaded or distributed systems
- Security Workflows: Visualize authentication, authorization, and token exchange mechanisms
- Business Process Modeling: Show workflows involving multiple departments or systems
- Design Reviews: Communicate design intent and discover edge cases early
2. Core Elements & Notation
Sequence diagrams consist of several fundamental building blocks. Understanding each element is essential for reading and creating effective diagrams.
2.1 Actors and Participants
Actors (typically shown as stick figures) represent external users or systems that initiate interactions. Objects/Participants (shown as rectangles at the top) represent instances of classes or system components. Each participant has a unique lifeline extending downward.
2.2 Lifelines
A lifeline is a vertical dashed line extending from each participant representing its existence over the time span of the diagram. The lifeline starts at the top of the diagram and continues downward, with time flowing from top to bottom.
2.3 Activation Bars
Activation bars (thin rectangles on the lifeline) indicate when a participant is actively processing or executing code. The height of the bar represents the duration of processing. Nested activation bars show nested method calls.
2.4 Messages and Arrows
Messages represent communication between participants. Each message type has distinct notation:
- Synchronous Message (Solid Arrow →): Caller blocks until receiving a response. Typical method call.
- Asynchronous Message (Open Arrow ⇢): Caller continues without waiting. Used for signals or fire-and-forget operations.
- Return Message (Dashed Arrow ⇠): Explicit return value from a synchronous call. Optional but recommended for clarity.
- Self-Message (Loop Back Arrow): Participant sends a message to itself, representing internal method calls or recursive processing.
- Creation Message: Message creating a new instance, targeting the top of a new participant's lifeline.
- Destruction (X): Explicit marker on a lifeline indicating object destruction or process termination.
Here's a basic notation overview in text form:
┌──────────────────────────────────────────────────────────────────────────────────────────┐ │ Sequence Diagram — Notation Overview │ │ │ │ ┌───────┐ ┌───────┐ ┌───────────┐ │ │ │ Actor │ │ Order │ │ Database │ │ │ └───┴───┘ └───┴───┘ └─────┴─────┘ │ │ │ │ │ │ │ ┊ ┊ ┊ │ │ ┊ ┊ ┊ │ │ │ place_order() │ │ │ │ │─────────────────────────────▶ │ │ │ │ │ │ │ │ │ │ save() │ │ │ │ │─────────────────────────────▶ │ │ │ │ │ │ │ │ │ ok │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ │ │ │ confirm │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ │ │ │ │ notify │ │ │ │ │─────────────────────────────⇢ │ │ │ │ │ │ │ │ time fl│ws downward ──▶ │ │ │ └──────────────────────────────────────────────────────────────────────────────────────────┘
3. Message Types in Detail
3.1 Synchronous vs Asynchronous Calls
Synchronous calls block the caller until a response is received. The caller's activation bar extends through the callee's processing and return. Use for tightly coupled operations where the result is needed immediately.
Asynchronous calls allow the caller to continue processing immediately without waiting. The caller's activation bar ends before the asynchronous message is fully processed. Use for event-driven architectures, background tasks, and loosely coupled systems.
3.2 Request-Response Patterns
The classic request-response pattern shows synchronous communication:
┌────────────────────────────────────────────────────────────────────┐ │ Request-Response Pattern (Synchronous) │ │ │ │ ┌─────────┐ ┌─────────┐ │ │ │ Client │ │ Server │ │ │ └────┴────┘ └────┴────┘ │ │ │ │ │ │ │ request │ │ │ │──────────────────────────────────▶ │ │ │ │ │ │ │ │ │ │ │ response │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ └────────────────────────────────────────────────────────────────────┘
3.3 Callbacks and Listeners
In callback patterns, the initial caller becomes the callee later. Object A calls Object B with a callback, then B invokes the callback asynchronously when work is complete:
┌────────────────────────────────────────────────────────────────────┐ │ Callback / Listener Pattern │ │ │ │ ┌───────────┐ ┌───────────┐ │ │ │ Object A │ │ Object B │ │ │ └─────┴─────┘ └─────┴─────┘ │ │ │ │ │ │ │ register(callback) │ │ │ │──────────────────────────────────▶ │ │ │ │ │ │ │ │ │ │ │ callback(result) │ │ │ ⇠──────────────────────────────────│ │ │ │ │ │ └────────────────────────────────────────────────────────────────────┘
3.4 Signals and Events
Signals are asynchronous one-way communications. Unlike method calls, they don't expect an immediate response. Useful for event-driven systems where components respond to events emitted by others.
┌────────────────────────────────────────────────────────────────────┐ │ Signals & Events (Asynchronous) │ │ │ │ ┌─────────────┐ ┌─────────────┐ │ │ │ EventSource │ │ Subscriber │ │ │ └──────┴──────┘ └──────┴──────┘ │ │ │ │ │ │ │ event │ │ │ │──────────────────────────────────⇢ │ │ │ │ │ │ │ │ │ └────────────────────────────────────────────────────────────────────┘
3.5 Found and Lost Messages
Found messages originate from an unspecified source (shown as a filled circle on the message start). Lost messages go to an unspecified destination (shown as a filled circle on the message end). Use these when the source or destination is unknown or outside the diagram scope.
4. Combined Fragments
Combined fragments add control flow logic to sequence diagrams, allowing you to represent conditionals, loops, parallelism, and other complex behaviors.
4.1 alt (Alternatives / If-Else)
Represents mutually exclusive alternatives. The diagram shows multiple interaction sequences, each guarded by a condition. Only one interaction sequence executes based on the condition's truth value.
┌──────────────────────────────────────────────────────────────────────────────────────────┐ │ Combined Fragment: alt (Alternatives / If-Else) │ │ │ │ ┌───────────┐ ┌───────┐ ┌─────────┐ │ │ │ Customer │ │ Store │ │ Payment │ │ │ └─────┴─────┘ └───┴───┘ └────┴────┘ │ │ │ │ │ │ │ │ order │ │ │ │ │───────────────────────────────▶ │ │ │ │ │ │ │ │ ┌─ alt: card valid ? ──────────────────────────────────────────────────────────┐ │ │ │ [ if card valid ] │ │ │ │ │ │ charge │ │ │ │ │──────────────────────────────▶ │ │ │ │ success │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ --- else --- │ │ │ │ │ │ error │ │ │ │ │──────────────────────────────▶ │ │ │ │ fail │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ └──────────────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ │ │ │ result │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ │ │ └──────────────────────────────────────────────────────────────────────────────────────────┘
4.2 opt (Optional)
Represents an optional interaction sequence that executes only if a condition is true. Simpler than alt when there's only one conditional path.
┌──────────────────────────────────────────────────────────────────────────────────────────┐ │ Combined Fragment: opt (Optional Path) │ │ │ │ ┌───────┐ ┌───────┐ ┌─────────┐ │ │ │ User │ │ App │ │ Logger │ │ │ └───┴───┘ └───┴───┘ └────┴────┘ │ │ │ │ │ │ │ │ login │ │ │ │ │───────────────────────────────▶ │ │ │ │ │ │ │ │ ┌─ opt: if debug enabled ──────────────────────────────────────────────────────┐ │ │ │ │ log_event │ │ │ │ │──────────────────────────────▶ │ │ │ │ logged │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ └──────────────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ │ │ │ success │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ │ │ └──────────────────────────────────────────────────────────────────────────────────────────┘
4.3 loop
Represents a repeated interaction sequence. The condition determines when the loop continues or terminates.
┌──────────────────────────────────────────────────────────────────────────────────────────┐ │ Combined Fragment: loop (Iteration) │ │ │ │ ┌─────────┐ ┌─────────┐ ┌───────────┐ │ │ │ Client │ │ Server │ │ Database │ │ │ └────┴────┘ └────┴────┘ └─────┴─────┘ │ │ │ │ │ │ │ │ start │ │ │ │ │───────────────────────────────▶ │ │ │ │ │ │ │ │ ┌─ loop: while items remain ───────────────────────────────────────────────────┐ │ │ │ │ fetch_item │ │ │ │ │──────────────────────────────▶ │ │ │ │ row │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ ─→ process │ │ │ └──────────────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ │ │ │ done │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ │ │ └──────────────────────────────────────────────────────────────────────────────────────────┘
4.4 break
Represents an exception path or early exit from an interaction. If the break condition occurs, the normal sequence is abandoned and execution jumps to the break sequence.
┌──────────────────────────────────────────────────────────────────────────────────────────┐ │ Combined Fragment: break (Early Exit) │ │ │ │ ┌───────────┐ ┌───────────┐ ┌─────────┐ │ │ │ Processor │ │ WorkQueue │ │ Handler │ │ │ └─────┴─────┘ └─────┴─────┘ └────┴────┘ │ │ │ │ │ │ │ │ check │ │ │ │ │───────────────────────────────▶ │ │ │ │ │ │ │ │ ┌─ break: if error detected ───────────────────────────────────────────────────┐ │ │ │ │ notify_error │ │ │ │ │──────────────────────────────⇢ │ │ │ rollb│ck │ │ │ ◀──────────────────────────────────────────────────────────────│ │ │ └──────────────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ │ └──────────────────────────────────────────────────────────────────────────────────────────┘
4.5 par (Parallel)
Represents interactions that execute in parallel. All parallel interaction sequences may execute concurrently. The diagram continues after all parallel sequences complete.
┌──────────────────────────────────────────────────────────────────────────────────────────────────┐ │ Combined Fragment: par (Parallel Execution) │ │ │ │ ┌─────────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │ │ Coordinator │ │ Task 1 │ │ Task 2 │ │ Task 3 │ │ │ └──────┴──────┘ └────┴────┘ └────┴────┘ └────┴────┘ │ │ │ │ │ │ │ │ │ start │ │ │ │ │ │───────────────────────⇢ │ │ │ │ │ st│rt │ │ │ │ │───────────────────────────────────────────────⇢ │ │ │ │ │ start │ │ │ │ │───────────────────────────────────────────────────────────────────────⇢ │ │ │ │ │ │ │ │ ┌─ par: parallel execution ───────────────────────────────────────────────────────────┐ │ │ │ all three tasks p│ocess concurrently │ │ │ │ └─────────────────────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ │ │ │ │ done │ │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ do│e │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ done │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ │ │ └──────────────────────────────────────────────────────────────────────────────────────────────────┘
4.6 critical (Critical Section)
Represents a critical section that must execute atomically without interruption. Used in concurrent systems to indicate synchronized or protected code regions.
4.7 neg (Negative Case)
Represents an interaction that should NOT happen. Used to document invalid or forbidden sequences. Helpful for documenting what the system must prevent.
4.8 ref (Reference to Another Diagram)
References another sequence diagram, allowing you to decompose complex diagrams into smaller, reusable components. The referenced diagram is shown as a box labeled "ref" with the diagram name.
4.9 seq (Strict Sequencing)
Enforces strict sequential ordering. Messages within a seq fragment must occur in the order shown, with no interleaving from other sources.
5. Example: E-Commerce Order Flow
Let's model a complete e-commerce order processing system involving multiple services and external systems. This example demonstrates synchronous calls, asynchronous messages, and error handling.
5.1 Interaction Sequence Description
Participants:
- User/Browser: Customer interface
- API Gateway: Entry point, authentication, routing
- Order Service: Manages order creation and persistence
- Payment Service: Processes payment transactions
- Inventory Service: Manages stock levels
- Notification Service: Sends order confirmations (async)
5.2 Text-Based Diagram
┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ │ E-Commerce Order Flow │ │ │ │ ┌───────┐ ┌─────────┐ ┌─────────┐ ┌───────┐ ┌─────────┐ ┌───────────┐ ┌─────────┐ │ │ │ User │ │ Browser │ │ API GW │ │ Order │ │ Payment │ │ Inventory │ │ Notify │ │ │ └───┴───┘ └────┴────┘ └────┴────┘ └───┴───┘ └────┴────┘ └─────┴─────┘ └────┴────┘ │ │ │ │ │ │ │ │ │ │ │ │ submit order │ │ │ │ │ │ │ │ │─────────────────▶ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ POST /orders │ │ │ │ │ │ │ │ │─────────────────▶ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ create_order() │ │ │ │ │ │ │ │ │─────────────────▶ │ │ │ │ │ │ │ │ │ ─→ persist to DB│ │ │ │ │ │ │ │ order_id │ │ │ │ │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ charge(│99.99) │ │ │ │ │ │ │ │───────────────────────────────────▶ │ │ │ │ │ │ │ │ │ ─→ process payme│t │ │ │ │ │ │ suc│ess │ │ │ │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ reserve(qty=2) │ │ │ │ │ │ │ │─────────────────────────────────────────────────────▶ │ │ │ │ │ │ │ │ │ ─→ check & reduc│ │ │ │ │ │ │ reserved │ │ │ │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ send_│mail │ │ │ │ │ │ │───────────────────────────────────────────────────────────────────────⇢ │ │ │ │ │ │ │ │ │ │ │ │ │ 200 OK │ │ │ │ │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ │ │ender confirmatio│ │ │ │ │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ Notify │rocesses email as│nchronously in ba│kground │ │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
5.3 Step-by-Step Explanation
- User Submits Order: Customer clicks "Place Order" in browser
- Browser to API Gateway: Sends POST request with order details and auth token
- API Gateway to Order Service: Validates request, creates order object
- Order Service Persists: Stores order in database, returns order ID
- Order Service to Payment Service: Initiates payment charge (synchronous, critical path)
- Payment Service Processes: Communicates with payment gateway, returns success/failure
- Order Service to Inventory Service: Reserves inventory items (synchronous)
- Inventory Service Validates & Updates: Checks stock, reduces quantities, returns confirmation
- Order Service to Notification Service (Async): Sends fire-and-forget notification for confirmation email
- API Gateway to Browser: Returns 200 OK with order details
- Browser Renders: Shows order confirmation page to user
- Notification Service (Background): Sends confirmation email asynchronously
6. Example: Authentication Flow (OAuth 2.0)
OAuth 2.0 is a widely-used authorization framework. Here's the Authorization Code Flow, which is the most secure option for user-facing applications.
6.1 OAuth 2.0 Authorization Code Flow
┌────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ │ OAuth 2.0 Authorization Code Flow │ │ │ │ ┌───────┐ ┌─────────────┐ ┌─────────────┐ ┌───────────┐ │ │ │ User │ │ Client App │ │ Auth Server │ │ Resource │ │ │ └───┴───┘ └──────┴──────┘ └──────┴──────┘ └─────┴─────┘ │ │ │ │ │ │ │ │ │ login │ │ │ │ │ │───────────────────────────▶ │ │ │ │ │ │redirect (client_id, scope)│ │ │ │ │ │───────────────────────────▶ │ │ │ │ auth│page │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ │ │ │ │ │ grant (credentials) │ │ │ │ │ │───────────────────────────▶ │ │ │ │ │ │ auth check │ │ │ │ │ │───────────────────────────▶ │ │ │ │ │ authorization code │ │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ redirect + code │ │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ │ │ │ │ │ │ │ exchange (code, secret) │ │ │ │ │ │───────────────────────────▶ │ │ │ │ │ccess_token + refresh_token│ │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ │ │ │ │ │ │ request (ac│ess_token) │ │ │ │ │───────────────────────────────────────────────────────▶ │ │ │ │ user│data │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ │ │ │ │ logged in │ │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
6.2 Token Refresh Flow (Happens Later)
When the access token expires, the client uses the refresh token to obtain a new access token without requiring the user to re-authenticate.
┌────────────────────────────────────────────────────────────────────┐ │ OAuth 2.0 — Token Refresh Flow │ │ │ │ ┌─────────────┐ ┌─────────────┐ │ │ │ Client App │ │ Auth Server │ │ │ └──────┴──────┘ └──────┴──────┘ │ │ │ │ │ │ │ refresh_token │ │ │ │──────────────────────────────────▶ │ │ │ │ │ │ │ │ │ │ │ new access_token │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ └────────────────────────────────────────────────────────────────────┘
7. Example: Microservices Saga Pattern
The Saga pattern solves the distributed transaction problem in microservices architectures. Here's a choreography-based saga with compensating transactions on failure.
7.1 Choreography-Based Saga: Trip Booking
Scenario: User books a trip including flight, hotel, and rental car. If any reservation fails, previous reservations are rolled back via compensating transactions.
┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ │ Saga Pattern — Choreography with Compensating Transactions │ │ │ │ ┌───────┐ ┌─────────────┐ ┌───────────────┐ ┌───────────────┐ ┌─────────────┐ │ │ │ User │ │ TripService │ │ FlightService │ │ HotelService │ │ CarService │ │ │ └───┴───┘ └──────┴──────┘ └───────┴───────┘ └───────┴───────┘ └──────┴──────┘ │ │ │ │ │ │ │ │ │ │ book trip │ │ │ │ │ │ │──────────────────────▶ │ │ │ │ │ │ │ │ │ │ │ │ │ │ reserve flight │ │ │ │ │ │ │──────────────────────▶ │ │ │ │ │ │ flight ok │ │ │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ │ │ │ │ │ │ │ │ reserv│ hotel │ │ │ │ │ │─────────────────────────────────────────────▶ │ │ │ │ │ hote│ ok │ │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ │ │ │ │ │ │ │ │ reserve car │ │ │ │ │ │────────────────────────────────────────────────────────────────────▶ │ │ │ │ │ CAR FAILED │ │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ │ │ │ │ --- Com│ensating Transactions │egin --- │ │ │ │ │ │ │ │ │ │ │ │ │ │ cancel│hotel │ │ │ │ │ │─────────────────────────────────────────────⇢ │ │ │ │ │ canc│lled │ │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ │ │ │ │ │ │ │ cancel flight │ │ │ │ │ │ │──────────────────────⇢ │ │ │ │ │ │ cancelled │ │ │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ │ │ │ │ │ │ │ trip booking failed │ │ │ │ │ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│ │ │ │ │ │ │ │ │ │ │ │ └──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
7.2 Key Saga Concepts
- Choreography: Services emit events; other services listen and react. Decoupled but can be harder to trace.
- Orchestration: Central orchestrator directs each service. Easier to understand but creates a single point of control.
- Compensating Transactions: Explicit rollback operations that undo previous actions (e.g., cancel flight, refund payment).
- Idempotency: Each operation must be safe to retry; otherwise, retries during recovery can cause data corruption.
8. Mermaid.js Code Examples
Mermaid.js is a JavaScript-based diagramming library that renders diagrams from text descriptions. You can include these code blocks in documentation and render them dynamically in web pages.
8.1 E-Commerce Order Flow in Mermaid
sequenceDiagram
actor User
participant Browser
participant API as API Gateway
participant Order as Order Service
participant Payment as Payment Service
participant Inventory as Inventory Service
participant Notify as Notification Service
User->>Browser: Click Place Order
Browser->>API: POST /orders (cart, auth)
API->>Order: create_order()
Order->>Order: persist to DB
Order-->>API: order_id
Order->>Payment: charge($99.99)
Payment->>Payment: process with gateway
Payment-->>Order: success
Order->>Inventory: reserve_items(qty: 2)
Inventory->>Inventory: check stock, reduce
Inventory-->>Order: reserved
Order->>Notify: send_confirmation(async)
API-->>Browser: 200 OK (order details)
Browser->>User: Render confirmation
par Background Processing
Notify->>Notify: send email
end
8.2 OAuth 2.0 Flow in Mermaid
sequenceDiagram
actor User
participant Client as Client App
participant Auth as Auth Server
participant Resource as Resource Server
User->>Client: Click "Login with OAuth"
Client->>Auth: Redirect to login (client_id, scope, redirect_uri)
Auth->>User: Display login form
User->>Auth: Submit credentials
Auth->>Auth: Validate credentials
Auth-->>Client: Redirect with authorization code
Client->>Auth: Exchange code for token (client_id, secret, code)
Auth->>Auth: Validate code and client
Auth-->>Client: Access token + Refresh token
Client->>Resource: Request user data (access token)
Resource->>Resource: Validate token
Resource-->>Client: User profile data
Client-->>User: Logged in, show dashboard
8.3 Saga Pattern Compensating Transactions in Mermaid
sequenceDiagram
participant Trip as Trip Service
participant Flight as Flight Service
participant Hotel as Hotel Service
participant Car as Car Service
participant Payment as Payment Service
Trip->>Flight: Reserve flight
Flight->>Flight: Check availability
Flight-->>Trip: OK
Trip->>Hotel: Reserve hotel
Hotel->>Hotel: Check availability
Hotel-->>Trip: OK
Trip->>Car: Reserve car
Car->>Car: Check availability
Car-->>Trip: FAILED - No cars available
Note over Trip: Compensating transactions begin
Trip->>Hotel: Cancel reservation
Hotel->>Hotel: Release booking
Hotel-->>Trip: Cancelled
Trip->>Flight: Cancel reservation
Flight->>Flight: Release booking
Flight-->>Trip: Cancelled
Trip->>Payment: Refund authorization
Payment->>Payment: Process refund
Payment-->>Trip: Refunded
Trip-->>Trip: Trip booking saga FAILED
9. Best Practices
Effective sequence diagrams require discipline and adherence to key principles:
9.1 Diagram Focus and Scope
- One Scenario Per Diagram: Each sequence diagram should illustrate a single, well-defined scenario or use case.
- Keep It Focused: Avoid combining multiple interaction patterns in a single diagram.
- Clear Title: Use a descriptive title that captures the interaction being modeled.
9.2 Participant Limits
- Limit Participants: Aim for 5-7 participants maximum. More than that makes diagrams hard to read.
- Use Reference Diagrams: Employ "ref" fragments to decompose complex interactions across multiple diagrams.
- Group Related Participants: Arrange participants logically (e.g., user-facing components on the left, backend services on the right).
9.3 Message Naming Conventions
- Use Method Names: Name messages after actual method calls in your codebase (e.g., `charge()`, `reserve_items()`).
- Include Parameters: Show important parameters: `charge($99.99)`, `reserve(qty: 2, item_id: ABC123)`.
- Show Return Values: Include return values for clarity: `--→ order_id` or `←-- success`.
9.4 Happy Path and Error Paths
- Start with Happy Path: First show the successful, non-error scenario.
- Error Paths Separately: Create additional diagrams for failure scenarios and exception handling.
- Use alt Fragments: When error paths are brief, use `alt` combined fragments within a single diagram.
9.5 Combined Fragments Usage
- Use Sparingly: Combined fragments add complexity; use them only when necessary.
- Label Clearly: Always label combined fragments with conditions and guard expressions.
- Keep Nesting Shallow: Avoid deeply nested combined fragments; use reference diagrams instead.
9.6 Synchronous vs Asynchronous
- Synchronous for Critical Paths: Use synchronous messages when the caller must wait for a response.
- Asynchronous for Independence: Use asynchronous messages for fire-and-forget operations and event notifications.
- Be Explicit: Clearly distinguish between synchronous and asynchronous to avoid confusion about blocking behavior.
9.7 Documentation and Clarity
- Add Notes: Use note boxes to explain non-obvious behavior or assumptions.
- Version Control: Keep sequence diagrams in version control alongside code.
- Keep Updated: Sequence diagrams must stay synchronized with actual implementation; outdated diagrams mislead.
10. Tools for Creating Sequence Diagrams
Multiple tools support sequence diagram creation, each with different strengths and workflows:
10.1 PlantUML
PlantUML is a text-based diagram generator supporting UML and non-UML diagrams. Write diagram code as plain text, then PlantUML renders PNG or SVG output. Integrates with many IDEs (VS Code, IntelliJ, etc.) and documentation generators (Sphinx, MkDocs). Free and open-source. Excellent for version-controlling diagrams as code.
10.2 Mermaid.js
Mermaid.js is a JavaScript library enabling diagram creation from markdown-like syntax. Renders in the browser natively, integrates with GitHub README files, and supports Jekyll/static sites. Simpler syntax than PlantUML; ideal for documentation sites and collaborative platforms. Free and open-source. Perfect for embedding diagrams in web pages.
10.3 Lucidchart
Lucidchart is a cloud-based diagramming platform with a visual editor. Offers extensive UML support, real-time collaboration, and integration with other tools (Jira, Confluence, Google Workspace). Paid (free tier available). Best for teams requiring visual, collaborative diagramming.
10.4 Draw.io (now diagrams.net)
Draw.io (diagrams.net) is a free, open-source diagramming tool available online and as a desktop app. Supports sequence diagrams, flowcharts, and UML. Integrates with Google Drive, GitHub, Confluence. Simple visual editor with drag-and-drop interface.
10.5 Visual Paradigm
Visual Paradigm is a comprehensive UML and software modeling tool. Professional-grade with advanced features: model-driven development, reverse engineering, code generation. Paid (community edition available). Best for large enterprises and complex modeling needs.
10.6 Figma Plugins
Figma offers various diagram plugins (e.g., FigJam, third-party plugins). Excellent for design teams; integrates with design workflow. Paid (with free tier). Best when diagramming is secondary to design work.
11. Conclusion
Sequence diagrams are indispensable for documenting system interactions, designing APIs, and communicating technical architecture with stakeholders. By mastering the core notation, message types, combined fragments, and best practices outlined in this guide, you'll be equipped to create clear, maintainable, and effective sequence diagrams that serve as living documentation of your system's behavior.
Start simple—document your happy paths first, then add error and edge-case scenarios. Use text-based tools like PlantUML or Mermaid.js to version control your diagrams alongside code. Keep diagrams focused, use consistent naming conventions, and update them as your system evolves.