LOW-LEVEL DESIGN · MODELING AND UML · UML · 19 OF 48

UML Sequence Diagrams: Lifelines, Messages and Frames Explained

How to read and draw UML sequence diagrams: lifelines, activation bars, synchronous, asynchronous and return messages, and loop, alt and opt frames, all on one real flow, booking bus seats with a hold, a payment that may fail and a ticket message, with matching Java code that prints the same trace.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 14

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 146 lines, with a small main() demo. Save it as SeatBookingSequenceDemo.java, then run javac SeatBookingSequenceDemo.java && java SeatBookingSequenceDemo.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * The bus seat booking flow from the sequence diagram. Each call prints one arrow of the diagram.
 * Prices are in rupees for readability.
 */
public class SeatBookingSequenceDemo {

    static void arrow(String from, String to, String message) {
        System.out.println("  " + from + " -> " + to + ": " + message);
    }

    record Booking(String id, int bus, List<Integer> seats, int price) { }

    record Result(boolean ok, String reason, Booking booking) {
        static Result failed(String reason) {
            return new Result(false, reason, null);
        }

        static Result success(Booking b) {
            return new Result(true, "ok", b);
        }
    }

    enum SeatState { HELD, SOLD }

    /** The seats of one bus. */
    static final class SeatInventory {
        private final Map<Integer, SeatState> taken = new HashMap<>();

        /** loop [for each seat]: hold all or none. */
        synchronized boolean holdAll(List<Integer> seats) {
            List<Integer> held = new ArrayList<>();
            for (int s : seats) {
                arrow("SeatInventory", "SeatInventory", "tryHold(" + s + ")");
                if (taken.containsKey(s)) {
                    held.forEach(taken::remove);      // undo the partial hold
                    return false;
                }
                taken.put(s, SeatState.HELD);
                held.add(s);
            }
            return true;
        }

        synchronized void releaseAll(List<Integer> seats) {
            seats.forEach(taken::remove);
        }

        synchronized void confirmAll(List<Integer> seats) {
            seats.forEach(s -> taken.put(s, SeatState.SOLD));
        }
    }

    static final class PaymentGateway {
        boolean charge(String card, int amount) {
            return !card.endsWith("0000");            // demo rule: this test card is declined
        }
    }

    static final class BookingStore {
        private final List<Booking> saved = new ArrayList<>();

        Booking save(int bus, List<Integer> seats, int price) {
            Booking b = new Booking("B-" + (301 + saved.size()), bus, List.copyOf(seats), price);
            saved.add(b);
            return b;
        }
    }

    /** Asynchronous: the caller does not wait for the e-ticket to be sent. */
    static final class TicketNotifier {
        private final ExecutorService worker = Executors.newSingleThreadExecutor();

        void sendLater(Booking b) {
            worker.submit(() -> System.out.println("  [async] e-ticket sent for " + b.id()));
        }

        void shutdown() throws InterruptedException {
            worker.shutdown();
            worker.awaitTermination(5, TimeUnit.SECONDS);
        }
    }

    static final class BookingService {
        private static final int SEAT_PRICE = 900;
        private final SeatInventory seats;
        private final PaymentGateway pay;
        private final BookingStore store;
        private final TicketNotifier notifier;

        BookingService(SeatInventory seats, PaymentGateway pay, BookingStore store, TicketNotifier notifier) {
            this.seats = seats;
            this.pay = pay;
            this.store = store;
            this.notifier = notifier;
        }

