Sequence Diagrams — How Objects Interact Over Time
Introduction
Class Diagrams — Structure of Your System showed what the library's classes are and how they are linked, and Use Case Diagrams — Who Does What showed what the system does for its users. Neither says what happens while it runs. When a member borrows a book, which object calls which method, in what order, and what comes back?
A sequence diagram answers that for one scenario at a time. Each object taking part gets a vertical line, and the calls between them are arrows across, read from the top down. Think of the class diagram as the cast list of a play, and of a sequence diagram as one scene of its script: who speaks to whom, in what order, and what happens as a result.
This page draws one scene of the library: a member borrowing a book, with every message a call in the library's own code.
Anatomy of a Sequence Diagram
A sequence diagram is made of five kinds of element.
Lifelines. Each object in the scenario has a box with its name and class, such as library:Library, and a vertical line under it: "A Lifeline is shown using a symbol that consists of a rectangle forming its “head” followed by a vertical line (which may be dashed) that represents the lifetime of the participant." Time runs down the page, so a message lower down happens later.
Messages. A message is an arrow from the object that sends it to the one that receives it, usually a method call. The arrowhead says what kind it is. A call that waits for its answer has a filled head: "A synchronous Message (messageSort equals synchCall) has a filled arrow head." A message sent without waiting has an open one: "An asynchronous Message (messageSort equals asynchCall or asynchSignal) has an open arrow head." The answer that comes back is dashed: "A reply Message (messageSort equals reply) has a dashed line with either an open or filled arrow head." An object can also send a message to itself, drawn as an arrow that loops back to its own line.
Activation bars. While an object is running a method, a thin bar covers its lifeline, from the call it receives to the answer it sends: "ExecutionSpecifications are represented as thin rectangles (gray or white) on the lifeline".
Combined fragments. A box round some messages says they run under a rule. UML describes the box: "The notation for a CombinedFragment in a Sequence Diagram is a solid-outline rectangle. The operator is shown in a pentagon in the upper left corner of the rectangle." Three operators cover most diagrams:
altis a choice: "The interactionOperator alt designates that the CombinedFragment represents a choice of behavior. At most one of the operands will be chosen." Its parts, the operands, are stacked in one box, and "InteractionOperands are separated by a dashed horizontal line." Each operand has a guard in square brackets, such as[available], and the last one can be[else].optis an if with no else: "The interactionOperator opt designates that the CombinedFragment represents a choice of behavior where either the (sole) operand happens or nothing happens."looprepeats: "The interactionOperator loop designates that the CombinedFragment represents a loop. The loop operand will be repeated a number of times."
Creation and destruction. A message that makes a new object is dashed with an open head, "An object creation Message (messageSort equals createMessage) has a dashed line with an open arrow head.", and it points at the new object's box, which stands at that height and not at the top, since the object did not exist before. An object that is destroyed ends in a cross: "The DestructionOccurrenceSpecification is depicted by a cross in the form of an X at the bottom of a Lifeline."
Notation Guide
The card puts each element on one sheet:
![A reference card for UML sequence diagram notation, in five panels. 1, Lifeline: a box named :ObjectName with a dashed line under it, and an arrow marked time pointing down; a box names the participant, the dashed line under it is its lifeline, and time runs down. 2, Messages, between :A and :B: methodCall() as a solid line with a filled head, returnValue as a dashed line back, notify() as a solid line with an open head, and selfMethod() looping back to :A; a filled head is a call that waits, a dashed line its answer, an open head a message that does not wait. 3, Activation bar: :Caller sends request() to :Object, whose thin bar, marked executing, runs from the call to its response. 4, Combined fragments: alt with [condition true] and [else] split by a dashed line, opt with [condition], loop with [while condition]; with alt one operand runs, with opt it runs or nothing does, and loop repeats while its guard holds. 5, Creation and destruction: :Caller sends a dashed «create» arrow with an open head to :Product, whose box stands where it is made, and an X at the foot of its lifeline, marked destroyed, ends it.](https://pub-a1b3030acfb94e84ba8a89fb182c53bc.r2.dev/public/lld-content-b09110b6-165f-45e4-8d80-a173b028b0e6/sequence_diagram_notation_reference_v1.webp)
Play a Borrow
Play the borrowing scene below. Alice borrows Clean Code while it is on the shelf, then Bob tries to borrow it while Alice has it. Watch the messages go out one at a time, top to bottom, and which part of the alt runs each time.

Complete Example: Borrowing a Book
Here is the whole scene, drawn from the library listing's own Member.borrow and Library.lend:

Read it from the top:
borrow(isbn, 2)comes intoalice:Memberfrom outside the frame. The frame, labelledsd borrow, holds the whole scene, and a message from its edge comes from whoever calledborrow.- Alice's
borrowcallslend(isbn, 2)on the library and waits for the answer. - Inside a
loop, the library asks its books for their ISBN until one matches. Here the first book, Clean Code, matches. - The library asks the book
isAvailable(), and the answer comes back dashed. - The answer chooses the operand of the
alt. Under[available], the library callsmarkAsBorrowed()on the book and makes a newLoan, a dashed creation arrow to the Loan's box, which stands at that height. The loan goes back to Alice, and from Alice back out of the frame. - Under
[else], the book is out,lendthrows an exception that says the book is BORROWED, and it comes back to Alice in place of a loan.
Only one operand runs in each borrow, as UML says of alt, and both are drawn so that the diagram covers both outcomes. isAvailable() stands above the alt because its answer is what chooses the operand.
The library listing does not check the member, so the diagram has no message for it. The use case diagram in Use Case Diagrams — Who Does What has Borrow Book include Verify Membership; a library whose code checked the member would add that call here, between lend and the search.
How to Read a Sequence Diagram
- Start at the top left, with the object or the frame's edge where the first message comes in.
- Read down. Each message happens after the ones above it.
- Look at each arrow's line and head. A solid line with a filled head is a call that waits; a dashed line is its answer, and it can point either way on the page, back to the caller.
- Follow the activation bars to see which object is working at each moment.
- Read each fragment's operator and guard to see what is a choice (
alt,opt) and what repeats (loop).
Translating a Sequence Diagram to Code
Every message in the diagram is a call in the code. Here are the two methods the scene runs, cut from the library listing in all six languages:
# in class Member
def borrow(self, isbn: str, day: int) -> Loan:
loan = self._library.lend(isbn, day)
self._loans.append(loan)
return loan
# in class Library
# «Create»: the library makes a Loan and hands it over without keeping it
def lend(self, isbn: str, day: int) -> Loan:
for book in self._books:
if book.get_isbn() == isbn:
if not book.is_available():
raise RuntimeError(
f"{book.get_title()} is {book.get_status().value}")
book.mark_as_borrowed()
return Loan(book, day)
raise ValueError(f"No book with ISBN {isbn}")// in class Member
public Loan borrow(String isbn, int day) {
Loan loan = library.lend(isbn, day);
loans.add(loan);
return loan;
}
// in class Library
// «Create»: the library makes a Loan and hands it over without keeping it
public Loan lend(String isbn, int day) {
for (Book book : books) {
if (book.getIsbn().equals(isbn)) {
if (!book.isAvailable()) {
throw new IllegalStateException(
book.getTitle() + " is " + book.getStatus());
}
book.markAsBorrowed();
return new Loan(book, day);
}
}
throw new IllegalArgumentException("No book with ISBN " + isbn);
}// in class Member
Loan& borrow(const std::string& isbn, int day) {
loans_.push_back(library_->lend(isbn, day));
return *loans_.back();
}
// in class Library
// «Create»: the library makes a Loan and hands it over without keeping it
std::unique_ptr<Loan> lend(const std::string& isbn, int day) {
for (Book* book : books_) {
if (book->getIsbn() == isbn) {
if (!book->isAvailable()) {
throw std::runtime_error(book->getTitle() + " is "
+ toString(book->getStatus()));
}
book->markAsBorrowed();
return std::make_unique<Loan>(*book, day);
}
}
throw std::invalid_argument("No book with ISBN " + isbn);
}// in class Member
borrow(isbn: string, day: number): Loan {
const loan = this.library.lend(isbn, day);
this.loans.push(loan);
return loan;
}
// in class Library
// «Create»: the library makes a Loan and hands it over without keeping it
lend(isbn: string, day: number): Loan {
for (const book of this.books) {
if (book.getIsbn() === isbn) {
if (!book.isAvailable()) {
throw new Error(`${book.getTitle()} is ${book.getStatus()}`);
}
book.markAsBorrowed();
return new Loan(book, day);
}
}
throw new Error(`No book with ISBN ${isbn}`);
}// in class Member
public Loan Borrow(string isbn, int day)
{
Loan loan = library.Lend(isbn, day);
loans.Add(loan);
return loan;
}
// in class Library
// «Create»: the library makes a Loan and hands it over without keeping it
public Loan Lend(string isbn, int day)
{
foreach (Book book in books)
{
if (book.Isbn == isbn)
{
if (!book.IsAvailable())
{
throw new InvalidOperationException(
$"{book.Title} is {book.Status}");
}
book.MarkAsBorrowed();
return new Loan(book, day);
}
}
throw new ArgumentException($"No book with ISBN {isbn}");
}// a method of Member
func (m *Member) Borrow(isbn string, day int) (*Loan, error) {
loan, err := m.library.Lend(isbn, day)
if err != nil {
return nil, err
}
m.loans = append(m.loans, loan)
return loan, nil
}
// a method of Library
// «Create»: the library makes a Loan and hands it over without keeping it.
// Go returns an error as a second value where Java throws.
func (lib *Library) Lend(isbn string, day int) (*Loan, error) {
for _, book := range lib.books {
if book.ISBN() == isbn {
if !book.IsAvailable() {
return nil, fmt.Errorf("%s is %s", book.Title(), book.Status())
}
book.MarkAsBorrowed()
return NewLoan(book, day), nil
}
}
return nil, fmt.Errorf("no book with ISBN %s", isbn)
}The for loop over the books is the loop fragment. The if on isAvailable() is the alt: its true branch marks the book and makes the Loan, the creation message, and its false branch throws, the [else] operand. Each return is an answer going back. Go has no exceptions, so its Lend returns the error as a second value, and its Borrow passes it on.
Common Mistakes in Sequence Diagrams
Mistake 1: too many lifelines. A diagram with ten objects across the page is hard to read, and its arrows cross each other. Keep one diagram to one scenario and the objects it needs; if a use case has a long error path, give it a diagram of its own.
Mistake 2: calls with no answers. A diagram with only calls hides what each method gives back. Draw the answer of every call whose result matters to the next step, such as available and loan. A call that returns nothing, like markAsBorrowed(), needs no line back.
Mistake 3: every small step. Five self-calls for parsing, trimming and caching inside one object bury the design. Show the calls between objects and the steps that matter to the scenario, and leave the rest to the code.
Mistake 4: two diagrams where one alt will do. Drawing "book available" and "book not available" as two separate diagrams repeats every message they share. One alt with an [else] operand shows the decision and both outcomes in one place.
Mistake 5: an answer from the wrong side. An answer goes from the object that did the work back to the one that called it: from library:Library back to alice:Member, never the other way.
When to Draw One
Draw a sequence diagram when you need to show how several objects work together for one scenario, when the order of the calls matters, or when you want to test a class design. If an object in the diagram receives a message it has no method for, the class design is missing something.
Other questions need other diagrams. What the system offers its users is a use case diagram, and what classes exist is a class diagram. A flow of one object calling one method on another is easier to say in a sentence than to draw.
Activity Diagrams — Workflow and Decision Points takes a workflow with its decisions and draws it as steps rather than messages between objects.
Key Takeaways
- A sequence diagram shows one scenario: a lifeline for each object, and messages across, read from the top down.
- A call has a solid line and a filled head, an answer a dashed line, and a creation message a dashed line to the new object's box at the height where it is made.
- Activation bars show who is working;
alt,optandloopframes show choices and repeats, the operands of analtsplit by a dashed line. - Every message is a call in the code, so a sequence diagram tests a class design: each message needs a method to receive it.