What Is a Sequence Diagram?

Sequence diagrams show how objects interact over time through ordered message exchanges. They are the most used UML behavioral diagram for documenting API flows, authentication handshakes, and microservice communication.

Definition and where sequence diagrams fit in UML

A sequence diagram is a UML interaction diagram that models the exchange of messages between objects arranged along a horizontal axis, with time progressing vertically downward. What is a sequence diagram in practical terms? It answers the question: in what order do these components talk to each other to complete a specific operation? UML 2.5 defines 14 diagram types split into structure diagrams and behavior diagrams. Sequence diagrams belong to the behavior category, specifically under interaction diagrams alongside communication diagrams, timing diagrams, and interaction overview diagrams. Of these four, sequence diagrams dominate industry usage because their visual format maps naturally to how engineers think about request-response flows. The vertical time axis is the key differentiator. Class diagrams show static relationships. Activity diagrams show control flow without regard to which object performs each action. Sequence diagrams show exactly which object sends a message, which object receives it, and in what order relative to every other message in the interaction. This makes them irreplaceable for documenting distributed system behavior where timing and ordering matter. A sequence diagram for an OAuth 2.0 authorization code flow, for example, shows the exact handshake between the browser, authorization server, and resource server. Each redirect, token exchange, and API call appears in chronological order. You can trace exactly when the access token is issued and which component holds it at each step.

Key elements: lifelines, messages, activation bars, and fragments

Lifelines are the vertical dashed lines extending downward from each participant. Each lifeline represents one object or component in the interaction. Draw a rectangle at the top with the object name and optionally its type, like 'paymentService:PaymentService' or simply ':APIGateway' when the instance name doesn't matter. Messages are the horizontal arrows between lifelines. UML defines several message types. A synchronous message (solid arrowhead) means the sender waits for a response. An asynchronous message (open arrowhead) means the sender continues without waiting. A return message (dashed line) shows the response flowing back. A self-message (arrow looping back to the same lifeline) represents internal processing, like a service validating input before forwarding a request. Activation bars are the thin rectangles overlaid on lifelines showing when an object is actively processing. When the API Gateway receives a request, its activation bar starts. It sends a message to the Auth Service, which gets its own activation bar. The Auth Service returns, its bar ends, and the API Gateway's bar continues as it processes the result. Nested activation bars show re-entrant calls clearly. Combined fragments add control logic. An 'alt' fragment models if/else branching: one operand for the success path, another for the error path, separated by a dashed line with guard conditions like '[status == 200]' and '[status >= 400]'. A 'loop' fragment repeats its content while a condition holds. An 'opt' fragment executes only if a condition is true. A 'par' fragment models parallel execution. Fragments can nest. Stripe's payment processing sequence, for example, uses an alt fragment to branch between successful charges and declined cards, with a loop fragment inside the decline path for retry logic up to three attempts.

When to use sequence diagrams: API flows, auth, and microservices

Sequence diagrams are the right choice when you need to document the temporal ordering of interactions between distinct components. Three scenarios demand them more than any other. API request flows through multiple services are the primary use case. When a mobile app makes a request that passes through an API gateway, hits an auth service, routes to a business logic service, queries a database, and returns an aggregated response, a sequence diagram makes the complete chain visible. Each hop appears as a message arrow. Latency-sensitive teams annotate each message with expected response times: '~50ms' for a Redis cache hit, '~200ms' for a PostgreSQL query, '~2s' for an external payment provider call. Authentication and authorization flows are the second major use case. OAuth 2.0, SAML 2.0, and OpenID Connect all involve multi-party handshakes where the order of operations is critical for security. Drawing the PKCE (Proof Key for Code Exchange) flow as a sequence diagram shows exactly when the code_verifier is generated, when the code_challenge is sent to the authorization server, and when the code_verifier is submitted to exchange for tokens. Without this visual ordering, engineers frequently misimplement these flows. Microservice choreography is the third scenario. When an order placement triggers inventory reservation, payment capture, and shipping label generation across three independent services communicating through events, a sequence diagram shows the event publication and consumption order. It makes race conditions visible. If the shipping service processes the OrderPlaced event before the payment service has confirmed payment, the diagram reveals the gap. Saga patterns with compensating transactions become much clearer when drawn as sequence diagrams with alt fragments for failure cases.

Best practices: limiting messages, naming, and showing error paths

