LLD · 04 System Design: LLD

Sequence Diagrams: How Objects Talk

Sequence Diagrams: How Objects Talk

Ana checks out: three mugs and a lamp, $86, all six tests pass. Then Ben checks out, the payment gateway doesn't answer in time, checkout crashes, and his lamp stays reserved for an order that doesn't exist. Before we fix it, we draw it. This episode teaches you to read and draw sequence diagrams: lifelines, synchronous calls and their replies, creating an object, asynchronous messages through a queue, activation bars, and the boxes that carry the ifs and loops: opt, alt and loop. Then we record real runs with Python's profile hook, turn them into diagrams, and compare them with ours, arrow by arrow: what a trace knows, and what it can't.

Chapters

Cheat sheet

Diagrams

Code

A small shop's checkout in three versions (Python 3.14, pytest, standard library only): version 1, the happy path (6 passed); version 2, after "payment can fail: add the retry path", with a retry loop and a failure branch that gives the stock back (10 passed: version 1's six tests unchanged, plus four new ones, which all fail on version 1); and a "one object does everyone's work" version that passes the same six tests. Plus a small tracer built on sys.setprofile that writes real runs as Mermaid sequence diagrams, and every diagram as a Mermaid file next to the code.

Sources

Transcript

Here's checkout in a small online shop, and a picture of how it runs. Ana orders three mugs and a lamp. Checkout asks the stock to reserve them, creates the order, asks it for its total, eighty-six dollars, and charges her card. Then it drops a receipt in an outbox for the mailer, and hands Ana her order. All six tests pass.

Then Ben checks out, and the payment gateway doesn't answer in time. Checkout crashes with a timeout, and Ben's lamp stays reserved: three lamps left on the shelf, for an order that doesn't exist. So a change request arrives: payment can fail. Add the retry path.

This is Just Known. From unknown, to known. Episode four of our low-level design series: sequence diagrams, how objects talk. This whole episode, in one sentence: a class diagram shows who knows whom, and a sequence diagram shows who calls whom, in what order. Same code, two views.

Last episode's kind of diagram shows that checkout keeps a stock and a gateway. A sequence diagram shows one conversation: who asks, who answers, and what happens next. The idea is older than U M L. The I T U, the telecom standards body, standardized message sequence charts in 1993, as recommendation Z one twenty. An early U M L specification says much of its sequence notation came from those charts, through an object-oriented version.

By 1996, the charts had boxes for choices, options and loops, and U M L two added the same kind of boxes. Start with the cast. Each box across the top is a lifeline: one participant in the conversation. Colon checkout means an object of the checkout class, with no name of its own. A stick figure is an actor, someone outside the system: here, Ana.

The dashed line under each box is that participant's life, and time runs down the page. So you read it top to bottom: each arrow is one message, in the order it happens. Left to right means nothing; it's just tidier to put the caller first, so most arrows point right. The first kind of arrow is a synchronous call: a solid line with a filled head. It's a method call, and the caller waits.

This one is a single line in the place order method: self dot stock dot reserve. Checkout stops right there until the stock is done. When it's done, a reply comes back: a dashed line, labeled with what came back. Reserve returns nothing, so its reply says None. Total's reply is eighty-six hundred: the order's total, in cents.

Every reply is a method returning. Creating an object is a dashed arrow with an open head, pointing at a new lifeline. The order's box starts right there, partway down, because before that line runs, the order doesn't exist. The last kind is a solid line with an open head: an asynchronous message. The sender doesn't wait.

Checkout puts the receipt on a queue and moves on, and the mailer sends it later, from its own worker thread. The run shows it: when checkout returns, one receipt is waiting, and none is sent. Then the worker sends it. That's the real difference: a call gets an answer back, and an asynchronous message doesn't. The thin bars are activations; U M L calls them execution specifications.

A bar shows when a participant is busy. Checkout's bar runs from Ana's call until it hands back the order. The stock's bar is short, and the whole time, checkout's bar keeps going, waiting for the reply. When an object calls one of its own methods, the arrow loops back to its own lifeline, and a second bar stacks on the first. You'll see one in a minute.

One more thing on this diagram: the box around the receipt. A box with a tag in its corner is a combined fragment, and the tag says how to read what's inside. Opt means optional: what's inside happens only when its guard, in square brackets, is true. Here the guard is cart dot send receipt, the very condition in the if statement. So an opt box is an if with no else.

Now the change request. The gateway can time out, which is temporary, so we try again, up to three times. Or the bank can decline, which is final. Either way, the stock goes back on the shelf. This time, we draw it before we write it.

Checkout calls a new method of its own, pay, and a second bar stacks on the first. Inside it, a loop box. Loop one comma three means at least once, and at most three times, and the guard, timed out, says when to go round again. Then an alt box, for alternatives. Each part has its own guard, and at most one part runs.