        Result book(int bus, List<Integer> wanted, String card) {
            arrow("BookingService", "SeatInventory", "holdAll(" + wanted + ")");
            if (!seats.holdAll(wanted)) {
                return Result.failed("seat taken");           // break: stop here
            }
            int price = SEAT_PRICE * wanted.size();
            arrow("BookingService", "PaymentGateway", "charge(" + price + ")");
            if (!pay.charge(card, price)) {                   // alt [declined]
                arrow("BookingService", "SeatInventory", "releaseAll(" + wanted + ")");
                seats.releaseAll(wanted);
                return Result.failed("payment declined");
            }
            arrow("BookingService", "SeatInventory", "confirmAll(" + wanted + ")");   // alt [payment ok]
            seats.confirmAll(wanted);
            arrow("BookingService", "BookingStore", "save()");
            Booking b = store.save(bus, wanted, price);
            arrow("BookingService", "TicketNotifier", "sendLater(" + b.id() + ")  [async]");
            notifier.sendLater(b);
            return Result.success(b);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        TicketNotifier notifier = new TicketNotifier();
        BookingService service = new BookingService(
                new SeatInventory(), new PaymentGateway(), new BookingStore(), notifier);

        System.out.println("Scenario 1: happy path");
        arrow("Passenger", "BookingService", "book(bus 7, [14, 15])");
        System.out.println("  reply: " + service.book(7, List.of(14, 15), "4111-1111"));

        System.out.println("Scenario 2: payment declined");
        arrow("Passenger", "BookingService", "book(bus 7, [16])");
        System.out.println("  reply: " + service.book(7, List.of(16), "4000-0000"));

        System.out.println("Scenario 3: seat already sold");
        arrow("Passenger", "BookingService", "book(bus 7, [16, 15])");
        System.out.println("  reply: " + service.book(7, List.of(16, 15), "4111-2222"));

        notifier.shutdown();
    }
}

Notes

The problem

Here is why order matters. Our classes are fine: a booking service, a seat inventory and a payment gateway. But the first version charges the card, and only then tries to hold the seat. Two passengers click on seat fourteen at the same moment, both are charged, and only one gets the seat. The other needs a refund and is angry. The class diagram looked perfect. The bug was in the sequence.

The idea

A sequence diagram shows one scenario over time. The objects that take part are lined up across the top, usually from the user on the left toward storage and outside systems on the right. Time flows down the page. Each arrow is a message, normally a method call, from one object to another. Read it from top to bottom like a story. One diagram describes one scenario, like booking two seats where payment works.

Reading the diagram
  • objects across the top,
  • left to right
  • time flows top to bottom
  • arrows are messages
  • (method calls) between them
  • one diagram = one scenario
  • e.g. "book two seats,
  • payment succeeds"

Lifelines

Each participant gets a lifeline: a box with its name at the top and a dashed line dropping down the page. The user is often drawn as a stick figure, called an actor. When an object is busy running a method, a thin rectangle called an activation bar sits on its lifeline. The bar starts when a call arrives and ends when the method returns, so you can see at a glance who is waiting for whom.

Lifelines and activation
Passenger  BookingService  SeatInventory
   |             |               |
   |---book()--->#               |
   |             #---hold()----->#
   |             #<--- ok -------#
   |             #               |

# activation bar: the object
  is busy running a method

Kinds of message

There are a few kinds of arrow. A synchronous call is a solid line with a filled arrowhead: the caller waits for the answer, like a normal Java method call. An asynchronous message is a solid line with an open arrowhead: the caller sends it and carries on, like putting a job on a queue. A return is a dashed line going back. A call to your own method loops back to your own lifeline, and creating a new object points at its box.

Messages
  • synchronous call:
  • solid line, filled head
  • the caller waits
  • asynchronous message:
  • solid line, open head
  • the caller moves on
  • return: dashed line back
  • self call: arrow loops back
  • to the same lifeline
  • create: dashed, to a new box

The happy path

Here is the fixed flow, the happy path. The passenger asks the booking service to book seats fourteen and fifteen on bus seven. The service first asks the seat inventory to hold both seats. Only then does it charge eighteen hundred rupees. When the charge succeeds, it confirms the seats, saves the booking, and sends the e-ticket as an asynchronous message, without waiting. The diagram makes the safe order impossible to miss.

The loop frame

Repeated steps go inside a frame, a rectangle with a small label in the corner. A loop frame repeats its messages, and the condition is written in square brackets, called a guard, like for each seat. Inside, the service tries to hold one seat at a time, and the inventory answers true or false. In Java, that is just a for loop. If any seat fails, the service releases the ones it already held.

loop frame
BookingService        SeatInventory
  |  +-loop [for each seat]------+
  |  |  |---tryHold(seat)--->|  |
  |  |  |<-- true / false ---|  |
  |  +--------------------------+

Java: for (int s : seats)
        held &= tryHold(s);

The alt frame

Failures go in an alt frame, short for alternatives. It is split by a dashed line into branches, and each branch has a guard. In the payment ok branch, we confirm, save and notify. In the declined branch, we release both seats so other passengers can buy them, and return a failure. In Java an alt frame is an if and else. Drawing it forces you to decide what happens on failure, which is what interviewers want to hear.

alt frame
  • +-alt [payment ok]--------+
  • | confirm seats |
  • | save booking |
  • | send e-ticket |
  • |- - [declined] - - - - - -|
  • | release seats |
  • | return failure |
  • +-------------------------+

Other frames

A few more frame labels are worth knowing. Opt is an optional block, an if with no else, such as apply a coupon only if the passenger has one. Par shows branches that run in parallel. Break stops the rest of the flow, for example when a seat is not available. And ref points to another diagram, so you can keep each one small instead of drawing the whole system on one page.

More frame labels
  • opt [has coupon]
  • steps that may be skipped
  • par
  • branches that run at the
  • same time
  • break
  • stop the flow here
  • ref
  • points to another diagram
  • (keeps each one small)

Sync vs async

Notice the two different arrowheads at the end. Saving the booking is synchronous. The service waits for the store to confirm, because without a saved record we cannot promise the passenger anything. Sending the e-ticket is asynchronous. The service hands it off and replies to the passenger at once. If the message is slow, the booking is still done. The diagram makes this design choice visible with one small arrowhead.

Diagram to code

Here is the booking method, and you can lay it beside the diagram. Hold all seats, or fail with taken. Charge the card. If it is declined, release the seats and fail. That is the alt frame. Otherwise confirm the seats, save the booking, and queue the e-ticket. Each arrow leaving the booking service lifeline is one line in this method, in the same order. A good sequence diagram is almost pseudo code.

BookingService.book()
if (!seats.holdAll(wanted))
    return Result.failed("taken");
if (!pay.charge(card, price)) {
    seats.releaseAll(wanted);
    return Result.failed("declined");
}
seats.confirmAll(wanted);
Booking b = store.save(...);
notifier.sendLater(b);
return Result.success(b);

Drawing it fast

In an interview, draw one flow, usually the most important use case. Put the actor on the left, then the main service, then its helpers. Draw only the calls that matter, and skip getters and obvious returns. Add one alt frame for the main failure, like payment declined, and mark asynchronous messages clearly. Talk while you draw. Five lifelines and ten arrows explain more than a page of text.

Interview recipe
  • 1 choose ONE flow: the most
  • important use case
  • 2 lifelines: actor, service,
  • then helpers left to right
  • 3 arrows for real calls only
  • 4 one alt for the main
  • failure
  • 5 mark async with "async"
  • skip getters and returns
  • that add nothing

Which diagram when

Which diagram should you draw? A class diagram shows structure: what exists and how it is connected. It does not change over time. A sequence diagram shows behaviour: one scenario in time order. Activity diagrams show the steps of a process, and state diagrams show the states of one object, like a booking going from held to paid to cancelled. In most design rounds, one class diagram plus one sequence diagram is the right amount.

Pick the right picture
  • class diagram:
  • what exists and how it
  • is connected (static)
  • sequence diagram:
  • one scenario, in time
  • order (dynamic)
  • activity / state diagram:
  • steps of a process, or
  • states of one object

Interview questions

What is a sequence diagram used for?

It shows how objects interact in one scenario over time: which object calls which, in what order, and what comes back. It is the main way to explain a flow such as booking, checkout or login, and to spot ordering bugs early.

What is a lifeline and an activation bar?

A lifeline is the dashed vertical line under each participant, representing that object over time. An activation bar is a thin rectangle on the lifeline showing the period when the object is executing a method.

How do you show synchronous versus asynchronous messages?

A synchronous call is a solid line with a filled arrowhead, and the caller waits for a reply. An asynchronous message is a solid line with an open arrowhead, and the caller continues without waiting. Replies are dashed lines.

What do the alt, opt and loop frames mean?

alt shows alternative branches, each with a guard condition, like an if and else. opt is a single optional block, like an if with no else. loop repeats the messages inside it while its guard holds, like a for or while loop.

What is the difference between a class diagram and a sequence diagram?

A class diagram is static: it shows classes, their fields and methods, and how they relate. A sequence diagram is dynamic: it shows one scenario as messages between objects in time order. Designs usually need one of each.

Why hold a seat before charging in a booking flow?

If you charge first, two users can pay for the same seat and one must be refunded. Holding first reserves the seat atomically, so only one user reaches payment; if payment fails, the hold is released for others.

How many lifelines should a sequence diagram have in an interview?

Usually four to seven: the actor, the main service and the helpers that matter for that flow. More than that suggests the scenario is too big and should be split, or that some details belong in another diagram referenced with a ref frame.