Keep the number of lifelines between 3 and 8 per diagram. More than 8 participants creates a diagram too wide to read on a standard screen. If your interaction involves 12 services, split it into sub-interactions. Draw one sequence diagram for the authentication phase and another for the business logic phase. Reference them using interaction use (ref) fragments. Name lifelines with role names, not implementation details. Use ':AuthService' instead of ':com.company.auth.AuthServiceImpl'. The reader needs to understand which system component is involved, not which Java class handles the request. Include the technology only when it matters for the discussion: ':Redis Cache' or ':PostgreSQL' clarifies the nature of the interaction in a way that ':DataStore' does not. Always show the error path. Most sequence diagrams only illustrate the happy path, which makes them useless for debugging and incident response. Use alt fragments to branch between success and failure. Show what happens when the database times out. Show the retry logic. Show the circuit breaker opening after the fifth consecutive failure. These error paths are where the real architectural complexity lives. Label every message with verb-noun pairs: 'validateToken,' 'createOrder,' 'reserveInventory.' Avoid generic labels like 'call' or 'request.' The message name should tell the reader what is happening without needing to reference another document. Include return values when they affect subsequent behavior: 'return orderId' or 'throw InsufficientFundsException.' Omit return values when they are obvious, like a 200 OK response to a health check. Number messages sequentially (1, 1.1, 1.2, 2) when discussing the diagram in a design document. This lets reviewers reference specific interactions by number during code reviews.

Reading sequence diagrams: following the top-to-bottom timeline

Reading a sequence diagram starts at the top-left and moves downward. The first message is the trigger: a user clicking a button, a cron job firing, or an external system sending a webhook. Follow that message arrow from the sender's lifeline to the receiver's lifeline. The receiver's activation bar begins. Read the messages sent by that receiver before its activation bar ends. This is the call stack. When the Auth Service receives 'validateToken,' it sends 'lookupSession' to Redis, receives the response, then sends 'checkPermissions' to the Permissions DB, receives that response, and finally returns the validation result. The nesting of activation bars shows you the call depth, just like a stack trace. Alt fragments require reading both operands. The guard condition on each operand tells you the branching criteria. Read the top operand first (the condition that evaluates to true in the common case), then the alternatives below the dashed separator. This is where error handling lives. Look for fragments within fragments. A loop inside an alt means retry logic that only applies in certain conditions. Return messages carry important information. A dashed arrow labeled 'return 401 Unauthorized' tells you that the entire subsequent flow depends on this authentication failure. Trace forward from that return to see how the calling service handles the error. Does it retry? Does it redirect the user? Does it propagate the error unchanged? Self-messages indicate internal processing that takes meaningful time or has side effects. When the Order Service sends itself a 'calculateTax' message, it means that calculation is worth calling out as a distinct step, usually because it involves business logic the reader should be aware of. Pay attention to the vertical distance between messages. While not formally specified in UML, longer gaps between messages conventionally indicate longer elapsed time, like waiting for user input or an external API response.

Generating sequence diagrams from text descriptions

Manually drawing sequence diagrams in tools like Visio or Lucidchart means positioning lifelines, dragging message arrows, aligning activation bars, and fiddling with fragment boundaries. For a 15-message interaction with two alt fragments, that's 20 to 30 minutes of layout work before you've communicated a single architectural idea. Text-to-diagram generation flips this workflow. Describe the interaction in natural language: 'User sends login request to API Gateway. API Gateway forwards to Auth Service. Auth Service validates credentials against PostgreSQL. If valid, Auth Service generates JWT and returns it. If invalid, Auth Service returns 401.' The AI parses the participants, message ordering, and branching logic from your description. Sequence diagram generation is particularly well-suited to AI because the format is highly structured. The lifelines are extracted from the nouns. The messages are extracted from the verbs. The ordering follows the sentence order. Alt fragments map to if/else language in the description. This structured mapping means AI generators produce accurate sequence diagrams more reliably than they produce freeform architecture diagrams. The output should be a standard format that works across tools. Draw.io's mxGraphModel XML can represent sequence diagrams with proper lifeline spacing, activation bars, and fragment boundaries. The XML format is portable: open it in Draw.io desktop, the VS Code extension, or embed it in Confluence. Diagrams.so generates sequence diagrams from plain-text descriptions and outputs native .drawio files. Describe your interaction with specific participant names and message labels, and the AI handles lifeline positioning, activation bar timing, and fragment placement. The generated diagrams follow UML 2.5 conventions with proper message arrow types.

Real-world examples

Generate these diagrams with AI

Related guides