If there's a receipt, the order goes back, with the opt box from before now inside. Else, checkout releases the stock and returns None. Boxes nest, just like ifs. And there are a few more tags, like par, for things that happen in parallel, and break, for an early exit. Now the diagram tells us what to write.

A new arrow into the stock means a method it must have: release, taking the lines. The arrow that loops back means checkout gets a method of its own, pay, and its reply says what pay returns: a receipt, or None. The loop box becomes a for loop over three tries, where a timeout goes round again, and a decline returns None. And the alt and opt boxes become the ifs in the place order method: each guard is its condition, word for word. In the app's code, only checkout and the stock changed.

Everything else is identical, including version one's six tests. Four new tests guard the failure path: a timeout is tried again, three timeouts give the stock back, a decline gives it back too, and a decline is never retried. All ten pass. Run the four new tests against version one, and all four fail: it crashes on the first timeout, and on the first decline. Can Python draw this for us?

It can record a real run. Python's set-profile hook calls a function of ours on every call and every return. Ours keeps the calls between our own objects, gives each object a lifeline, and writes the run as Mermaid text. For Ana's checkout, Python reported forty-nine events: our methods, built-ins like sum and len, even the queue's own locks. The tracer kept nine messages.

Drawn out, they match our diagram arrow for arrow: every call, the create, and every reply. Except at the top: the trace doesn't know Ana. Its caller is just the main thread. But the receipt to the mailer is missing. The profile hook works per thread, and the mailer runs on another one.

Hook new threads too, with threading's set-profile, and the mailer shows up, called by the worker thread. Still, no arrow joins checkout to the mailer: the queue sits between them, and the trace can't see that one caused the other. Now trace version two. Ben's run has no loop box, just two charges in a row. Chen's has no alt box, only the branch that ran.

And Ben's first charge didn't return None, whatever the trace says. It timed out. The profile hook reports an exception and a None the same way; Python's newer monitoring hook can tell them apart. A trace is one run: one path, no guards, no intent. U M L says it too: one combined fragment describes many traces at once.

So use traces to check your diagrams, and diagrams to say what should happen. Traces are also good at spotting a bad design. Here's another checkout that passes the same six tests. But it does everyone's work: it asks the stock for each level, checks it, and sets the new number itself, and it adds up the order's total itself. Trace the same order, and count.

In version one, checkout sends four messages. Here it sends eight, six of them to the stock, getting and setting numbers. And the order is created, and never asked a thing. When one lifeline sends nearly every arrow, and the others just hold data, the logic is in the wrong place. The stock's rule now lives in checkout, so anything else that takes stock has to copy it.

We'll give each class one job in episode five. So when is a sequence diagram worth drawing? For one tricky flow: a payment, a retry, anything with failures or more than one thread. In a design review, and in an interview. Keep each diagram to one scenario, with only the messages that matter, not every getter.

Skip it for simple code, where the method is easier to read than the picture. And keep it as text next to the code, like this episode's Mermaid files, so it changes when the code does. You've probably met these already. The TLS one point three standard draws its handshake as one: client on the left, server on the right, and the handshake's messages flowing down the page. Our networks series drew its handshakes the same way.

And GitHub renders Mermaid sequence diagrams right inside Markdown files, issues and pull requests, so a diagram can live right next to the code it describes. Interview corner. What's the difference between a synchronous and an asynchronous message? And how would you show a retry on a sequence diagram? Pause here, and try answering in thirty seconds.

Here's a strong answer. A synchronous call is a solid arrow with a filled head: the caller waits, and a dashed reply comes back. An asynchronous message has an open head: the sender moves on, and the receiver handles it later, often from a queue, on another thread. For a retry, put the call in a loop box, with its bounds and a guard: loop one comma three, while it times out. Then an alt box for the outcome: paid, or else, give the stock back.

To stand out, say how you'd test it: script the gateway's answers, a timeout and then a success, and check it tried the charge twice. Let's recap. A sequence diagram shows who calls whom, and in what order: lifelines across the top, time down the page, and an arrow for every message. The boxes carry the ifs and loops that no single run can show. A trace tells you what happened.

The diagram says what should. Next, we'll give each class one job, so a new feature touches one place, not ten. That's episode five: SOLID, part one, single responsibility and open closed. This is Just Known. From unknown, to known.

Note: Ana, Ben, Chen, the mugs, the lamp and the shop are made-up examples, and the payment gateway is a fake that answers from a script; every line of code, test, trace and output on screen is from a real run (Python 3.14.3, pytest 9.2.0). Pictures marked "illustration" are not real output.
Narration voice generated with Google Gemini text-to-speech.