Mermaid Sequence Diagram: alt, opt and loop Blocks
Payments fail, cards get declined and services time out. Show those paths in a Mermaid sequence diagram with opt, loop and alt blocks, using an online shop's payment flow in the free Mermaid live editor.
Step by step
When things go wrong
- Payment paths. Real payments go wrong. Cards get declined and services time out. A sequence diagram with only the happy path hides that. Here's the online shop payment flow we'll write in Mermaid, with opt, loop and alt blocks.
- Sequence diagram. Clear the editor and type sequence diagram, as one word with a capital D.
sequenceDiagram
The happy start
- Participants. Add the customer as an actor, then the shop and the payment API as participants. Then the first message, an arrow with two greater than signs. Place order. Three lifelines and one message. Now let's add the paths that only happen sometimes.
actor C as Customer participant S as Shop participant P as Payment API C->>S: Place order
opt
- opt. First, opt. Opt means optional: the messages inside only happen when the condition is true. Only a customer with no saved card types in card details. Close every block with the word end.
opt No saved card S->>C: Ask for card details C->>S: Enter card details end
loop
- loop. Next, loop. A loop repeats the messages inside it. The shop charges the card, and if the payment API times out, the shop tries again, up to three times. Two dashes make a dotted reply. Each block is a frame. The keyword sits in the corner, and the condition sits next to it in square brackets.
loop Up to 3 tries S->>P: Charge card P-->>S: Timeout end
alt
- alt. When it answers, the payment API sends the result. Now alt, for either-or outcomes. Type alt and the first case, approved: the shop confirms the order. Until the block is closed, Mermaid greys out the diagram. The word else adds the other case. Declined: the shop asks for another card. Type end to close the block. The alt frame has two parts, split by a dashed line. Only one of them happens for each order. Here's the declined path. Every part of every block is a scenario, and each scenario can become a test case.
P-->>S: Payment result alt Approved S-->>C: Order confirmedelse Declined S-->>C: Ask for another card end - The whole flow. Here's the whole payment flow. An optional card step, a retry loop, and two outcomes, all in plain text.
Recap
- The rules. So, use opt for steps that only sometimes happen, loop for retries and repeats, and alt with else for either-or outcomes. Close every block with end.