LESSON 3.3
Sequence diagrams
A sequence diagram shows which objects talk, in which order, and what each call returns. It turns vague flow descriptions into testable contracts.
6 min read
A sequence diagram adds time to a class diagram. It shows which objects participate in a use case, in what order they communicate, and what each call returns. It is the cheapest way to find circular dependencies before writing any code.
Reading a sequence diagram
Each vertical line is an object (called a lifeline). Each horizontal arrow is a method call. The arrow label is the method name and arguments. The return arrow (often dashed) carries the return value.
Reading downward gives the time order. A method body spans the rectangle (activation) on its lifeline. Arrows that go both ways (call then return) describe synchronous calls. In an async system, the return never arrives — or arrives on a different lifeline.
The booking use case
Requirement: A customer books a ticket. The system checks availability, charges the card, then confirms the booking.
Lifelines: Customer, BookingService, SeatInventory, PaymentGateway.
Customer → BookingService.book(seatId, card)BookingService → SeatInventory.reserve(seatId)→ returnstrueBookingService → PaymentGateway.charge(card, amount)→ returnsreceiptBookingServicecreates aBooking(seatId, receipt)and returns it toCustomer
This reveals three things:
BookingServicedepends on bothSeatInventoryandPaymentGateway.- If
reservereturnsfalse,chargemust not be called —BookingServicemust branch. PaymentGateway.chargeneeds anamount. Where does the amount come from? The diagram forces you to answer.
In code
What a sequence diagram reveals
After drawing the diagram, ask:
- Circular dependency? If
AcallsBwhich callsA, you have a cycle. Break it with an event or an intermediate object. - Missing data? If a call needs data that no previous step produced, the diagram is incomplete.
- Branching? If a call can fail, the diagram needs an alternate path. Missing alternate paths become missing error-handling code.
Where you have already seen it
Postman visualizations of API chains are informal sequence diagrams. OpenAPI links capture the same idea for REST APIs. Java's CompletableFuture.thenCompose chains are a sequence diagram expressed in code. Actor frameworks (Akka, Erlang) use explicit lifelines and message passing as their core abstraction.
Try it
Ticket Booking LLD
Draw the sequence for booking, cancellation and refund before implementing any of the three.