The Sequence Diagram
Chapter Twenty-Two
Syllabus topic Module 1, "System Modeling using UML: ... Sequence Diagram".
Pages 132 to 137 of 499
In one line
A sequence diagram shows one scenario as a conversation over time: the participants across the top, time running down the page, each message an arrow from the one who sends it to the one who receives it, and frames around the parts that are chosen, optional, repeated or cut short.
In the wording to use when asked: a sequence diagram is a UML interaction diagram that shows the messages exchanged between lifelines, arranged in time order from top to bottom; combined fragments such as alt, opt, loop and break express alternatives, options, iteration and exceptional exits, each with a guard in square brackets.
The parts
| Part | What it means | How UML draws it |
|---|---|---|
| Lifeline | one participant in the scenario: an actor, an object, a component, a database | a rectangle with its name, and a dashed line running down the page |
| Synchronous message | a call whose sender waits for the answer | a solid line with a filled arrowhead |
| Asynchronous message | a message whose sender does not wait | a solid line with an open arrowhead |
| Reply | the answer to a call | a dashed line with an arrowhead |
| Creation message | a message that creates a participant | a dashed line with an open arrowhead, ending at the new participant's head |
| Self-message | a participant doing something itself | an arrow that leaves a lifeline and comes back to it |
| Activation | the time a participant spends doing something | a thin rectangle on its lifeline |
| Combined fragment | a part of the scenario with a rule attached | a rectangle, its operator in a small pentagon at the top left, its parts divided by dashed lines, each part's guard in square brackets |
Time runs down the page. The specification requires every message line to run horizontally or downwards from sender to receiver. A message never points up, because it cannot arrive before it was sent.
Name a message after what the receiver can do: an operation of its class, a route of the API, an SQL statement. That is Chapter 19's fourth check, and it is what makes the diagram testable against the code.
The fragments
alt, alternatives. Several parts, each with a guard; at most one runs, the one whose guard is true. A guard of [else] means "none of the others". An if-else.
opt, an option. One part, which either runs or does not, depending on its guard. An if with no else.
loop, repetition. One part, repeated. Its guard can give the least and the most number of times, written loop(1, 10), and a condition to stop.
break, an early exit. When its guard is true, its part runs instead of the rest of the fragment that encloses it, and that rest is skipped. It is how a refusal is drawn: the order is refused, and nothing after it happens. Put the break at the level whose remainder must be skipped; for a refusal of the whole request, that is the level of the whole diagram.
The Sequence Diagram
There are others. par shows parts that run at the same time, in any interleaving. critical marks a region that must not be interleaved with anything else. A frame labelled ref stands for a whole other sequence diagram, drawn elsewhere, which keeps a large scenario readable.
Drawing one: a scenario at a time
A sequence diagram shows one scenario. Not the system; not even a whole use case with every branch. Choose the scenario first:
- Pick a use case, and write its main success scenario and its important extensions (Chapter 12).
- Choose the level. Between the user, the page and the server, the participants are what the user sees. Inside the server, they are the parts of the code. Mixing the two in one diagram gives a diagram too wide to read.
- Put the participants left to right, in the order in which they first act.
- Write the messages top to bottom, each named after what its receiver can do.
- Add a frame for each extension: break for a refusal, alt for a real choice, opt for something that may or may not happen, loop for repetition.
- Check every message against the class diagram and the API.
The worked diagrams
The worked team drew UC-4, Place an order, at both levels.
The page and the server
Figure 22.1 UC-4 Place an order, between the student, the page and the server
@startuml sequence-request
!pragma layout smetana
autonumber
hide footbox
actor Student
participant "Menu page" as Page
participant "API" as Api
Student -> Page : Place order
Page -> Api : POST /api/orders
Api -> Api : check session\nand role
break not a signed-in student
Api --> Page : 401 or 403
Page --> Student : the message
end
Api -> Api : check input
break input wrong
Api --> Page : 400 and\nthe problems
Page --> Student : each problem\nby its field
end
Api -> Api : place order
alt accepted
Api --> Page : 201 and the order
Page --> Student : its number
else refused
Api --> Page : 409 and the reason
Page --> Student : the reason
end
@endumlRead it top to bottom. The student taps Place order (1), and the page sends POST /api/orders (2). The API then does three things in turn, each drawn as a self-message, and each can stop the request:
- Checks the session and the role (3). If the student is not signed in, the answer is 401; if the person signed in is not a student, 403. The first break frame: nothing after it happens.
- Checks the input (6). A slot that does not exist, or an item listed twice, and the answer is 400 with each problem. The page shows a problem beside its field where the form has one, and the rest in the message at the top.
- Places the order (9). Either it is accepted, 201 with the order, and the page shows its number; or it is refused, 409 with the reason, such as "Only 2 left". An alt, because both are ordinary outcomes of placing an order.
The Sequence Diagram
The status codes are the application's own (Chapter 48 explains each). Every message the page sends is a route of the API, and every answer is one the page handles.
Inside the server: the transaction
Message 9, "place order", is where the rules of FR-7 to FR-11 are enforced. The second diagram opens it up:
Figure 22.2 Message 9 opened up: placing an order inside one database transaction
@startuml sequence-transaction
!pragma layout smetana
autonumber
hide footbox
participant "API" as Api
participant "Order\nservice" as Service
database "MySQL" as Db
Api -> Service : place(user, order)
Service -> Service : is the slot\nstill open?
break slot closed
Service --> Api : slot_closed
end
Service -> Db : BEGIN
Service -> Db : lock the\nstudent's row
Service -> Db : count their orders\nfor this slot
Db --> Service : the count
break count is not 0
Service -> Db : ROLLBACK
Service --> Api : slot_taken
end
loop each item in id order,\nuntil one is short
Service -> Db : take stock only\nif enough is left
Db --> Service : 1 row changed, or 0
opt 1 row changed
Service -> Db : read its price
end
end
break an item was short
Service -> Db : read what is left
Service -> Db : ROLLBACK
Service --> Api : sold_out or\nitem_unavailable
end
Service -> Db : INSERT the order\nand its lines
Service -> Db : COMMIT
Service --> Api : the new order
@enduml- Is the slot still open? (2) Each slot closes 15 minutes before its time (FR-8). If it has closed, the service answers
slot_closedat once, before touching the database. - BEGIN (4). Everything that follows, up to COMMIT or ROLLBACK, happens as one transaction: all of it or none of it (Chapter 45).
- Lock the student's row, then count their orders for this slot (5 to 7). FR-10 allows one active order per student per slot. The lock means that if the same student taps Place order twice in the same instant, the second request waits until the first has finished, and its count then sees the first order. If the count is not zero, the second break: roll back and answer
slot_taken. The project's tests send two orders from one student at the same moment and check that exactly one is accepted. - The loop (10 to 12). For each item, in the order of its id, the service takes the stock only if enough is left, in one statement, and the database answers how many rows it changed: 1 if the stock was taken, 0 if not. Only when it was taken does the service read the item's price, in the opt frame. Taking the items in id order is deliberate: two orders that share items always take them in the same order, so they can never wait for each other in a circle.
- An item was short (13 to 15). The third break. The service reads what is left, so that the student can be told "Only 2 left" rather than just "No", rolls back everything taken so far, and answers
sold_out, oritem_unavailableif the owner has switched the item off. - Otherwise (16 to 18), insert the order and its lines, commit, and return the new order.
The Sequence Diagram
This is the diagram that answers the question every examiner asks of an ordering system: what happens when two students order the last biryani at the same moment? Both run message 10 at once. The database lets only one of them change the row while enough is left: that student's update changes 1 row, the other's changes 0, and the second student is told the biryani is sold out. Chapter 45 proves it with a test in which twenty students order the last five plates at the same moment, and exactly five are served.
What the first drawing got wrong
The team's first version drew the shortage as an alt inside the loop: one part for "taken", one for "short", with the rollback in the second. After the alt the diagram carried on to INSERT and COMMIT, so read top to bottom it said that the order was saved even after it had been rolled back. It also had no refusal for a second order in the same slot, although FR-10 forbids one. Both mistakes survived the design review. When the ordering code was built, in the first increment, a reviewer who compared the diagram with it found both, which is exactly what Chapter 19's checks are for, and the corrected diagrams became version 1.1 of the UML set (Chapter 35).
The fix was to draw each refusal as a break at the level of the whole diagram, so that everything after it is visibly skipped, and to make the loop stop at the first short item, as the code does. Every message was then checked against a function in the code: isSlotOpen, lockUser, countActive, takeStock, the menu store's findById, refusal and insert.
The Sequence Diagram
What the diagrams leave out
The replies to BEGIN, the lock, INSERT and COMMIT are not drawn; each diagram draws a reply only where its content matters to the story, such as the count or the rows changed. Activation bars are left out for the same reason. Both are choices of readability, not of UML: if your guide expects every reply and every activation, draw them.
The source, line by line
actor Studentandparticipant "Menu page" as Pagedeclare the lifelines, left to right in the order written;database "MySQL" as Dbdraws the database with a cylinder head.Page -> Api : POST /api/ordersis a synchronous message;Api --> Page : 201 and the orderis a reply, dashed.Api -> Api : check inputis a self-message.break slot closed ... end,alt accepted ... else refused ... end,loop ... endandopt ... enddraw the fragments; the text after the operator becomes the guard.autonumbernumbers the messages, which is what lets the text above say "message 9", andhide footboxstops PlantUML repeating the participants' names at the bottom.
Mistakes examiners circle
One diagram for the whole system. A sequence diagram is one scenario; draw several.
An alt where a break is meant. If the scenario carries on after a failure, the diagram says the failure did not matter.
Arrows that point up, or messages drawn out of order.
Messages nobody can receive: "save order" sent to a class with no such operation, or to the database as if it had methods.
Two levels in one diagram: a tap on a phone and an SQL statement among eight participants.
Guards missing from the fragments, so the reader cannot tell which part runs when.
Do this for your project
- Draw a sequence diagram for each use case whose steps matter: at least the one your project exists for.
- Draw it at the level of the user and the server first; open up the server in a second diagram where the rules live.
- Name every message after a route, an operation or a statement your system really has.
- Draw every refusal the code makes, each as a break, so that nothing after it appears to happen.
- Compare the diagram with the code line by line once the code exists, and fix whichever is wrong.
Quick revision
- Lifelines across the top; time runs down; messages are horizontal or downward.
- Synchronous: filled arrowhead. Asynchronous: open arrowhead. Reply: dashed line. Creation: dashed, to the new lifeline's head.
- Activation: a thin rectangle on the lifeline.
- alt (choose one), opt (run or not), loop (repeat;
loop(min, max)), break (run instead of the rest); guards in [square brackets],[else]for none of the others. - Also par (in parallel), critical (not interleaved), ref (another diagram).
- One scenario per diagram, at one level.
The Sequence Diagram
Questions you must be able to answer
1. What does a sequence diagram show? The messages exchanged between the participants of one scenario, in time order from top to bottom: who calls whom, in what order, and what comes back, with frames for the parts that are chosen, optional, repeated or cut short.
2. Distinguish synchronous and asynchronous messages and replies in UML's notation. A synchronous message, whose sender waits, is a solid line with a filled arrowhead; an asynchronous message, whose sender does not wait, is a solid line with an open arrowhead; a reply is a dashed line.
3. What is the difference between alt, opt and break? Alt chooses at most one of several parts, the one whose guard is true. Opt runs its single part or does not. Break runs its part instead of the rest of the enclosing fragment, which is skipped, and is used for an early exit such as a refusal.
4. What happens, in the worked diagram, when two students order the last plate at the same moment? Both send the conditional update that takes stock only if enough is left. The database lets only one of them change the row: that update changes one row and the order goes on; the other changes none, and that student's order is rolled back and refused as sold out.
5. Why does the order service take items in order of their id? So that two orders that share items always take them in the same order. Each then waits for the other at most once, in one direction, and they can never deadlock waiting for each other in a circle.
6. What was wrong with the worked team's first sequence diagram, and how was it fixed? It drew a stock shortage as an alt inside the loop and then continued to insert and commit the order, so the diagram showed an order saved after a rollback; and it had no refusal for a second order in the same slot. Each refusal was redrawn as a break at the level of the whole diagram, and every message was checked against the code.
The rest of this subject
These notes are cut from the University's printed syllabus. Open the syllabus itself for the same subject.