UML in Practice: Class, Sequence, State, Activity, Component, Package & Deployment Diagrams
"The objective of UML is to provide system architects, software engineers, and software developers with tools for analysis, design, and implementation of software-based systems as well as for modeling business and similar processes." — Object Management Group, OMG Unified Modeling Language Version 2.5.1 (formal/2017-12-05), Clause 1 "Scope", December 2017
Summary: UML is a standard picture language for software: 14 diagram types, half for structure (what exists) and half for behaviour (what happens over time). In daily work you need about seven of them, drawn as sketches, kept as text in the repository. Focus: The 14 diagrams and when each one answers a real question; class-diagram notation in depth (visibility, multiplicity, the six relationship lines, association classes, qualifiers, stereotypes, OCL); sequence, state machine and activity notation; component, package and deployment views; Fowler's three modes; PlantUML and Mermaid; the C4 model; reading Go and Laravel code into diagrams. Learning goal: Pick the right diagram for a design question, draw it correctly in five minutes as PlantUML or Mermaid text, read any UML a colleague hands you, and keep the diagrams honest by generating or testing them against Go and Laravel code.
This page is the complete reference for UML as working engineers use it. It covers the history (Booch, Rumbaugh, Jacobson and the OMG), all 14 diagram types of UML 2.5.1, the notation details that cause most misreadings, Fowler's sketch/blueprint/programming-language split, text-based UML with PlantUML and Mermaid, the C4 model as the modern complement for architecture, and one checkout system drawn six ways and implemented in Go and Laravel. It does not re-teach its neighbours: the difference between architecture and design is on Architecture vs Design, CRC cards and conceptual design on The Design Process, the object-oriented ideas behind every box on Object-Oriented Modeling, class responsibilities on Low-Level Design, and the pattern diagrams on Design Patterns. Interfaces as seams are on Interface Segregation and Dependency Inversion.
Page map
| If you are looking for | Go to |
|---|---|
| All 14 diagrams and the three relationship tables on one screen | Everything in one minute |
| Why a standard notation exists and what it costs | Why UML exists |
| Booch, OMT, OOSE, the OMG, UML 1.x to 2.5.1 | Where it comes from |
| Sketch vs blueprint vs programming language | Fowler's three modes |
| Structure vs behaviour taxonomy | The 14 diagrams |
| Visibility, multiplicity, arrows, association classes, qualifiers, stereotypes, OCL | Class diagram |
| Object, package, component, composite structure, profile, deployment | Structure diagrams |
| Use case, activity, state machine | Behaviour diagrams |
| Sequence, communication, interaction overview, timing | Interaction diagrams |
| Frames, metamodel, XMI, text syntaxes | Mechanics |
| Turning a Go package or a Laravel module into a class diagram | Reading Go, Reading Laravel |
| Checkout drawn six ways and coded in Go and Laravel | Go, Laravel, Worked system |
| UML vs C4, and which diagram for which question | UML and C4, Choosing |
| Diagrams for monoliths, modules, services and replicas | In architecture |
| Hands-on: generate, render and test diagrams | Lab |
| Wrong beliefs, cheat sheet, self-check, every term | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The 14 diagrams of UML 2.5.1. The list is Annex A of the specification; "used daily" is our judgement from practice, not the spec's.
| Diagram | Family | Question it answers | Use it when | Used daily? | PlantUML / Mermaid |
|---|---|---|---|---|---|
| Class | Structure | What types exist and how are they related? | Domain model, module API, review of a design | Yes | Yes / Yes |
| Object | Structure | What does memory look like at one moment? | Explaining a tricky data shape, test fixtures | Sometimes | Yes / No |
| Package | Structure | Which modules depend on which? | Layering, import rules, modular monolith | Yes | Yes / via flowchart |
| Component | Structure | Which replaceable parts provide and require which interfaces? | Ports and adapters, plug-in boundaries | Yes | Yes / via flowchart or C4 |
| Composite structure | Structure | What is wired inside one class or component? | Embedded systems, parts and ports | Rarely | Partial / No |
| Deployment | Structure | What runs where, and how do machines talk? | Infrastructure, environments, failover | Yes | Yes / via C4Deployment |
| Profile | Structure | Which stereotypes extend UML for my domain? | Tool vendors, SysML-style extensions | Rarely | No / No |
| Use case | Behaviour | Who uses the system for which goal? | Scope workshops (text matters more) | Rarely | Yes / No |
| Activity | Behaviour | What steps happen, in which order, by whom, in parallel? | Business workflows, pipelines, sagas | Yes | Yes / via flowchart |
| State machine | Behaviour | Which states can one thing be in, and what moves it? | Orders, payments, subscriptions, protocols | Yes | Yes / Yes |
| Sequence | Interaction | Who calls whom, in what order, for one scenario? | API flows, debugging, code review | Yes | Yes / Yes |
| Communication | Interaction | Who talks to whom (numbered messages on links)? | Small collaborations on a whiteboard | Rarely | No / No |
| Interaction overview | Interaction | How do several interactions chain together? | Long scenarios built from sequence fragments | Rarely | No / No |
| Timing | Interaction | How do states change against a time axis? | Real-time and hardware, timeouts | Rarely | Yes / No |
The six class-diagram lines. Every row is unpacked in the class diagram block.
| Relationship | Line | Plain words | PlantUML / Mermaid | Typical code |
|---|---|---|---|---|
| Association | Solid line, optional open arrow | A has a long-lived reference to B | A --> B | Field holding B or B's id |
| Aggregation | Solid line, hollow diamond at the whole | B is part of A but can be shared or outlive it | A o-- B | Slice of pointers to shared things |
| Composition | Solid line, filled diamond at the whole | A owns B; B dies with A | A *-- B | Slice of values; ON DELETE CASCADE |
| Dependency | Dashed line, open arrow | A uses B briefly (parameter, local, creation) | A ..> B | Function argument, new B() |
| Generalization | Solid line, hollow triangle at the parent | A is a kind of B | A --|> B | extends; Go embedding is not this |
| Realization | Dashed line, hollow triangle at the interface | A implements interface B | A ..|> B | PHP implements; Go implicit |
Sequence-diagram arrows.
| Message | Line and head (UML 2.5.1, 17.4.4) | PlantUML | Mermaid |
|---|---|---|---|
| Synchronous call | Solid line, filled head | A -> B | A->>B |
| Asynchronous signal or call | Solid line, open head | A ->> B | A-)B |
| Reply | Dashed line | B --> A or return | B-->>A |
| Create | Dashed line, open head, to the new lifeline's head | create B then A -> B | create participant B |
| Delete | Message ending in an X on the lifeline | destroy B | destroy B |
| Lost / found | Black dot at the end / at the start | A ->x B (lost), [o-> B (found) | not supported |
Why UML exists
A design you cannot show is a design only you can review. Before 1997 every object-oriented method had its own boxes and arrows, so a diagram from one team needed a legend for the next. UML fixed the notation so that a filled diamond means the same thing in every book, tool and code review. The trade is the usual one: a shared language is more precise and more to learn.
| Ad hoc boxes and lines | UML | C4 model |
|---|---|---|
| Zero learning cost | A real learning cost (the spec is 796 pages) | Small learning cost |
| Every arrow needs a legend | Arrows have fixed meanings | Arrows are labelled relationships |
| Mixes levels (a class next to a server) | Separates views by diagram type | Separates views by zoom level |
| Cannot be checked against code | Can be generated from code and tested | Code level often generated |
| Good for one meeting | Good for design reviews and teaching | Good for architecture documentation |
The analogy we reuse on this page: a building's drawing set. One house has a floor plan, an electrical plan, a plumbing plan and a site plan. Nobody draws one picture with every wire and pipe; each drawing answers one question for one reader, and all of them describe the same building. UML is that drawing set for software: the class diagram is the floor plan, the sequence diagram is "what happens when someone rings the bell", the deployment diagram is the site plan. The symbols are standard so that an electrician from another city can read them.
Three common misunderstandings, up front
- "UML is a heavyweight process." UML is a notation. The heavy process that came with it in the 1990s (the Rational Unified Process) is a separate thing. A two-minute whiteboard sketch with correct arrows is UML.
- "A diagram must show everything." The spec itself says the opposite for multiplicity: "If no multiplicity is shown on the diagram, no conclusion may be drawn about the multiplicity in the model." A diagram is a view of a model; leaving things out is normal.
- "UML is dead, use C4 instead." C4 covers static architecture structure at four zoom levels and its own FAQ says to "supplement the C4 diagrams with UML state diagrams, timing diagrams, etc if you need to". Sequence diagrams and state machines have no C4 replacement.
Where it comes from
The specification states the origin in its first clause:
"The initial versions of UML (UML 1) originated with three leading object-oriented methods (Booch, OMT, and OOSE), and incorporated a number of best practices from modeling language design, object-oriented programming, and architectural description languages." — OMG UML 2.5.1, Clause 1
The three methods belonged to the people later called the "three amigos": Grady Booch (the Booch method), James Rumbaugh (OMT, the Object Modeling Technique) and Ivar Jacobson (OOSE, Object-Oriented Software Engineering, which introduced use cases). Fowler's book page summarises why it mattered:
"The UML appeared in 1997 to eliminate the bedlam that had overtaken graphical modeling languages in the object-oriented world." — Martin Fowler, UML Distilled book page, martinfowler.com
| Year | Event | Source |
|---|---|---|
| 1994 | Rational Software hires James Rumbaugh; Booch and OMT merge work | Wikipedia (secondary) |
| 1995 | Ivar Jacobson joins Rational; OOSE and use cases come in | Wikipedia (secondary) |
| Jan 1997 | UML Partners propose UML 1.0 to the OMG | Wikipedia (secondary) |
| Nov 1997 | OMG adopts UML 1.1 | Wikipedia (secondary) |
| 1997 | Fowler's UML Distilled, the first UML book | Fowler's book page |
| 2003 | UML Distilled 3rd edition rewritten for UML 2 | Fowler's book page |
| 2005 | UML 2.0 replaces 1.5; ISO/IEC 19501:2005 published | Wikipedia (secondary) |
| 2012 | ISO/IEC 19505-1:2012 (UML 2 infrastructure) | Wikipedia (secondary) |
| Dec 2017 | UML 2.5.1, OMG document formal/2017-12-05 (current) | OMG spec cover page |
UML 2.0 added the interaction operators (alt, opt, loop, par, ref) that make sequence diagrams useful, and UML 2.5 rewrote the text for readability: "The UML Infrastructure no longer forms part of the UML specification. The entire UML specification is constituted in this document." The same clause drops the old compliance levels L0 to L3: "A tool either complies with the whole of UML or it does not." The OMG's own list of published versions runs 1.5, 2.0, 2.1.2, 2.2, 2.3, 2.4.1, 2.5.1. The constraint language that sits beside UML, OCL, is a separate OMG specification; its page states that "OCL version 2.4 is the latest version of OCL that is aligned with UML 2.4.1 and MOF 2.4.1."
Two later threads matter for practitioners. Text-based UML (PlantUML, then Mermaid) moved diagrams into source control, and GitHub now renders Mermaid in Markdown. And Simon Brown's C4 model, which its FAQ says "was inspired by UML and the 4+1 model for software architecture", gave teams a lighter way to draw architecture; Kruchten's 4+1 views is the architecture-side ancestor.
Fowler's three modes: sketch, blueprint, programming language
Fowler's 2003 bliki entry explains why people argue about UML: "people differ about what should be in the UML because there are differing fundamental views about what the UML should be." He names three modes.
| Mode | Goal | Fowler's words | Tools | Where it lives today |
|---|---|---|---|---|
| Sketch | Communicate one idea, fast | "The essence of sketching is selectivity." | Whiteboard, PlantUML, Mermaid | Design reviews, PRs, docs |
| Blueprint | Hand a complete design to coders | "a UmlMode that focuses on completeness" | CASE tools, round-trip engineering | Regulated and safety-critical domains |
| Programming language | Generate the program from the model | "I don't believe that graphical programming will succeed just because it's graphical." | MDA, executable UML | Niche (embedded, some state-machine code generators) |
"Hence my sound-bite “comprehensiveness is the enemy of comprehensibility”" — Martin Fowler, UmlAsSketch, bliki
Each mode works in two directions. Forward engineering draws before coding; reverse engineering draws from existing code to understand it. Blueprint tools that do both are round-trip tools; Fowler calls tools that use the source code itself as the repository "tripless". This page is written for the sketch mode, with one blueprint habit borrowed: keep the sketch as text next to the code and test it, so it cannot silently rot.
The concepts, one by one
Each block follows the same order: plain words, the usual wrong belief, a precise definition (quoted from UML 2.5.1 where the wording matters), a sequence or scenario, real situations, the notation, and the diagram as PlantUML and Mermaid text. The running example is one checkout: a customer places an order, stock is reserved, the card is charged, the order is paid and shipped.
The 14 diagrams: structure vs behaviour Must-know
In plain words: structure diagrams are photographs (what exists); behaviour diagrams are films (what happens). Interaction diagrams are the films about messages.
Common misunderstanding: "Every system needs all 14." The spec calls the taxonomy "a logical organization" and adds that "the boundaries between the various kinds of diagram types are not strictly enforced." Most teams use seven, and most single designs need two or three.
Definition: UML 2.5.1 Annex A: "Structure diagrams show the static structure of the objects in a system. That is, they depict those elements in a specification that are irrespective of time." And: "Behavior diagrams show the dynamic behavior of the objects in a system, including their methods, collaborations, activities, and state histories."
Design question First diagram Second diagram
1 "What is an Order made of?" class object (one example)
2 "What happens when the customer clicks Pay?" sequence activity (if many actors)
3 "Can a shipped order be canceled?" state machine -
4 "Which module may import which?" package component
5 "What runs on which server?" deployment C4 containerReal scenario: a design review for a refund feature needs a state machine (is "refunded" reachable from "shipped"?) and a sequence diagram (who calls the PSP, who emits the event); nobody needs a use case diagram. An onboarding document needs one C4 container diagram and one class diagram of the core domain.
Diagram frames. Annex A lets any diagram sit in a frame whose heading is [<kind>]<name>[<parameters>], with the short kinds act, cmp, dep, sd, pkg, stm, uc (and long forms such as class). When you see sd PlaceOrder in a corner, it is a sequence diagram named PlaceOrder.
Class diagram Must-know
In plain words: boxes are types, compartments list what they hold and what they can do, and the line style between two boxes says how they are related.
Common misunderstanding: "The diamond means 'has a'." Every association means "has a". The hollow diamond (aggregation) adds almost nothing; the spec says "Precise semantics of shared aggregation varies by application area and modeler." Only the filled diamond (composition) has a strong, testable meaning.
Definition: a class symbol is a rectangle with a name compartment and optional attribute and operation compartments. Attributes follow the property grammar of clause 9.5.4: [<visibility>] ['/'] <name> [':' <prop-type>] ['[' <multiplicity-range> ']'] ['=' <default>] ['{' <prop-modifier> [',' <prop-modifier>]* '}'], with <visibility> ::= ‘+’ | ‘-‘ | ‘#’ | ‘~’ (quote marks normalised in the property line).
Visibility.
| Symbol | UML name | Java / C# | PHP | Go |
|---|---|---|---|---|
+ | public | public | public | Exported identifier (capital letter) |
- | private | private | private | No equivalent per type |
# | protected | protected | protected | No equivalent (no inheritance) |
~ | package | package-private (Java) | No equivalent | Unexported identifier: visible in the whole package |
Multiplicity. Written [lower..upper] on a property or at an association end; * means unbounded; omitted means "not shown", not "one" on a diagram, although in the attribute grammar an omitted multiplicity "implies a multiplicity of 1 (exactly one)".
| Written | Means | Typical code |
|---|---|---|
1 | Exactly one | Non-null field |
0..1 | Optional | Nullable field, pointer, ?Type |
* or 0..* | Any number | Slice, collection, hasMany |
1..* | At least one | Collection plus a validation rule |
2..4 | Bounded | Domain rule (e.g. 2 to 4 players) |
{ordered}, {unique}, {readOnly} | Property modifiers | Sorted slice, set, immutable field |
The six relationships. Spec wording, per line: a Dependency "is shown as a dashed arrow between two model Elements"; "A Realization is shown as a dashed line with a triangular arrowhead at the end that corresponds to the realized Element"; a Generalization "is shown as a line with a hollow triangle as an arrowhead"; and for associations, "When one end has aggregation = AggregationKind::shared a hollow diamond is added", while composition "differs in having the diamond filled in". The meaning of composition:
"Composite aggregation is a strong form of aggregation that requires a part object be included in at most one composite object at a time. If a composite object is deleted, all of its part instances that are objects are deleted with it." — OMG UML 2.5.1, 9.5.3
PlantUML's documentation compresses it to "The part cannot exist without the whole" (composition) and "The part can exist independently of the whole" (aggregation). Navigability is an open arrowhead on an association end; "A small x on the end of an Association indicates the end is not navigable."
Association class. When the link itself has data, the link is a class. The spec: "An AssociationClass is shown as a Class symbol attached to the Association path by a dashed line." Classic examples: Enrollment between Student and Course (grade, date); OrderLine between Order and Product (quantity, price at time of sale). In a relational database it becomes a join table with extra columns; in Laravel, a belongsToMany with withPivot('qty', 'unit_price') or a custom pivot model.
Qualified association. A qualifier is a small box on one end that acts like a map key: Order [lineNo] → 0..1 OrderLine reads "given an order and a line number, there is at most one line". The spec: a qualified end "has qualifiers that partition the instances associated with an instance at that end". In code it is a map, or a composite unique key (order_id, line_no).
Abstract, interface, enumeration, stereotypes. "The name of an abstract Classifier is shown in italics, where permitted by the font in use" (or with {abstract}). An interface uses the keyword «interface»; an enumeration «enumeration»; a data type «dataType». A stereotype such as «entity», «control», «boundary» or «repository» is a profile extension that tags an element with a role; keywords in guillemets that UML itself defines (like «interface» or «use») are not stereotypes but are drawn the same way.
Constraints and OCL. Anything in braces is a constraint: {qty > 0}, {ordered}, {xor}. Precise constraints can be written in OCL, for example:
context Order
inv atLeastOneLine: self.lines->notEmpty()
inv totalMatches: self.total = self.lines->collect(subtotal)->sum()
context Order::fire(e : Event)
pre: e = Event::stockReserved implies self.lines->notEmpty()In practice OCL appears in model-driven tooling; in code the same rules become validation, database CHECK constraints and tests.
Real scenario: a domain review of Order/OrderLine/Product where the composition question ("can a line exist without its order?") decides the foreign key's ON DELETE rule; a Laravel module review where an interface plus realization shows that StripeGateway can be swapped; a code review where an inheritance triangle reveals a Square extends Rectangle Liskov problem.
The checkout's full class diagram is drawn in the worked system; here is its text:
@startuml
hide circle
class Customer {
- id : CustomerId
- email : String
}
class Order <<entity>> {
- id : OrderId
- status : OrderStatus
+ /total : Money
+ addLine(sku, qty, price)
+ fire(e : Event)
}
class OrderLine {
- sku : String
- qty : Integer {qty > 0}
- unitPrice : Money
+ /subtotal() : Money
}
class Product {
- sku : String
- price : Money
}
enum OrderStatus {
Pending
Reserved
Paid
Shipped
Canceled
}
abstract class Payment {
- amount : Money
}
class CardPayment
class WalletPayment
interface PaymentGateway {
+ charge(o, amt)
}
class StripeGateway
class CheckoutService <<control>> {
+ placeOrder(cmd)
}
Customer "1" -- "0..*" Order
' qualifier syntax from PlantUML's "Qualified associations" section
Order [lineNo] *-- "0..1" OrderLine : lines
OrderLine "0..*" --> "1" Product
Order --> OrderStatus : status
Order "1" -- "0..*" Payment
Payment <|-- CardPayment
Payment <|-- WalletPayment
CheckoutService ..> Order : <<create>>
CheckoutService ..> PaymentGateway : <<use>>
PaymentGateway <|.. StripeGateway
@endumlclassDiagram
class Customer {
-CustomerId id
-String email
}
class Order {
<<entity>>
-OrderId id
-OrderStatus status
+total() Money
+addLine(sku, qty, price)
+fire(Event e)
}
class OrderLine {
-String sku
-int qty
-Money unitPrice
+subtotal() Money
}
class OrderStatus {
<<enumeration>>
Pending
Reserved
Paid
Shipped
Canceled
}
class Payment {
<<abstract>>
-Money amount
}
class PaymentGateway {
<<interface>>
+charge(o, amt)
}
Customer "1" -- "0..*" Order
Order "1" *-- "1..*" OrderLine : lines
OrderLine "0..*" --> "1" Product
Order --> OrderStatus : status
Order "1" -- "0..*" Payment
Payment <|-- CardPayment
Payment <|-- WalletPayment
CheckoutService ..> Order : create
CheckoutService ..> PaymentGateway : use
PaymentGateway <|.. StripeGateway
%% Mermaid has no qualifiers and no derived (/) markerObject diagram Good to know
In plain words: a photograph of memory: concrete objects with values, linked to each other, at one instant.
Common misunderstanding: "An object diagram is a class diagram with different names." It shows instances, so multiplicities become actual counts and you can see the case that breaks a rule (an order with zero lines, two customers sharing one cart).
Definition: an object is an InstanceSpecification: "An InstanceSpecification represents the possible or actual existence of instances in a modeled system". It is drawn like a class with the name underlined as name : Type, and slots attribute = value.
Moment Object state (after PlaceOrder succeeded)
1 t0 c7:Customer -- o1:Order{status=pending}
2 t1 o1 *-- l1:OrderLine{lineNo=1, qty=2}, l2:OrderLine{lineNo=2, qty=1}
3 t2 o1{status=paid, /total=33.00 EUR}Real scenario: explaining a recursive structure (a category tree, a bill of materials); documenting a test fixture; showing support engineers exactly what a broken production record looked like.
@startuml
object "c7 : Customer" as c7 {
email = "a@b.io"
}
object "o1 : Order" as o1 {
id = "o-1"
status = paid
}
object "l1 : OrderLine" as l1 {
lineNo = 1
qty = 2
}
object "l2 : OrderLine" as l2 {
lineNo = 2
qty = 1
}
c7 -- o1
o1 *-- l1
o1 *-- l2
@enduml%% Mermaid has no object diagram; a classDiagram with instance names is the usual stand-in
classDiagram
class c7_Customer {
email = "a@b.io"
}
class o1_Order {
id = "o-1"
status = paid
}
class l1_OrderLine {
lineNo = 1
qty = 2
}
c7_Customer -- o1_Order
o1_Order *-- l1_OrderLinePackage diagram Important
In plain words: folders and the "may import" arrows between them.
Common misunderstanding: "A package diagram is just the folder tree." The folder tree shows containment; the package diagram's value is the dependency arrows, which you can then enforce (Go's internal/, architecture tests, deptrac-style rules).
Definition: a package is a namespace for packageable elements, drawn as a tabbed folder. Dependencies between packages are dashed arrows, optionally with «import» (public import: the imported names become visible) or «access» (private import), and «merge» for package merge (used inside the UML metamodel itself, rarely in applications).
Rule drawn on the package diagram Enforced by
1 web ..> checkout Go: import path; PHP: architecture test
2 checkout ..> payments, inventory only through interfaces (ports)
3 payments, inventory ..> platform platform imports nothing above it
4 nobody ..> web a cycle here fails the Go buildReal scenario: the module map of a modular monolith; a layering rule ("domain imports nothing from infrastructure") that the Dependency Inversion chapter enforces; finding import cycles before Go refuses to compile them.
@startuml
package web {}
package checkout {}
package payments {}
package inventory {}
package platform {}
web ..> checkout : <<import>>
checkout ..> payments : <<use>>
checkout ..> inventory : <<use>>
payments ..> platform
inventory ..> platform
@endumlflowchart TB
web["pkg web"] -. import .-> checkout["pkg checkout"]
checkout -. use .-> payments["pkg payments"]
checkout -. use .-> inventory["pkg inventory"]
payments -.-> platform["pkg platform"]
inventory -.-> platformComponent diagram Must-know
In plain words: replaceable building blocks with sockets and plugs: what each part offers (provided interface) and what it needs (required interface).
Common misunderstanding: "A component is a microservice." In UML a component is any modular, replaceable unit: a Go package with an interface seam, a Laravel module, a library, or a service. Deployment is a separate question for the deployment diagram.
Definition: "A Component represents a modular part of a system that encapsulates its contents and whose manifestation is replaceable within its environment." Interfaces attach in two ways, from clause 10.4.4: a provided interface by "a circle or ball, often also called lollipop"; a required interface by "a half-circle or socket". A ball in a socket is an assembly connector. A port is a named interaction point on the component's border.
Request Component Required -> Provided
1 POST /orders Web API PlaceOrder -> Checkout
2 charge card Checkout PaymentGateway -> PSP adapter
3 reserve stock Checkout Inventory -> Inventory adapter
4 persist Checkout Orders -> Order storeReal scenario: a hexagonal ("ports and adapters") service where the domain component requires PaymentGateway and two adapters provide it (Stripe in production, a fake in tests); a Laravel package whose service provider binds a contract to an implementation; a plug-in system (Microkernel).
@startuml
component "Web API" as Web
component Checkout
component "PSP adapter" as PSP
component "Inventory adapter" as Inv
component "Order store" as Store
() PlaceOrder
() PaymentGateway
() "Inventory" as InvPort
() Orders
Checkout - PlaceOrder
Web ..> PlaceOrder : use
PSP - PaymentGateway
Inv - InvPort
Store - Orders
Checkout ..> PaymentGateway : use
Checkout ..> InvPort : use
Checkout ..> Orders : use
@enduml%% Mermaid has no UML component diagram; flowchart with circle nodes as interfaces
flowchart LR
Web["«component» Web API"] -- requires --> PO(("PlaceOrder"))
PO --- Checkout["«component» Checkout"]
Checkout -- requires --> PG(("PaymentGateway"))
PG --- PSP["«component» PSP adapter"]
Checkout -- requires --> INV(("Inventory"))
INV --- InvA["«component» Inventory adapter"]
Checkout -- requires --> ORD(("Orders"))
ORD --- Store["«component» Order store"]Composite structure and profile diagrams Good to know
In plain words: a composite structure diagram opens one box and shows the parts and ports wired inside it; a profile diagram defines your own stereotypes.
Common misunderstanding: "Composite structure is the same as composition." Composition is a relationship on a class diagram; a composite structure diagram shows the runtime wiring of parts inside one classifier, connected through ports with connectors.
Definition: a composite structure diagram "Shows the internal structure of a StructuredClassifier" (Annex B, diagram kinds). A profile diagram shows stereotypes extending metaclasses: "A Stereotype defines an extension for one or more metaclasses". SysML, the systems-engineering language, is the best-known profile of UML.
| Diagram | When it pays off | Typical reader |
|---|---|---|
| Composite structure | Embedded controllers, hardware/software parts, a component with internal sub-components and ports | Systems engineers |
| Profile | Defining «aggregateRoot», «repository», «microservice» once so a tool can validate them | Tool builders, architecture teams |
Deployment diagram Must-know
In plain words: the site plan: which machines and runtimes exist, which built files run on them, and which network paths connect them.
Common misunderstanding: "Deployment means Kubernetes YAML." The diagram is the picture of the topology; one diagram per environment (production, staging) is normal, because clustering and replicas differ.
Definition: "A Node is computational resource upon which Artifacts may be deployed, via Deployment relationships, for execution." Nodes are drawn as 3D boxes and can nest; standard kinds are «device» and «executionEnvironment». "An artifact is the specification of a physical piece of information that is used or produced by a software development process, or by deployment and operation of a system", for example "source files, scripts, and binary executable files, a table in a database system". An artifact «manifest»s a component. Lines between nodes are communication paths, labelled with the protocol.
Hop From -> To Protocol Failure to plan for
1 customer request Browser -> Load balancer HTTPS TLS expiry
2 route Load balancer -> api pod HTTP pod restart
3 write order api pod -> PostgreSQL primary SQL/5432 failover, pool exhaustion
4 replicate primary -> replica WAL stream replica lag
5 event api pod -> RabbitMQ -> worker AMQP broker down, redelivery
6 charge api pod -> Stripe HTTPS timeout, idempotency keyReal scenario: an incident review that needs to show the replica a stale read came from; a capacity plan; a compliance document listing where card data can travel.
@startuml
node "Browser" as B
node "Load balancer" as LB
node "k8s cluster" {
node "api pod" {
artifact "checkout-api (Go)" as api
}
node "worker pod" {
artifact "laravel-worker:1.4" as worker
}
}
database "PostgreSQL" as PG
database "replica" as REP
queue "RabbitMQ" as MQ
cloud "Stripe" as ST
B -- LB : HTTPS
LB -- api : HTTP
api -- PG : SQL
PG -- REP : WAL
api -- MQ : AMQP
worker -- MQ : AMQP
api -- ST : HTTPS
@endumlC4Deployment
title Checkout, production
Deployment_Node(k8s, "k8s cluster", "Kubernetes") {
Deployment_Node(apiPod, "api pod") {
Container(api, "checkout-api", "Go")
}
Deployment_Node(workerPod, "worker pod") {
Container(worker, "laravel-worker", "PHP 8.4")
}
}
Deployment_Node(db, "PostgreSQL primary") {
ContainerDb(pg, "orders schema", "PostgreSQL")
}
Rel(api, pg, "SQL", "TCP 5432")Use case diagram, and why it is weak Important
In plain words: stick figures (actors) connected to ovals (goals) inside a box (the system).
Common misunderstanding: "The use case diagram is the use case." The diagram only lists names. Jacobson's use cases are text: a main success scenario and extensions. Fowler's note on use cases and stories puts the value in the narrative: "Use cases organize requirements to form a narrative of how users relate to and use a system."
Definition: an actor is a role outside the subject; a use case is a goal the subject delivers. «include» is a dashed arrow "pointing from the base UseCase to the included UseCase"; «extend» is a dashed arrow "pointing from the extending UseCase towards the extended UseCase", optionally with a condition and extension points.
Why it is weak in practice:
| Problem | What happens | Better tool |
|---|---|---|
| No order, no data, no errors | The interesting part (what if the card is declined?) is invisible | Use case text, sequence diagram |
| «include»/«extend» debates | Teams argue arrows instead of requirements | Plain bullet extensions |
| Looks complete while saying little | Ten ovals pass a review that found nothing | User stories with acceptance criteria |
| Functional decomposition creeps in | "Validate address" becomes a use case | Goals at user level only |
It still earns its place in a scope workshop: one diagram that shows actors (including secondary ones such as a payment provider) and the system boundary.
@startuml
left to right direction
actor Customer
actor "Payment provider" as PSP
rectangle Shop {
usecase "Place order" as UC1
usecase "Authenticate" as UC2
usecase "Apply coupon" as UC3
}
Customer -- UC1
UC1 -- PSP
UC1 .> UC2 : <<include>>
UC3 .> UC1 : <<extend>>
@enduml%% Mermaid has no use case diagram; stadium nodes as ovals
flowchart LR
Customer(["actor Customer"]) --- UC1(["Place order"])
UC1 --- PSP(["actor Payment provider"])
UC1 -. include .-> UC2(["Authenticate"])
UC3(["Apply coupon"]) -. extend .-> UC1Activity diagram Must-know
In plain words: a flowchart with superpowers: real parallelism (fork/join), swimlanes for who does each step, and data flowing between steps.
Common misunderstanding: "An activity diagram is an old flowchart." UML 2 activities have token semantics (Petri-net style): a join waits until every incoming flow has a token, which is exactly how a saga step that waits for two services behaves. A flowchart has no such rule.
Definition: actions (rounded rectangles) connected by control flows; an initial node (black dot) and an activity final node (bullseye); a flow final (circle with X) ends one flow only. "A ForkNode is a ControlNode that splits a flow into multiple concurrent flows"; a join synchronises them. "A DecisionNode is a ControlNode that chooses between outgoing flows", with guards in brackets; a merge node rejoins alternatives without waiting. "An ActivityPartition is a kind of ActivityGroup for identifying ActivityNodes that have some characteristics in common", drawn as swimlanes. Object nodes (rectangles such as o : Order [paid]) carry data along object flows.
Token Node Rule
1 one token fork becomes two tokens: Reserve stock || Authorize payment
2 token A arrives join waits
3 token B arrives join both present -> one token continues to Create order
4 [invalid] at decision decision exactly one outgoing guard must be true
5 token reaches bullseye activity final the whole activity ends, all tokens destroyedReal scenario: a checkout or onboarding workflow spanning teams; a data pipeline with parallel stages; a saga whose compensation paths need to be visible; a Laravel Bus::batch whose jobs run in parallel and a then callback that acts as the join.
@startuml
|Customer|
start
repeat :Submit cart;
|Checkout|
:Validate cart;
backward:Fix cart;
repeat while (cart invalid?) is (yes)
->no;
fork
|Warehouse|
:Reserve stock;
fork again
|Payments|
:Authorize payment;
end fork
|Checkout|
:Create order;
note right: object flow o : Order [paid]
:Send confirmation;
|Customer|
:Read confirmation;
stop
@endumlflowchart TB
subgraph Customer
s((start)) --> submit[Submit cart]
fix[Fix cart]
readc[Read confirmation] --> e(((End)))
end
subgraph Checkout
validate[Validate cart] --> valid{valid?}
create[Create order] --> obj[/o : Order paid/]
obj --> send[Send confirmation]
end
subgraph Warehouse
reserve[Reserve stock]
end
subgraph Payments
auth[Authorize payment]
end
submit --> validate
valid -- no --> fix --> submit
valid -- yes --> reserve & auth
reserve & auth --> create
send --> readcState machine diagram Must-know
In plain words: the list of states one thing can be in, and the only arrows allowed between them. If there is no arrow, the change is illegal.
Common misunderstanding: "A status column with a dropdown is a state machine." Without the transition table, any code can set any status; the "shipped then pending again" bug is the result. The diagram's value is the arrows you did not draw.
Definition: states are rounded rectangles; a transition is labelled with the grammar from clause 14.2.4: [<trigger> [‘,’ <trigger>]* [‘[‘ <guard>’]’] [‘/’ <behavior-expression>]], that is event [guard] / effect. A state can have entry /, exit / and do / behaviours. A composite state contains regions; a state with several regions is orthogonal (isOrthogonal), and its regions run concurrently, drawn separated by a dashed line. Pseudostates include initial (dot), choice, junction, fork, join, entry/exit points, terminate, and history: "Deep history (deepHistory) represents the full state configuration of the most recent visit to the containing Region", while "Shallow history (shallowHistory) represents a return to only the topmost substate". Time events are written after(15 min), change events when(stock = 0).
Event From Guard To Effect
1 stockReserved Pending [lines not empty] Reserved reserve()
2 paymentCaptured Reserved - Paid -
3 paymentDeclined Reserved - Canceled release()
4 after(15 min) Pending - Canceled -
5 dispatched Paid - Fulfilment enters both regions
6 hold, then resume Fulfilment - H* -> same substates as before
7 cancel Paid - (no arrow) rejected: illegal transitionReal scenario: order, payment, subscription and refund lifecycles; TCP connection states; document approval; any column named status. The Go and Laravel code below implement the top-level machine: Fulfilment is flattened into one Shipped state, and the 15-minute timer and the hold/resume history are left out. A test fails when the code and the top-level diagram drift.
@startuml
[*] --> Pending
Pending : entry / startTimer(15m)
Pending --> Reserved : stockReserved [lines not empty] / reserve()
Pending --> Canceled : cancel
Pending --> Canceled : after(15 min)
Reserved --> Paid : paymentCaptured
Reserved --> Canceled : paymentDeclined / release()
Paid --> Fulfilment : dispatched
state Fulfilment {
[*] --> Packing
Packing --> InTransit : shipped
InTransit --> [*]
--
[*] --> Invoicing
Invoicing --> Invoiced
Invoiced --> [*]
}
Fulfilment --> OnHold : hold
OnHold --> Fulfilment[H*] : resume
Fulfilment --> [*]
Canceled --> [*]
@endumlstateDiagram-v2
[*] --> Pending
Pending: Pending (entry / startTimer)
Pending --> Reserved: stockReserved [lines not empty] / reserve()
Pending --> Canceled: cancel, after(15 min)
Reserved --> Paid: paymentCaptured
Reserved --> Canceled: paymentDeclined / release()
Paid --> Fulfilment: dispatched
state Fulfilment {
[*] --> Packing
Packing --> InTransit: shipped
InTransit --> [*]
--
[*] --> Invoicing
Invoicing --> Invoiced
Invoiced --> [*]
}
Fulfilment --> OnHold: hold
OnHold --> Fulfilment: resume (Mermaid has no history pseudostate)
Fulfilment --> [*]
Canceled --> [*]Sequence diagram Must-know
In plain words: time runs down the page; each participant is a vertical dashed line; arrows are calls and replies in order. One diagram is one scenario.
Common misunderstanding: "A sequence diagram shows the algorithm." It shows one trace. Loops and branches are possible with combined fragments, but a diagram full of nested alts is code drawn badly; split it into one diagram per scenario.
Definition: "A Lifeline represents an individual participant in the Interaction." Execution specifications (activations) are "thin rectangles (gray or white) on the lifeline". Message kinds, from clause 17.4.4: "An asynchronous Message ... has an open arrow head", "A synchronous Message ... has a filled arrow head", "A reply Message ... has a dashed line", "An object creation Message ... has a dashed line with an open arrow head", and a deletion message ends in a destruction occurrence (an X). "A lost Message is a Message where the sending event occurrence is known, but there is no receiving event occurrence"; a found message is the reverse. A gate is a message end on the boundary of an interaction or fragment.
Combined fragments (interaction operators).
| Operator | Meaning (UML 2.5.1, 17.6.3) | Use it for |
|---|---|---|
alt | "At most one of the operands will be chosen"; [else] negates the others | Success vs failure branches |
opt | "either the (sole) operand happens or nothing happens" | Optional step (send email if opted in) |
loop | "The loop operand will be repeated a number of times", loop(min,max) | Retries, pagination |
par | "a parallel merge between the behaviors of the operands" | Fan-out calls |
break | Operand runs "instead of the remainder of the enclosing InteractionFragment" | Early exit on error |
critical | Operand is atomic: no interleaving | A section under a lock |
neg, assert | Invalid trace; the only valid trace | Specifying forbidden behaviour |
seq, strict | Weak vs strict ordering of operands | Rare; precision modelling |
ignore, consider | Which messages are (ir)relevant | Rare |
ref | An InteractionUse: "a shorthand for copying the contents of the referenced Interaction" | Reusing "Authenticate" in many diagrams |
Step Lifeline -> lifeline Arrow Code (Go)
1 1 Client -> CheckoutService sync, filled head svc.PlaceOrder(ctx, ...)
2 2 CheckoutService --> o:Order «create», dashed open checkout.NewOrder(id, customer)
3 3 CheckoutService -> Inventory sync s.Inventory.Reserve(...)
4 4 alt [captured] / [declined] combined fragment if err := s.Payments.Charge(...); err != nil
5 5 CheckoutService ->> Broker async, open head s.Events.Publish(...) without waiting
6 6 CheckoutService --> Client reply, dashed return o, nilReal scenario: an API flow in a pull request description; reproducing a race between a webhook and a redirect; showing which service owns a retry; documenting an OAuth or payment handshake; explaining a saga step and its compensation.
@startuml
participant Client
participant ":CheckoutService" as S
participant ":Inventory" as I
participant ":PaymentGateway" as P
participant ":OrderRepo" as R
queue ":Broker" as B
Client -> S ++ : placeOrder(items)
create Order
S --> Order : <<create>>
S -> I : reserve(lines)
I --> S : ok
alt captured
S -> P : charge(o, total)
P --> S : paymentId
S -> Order : fire(paymentCaptured)
else declined
S -> I : release(o)
S -> Order : fire(paymentDeclined)
end
S -> R : save(o)
opt paid
S ->> B : OrderPaid
end
return 201 / 402
@endumlsequenceDiagram
participant C as Client
participant S as CheckoutService
participant I as Inventory
participant P as PaymentGateway
participant R as OrderRepo
participant B as Broker
C->>+S: placeOrder(items)
create participant O as Order
S-->>O: «create»
S->>I: reserve(lines)
I-->>S: ok
alt captured
S->>P: charge(o, total)
P-->>S: paymentId
S->>O: fire(paymentCaptured)
else declined
S->>I: release(o)
S->>O: fire(paymentDeclined)
end
S->>R: save(o)
opt paid
S-)B: OrderPaid
end
S-->>-C: 201 / 402Communication diagram Good to know
In plain words: the same messages as a sequence diagram, but drawn on the links between objects with numbers (1, 1.1, 1.2) instead of top-to-bottom order.
Common misunderstanding: "It is a different kind of information." It is the same interaction seen from the structure side: good for "who talks to whom", poor for "in which order". UML 1 called it a collaboration diagram.
Definition: lifelines as boxes connected by links; each message is a numbered label with a small arrow; nested numbers (1.1, 1.2) mean calls made while handling message 1. The left half of the object diagram figure shows the objects; the right half is the checkout as a communication diagram. Neither PlantUML nor Mermaid has a communication diagram type; an object diagram with numbered link labels is the usual approximation.
Number Link Message
1 1 Client - CheckoutService placeOrder()
2 1.1 CheckoutService - Inventory reserve()
3 1.2 CheckoutService - PSP charge()
4 1.3 CheckoutService - OrderRepo save()
5 1.4 CheckoutService - Broker publish()@startuml
' no communication diagram type: object diagram with numbered link labels
object ":Client" as C
object ":CheckoutService" as S
object ":Inventory" as I
object ":PaymentGateway" as P
object ":OrderRepo" as R
object ":Broker" as B
C -- S : 1: placeOrder() >
S -- I : 1.1: reserve() >
S -- P : 1.2: charge() >
S -- R : 1.3: save() >
S -- B : 1.4: publish() >
@enduml%% no communication diagram type: flowchart with numbered edge labels
flowchart LR
C[":Client"] -- "1: placeOrder()" --> S[":CheckoutService"]
S -- "1.1: reserve()" --> I[":Inventory"]
S -- "1.2: charge()" --> P[":PaymentGateway"]
S -- "1.3: save()" --> R[":OrderRepo"]
S -- "1.4: publish()" --> B[":Broker"]Interaction overview and timing diagrams Good to know
In plain words: an interaction overview is an activity diagram whose boxes are whole sequence diagrams (or refs to them); a timing diagram puts lifelines' states on a horizontal time axis.
Common misunderstanding: "Timing diagrams are for performance graphs." They show state over time with duration constraints ({t..t+3s}), the natural picture for timeouts, debouncing and hardware handshakes.
Definition: both are interaction diagrams (Annex A: "Interaction Overview Diagram - Interactions", "Timing Diagram - Interactions"). PlantUML supports timing diagrams (robust and concise participants); Mermaid has neither.
| Diagram | Good for | Example |
|---|---|---|
| Interaction overview | Chaining scenarios: login, then checkout, then (alt) 3-D Secure | ref Authenticate → decision → ref PlaceOrder |
| Timing | Timeouts and state durations | Order Pending for at most 15 minutes, then Canceled |
Mechanics
Model, diagram and notation are three different things Important
Annex A opens with the distinction: "A UML model consists of elements such as packages, classes, and associations. The corresponding UML diagrams are graphical representations of parts of the UML model." The model lives in a tool's repository (or in your code); each diagram is a filtered view. That is why the same class can appear on ten diagrams with different compartments shown.
| Layer | What it is | Standard | Who cares |
|---|---|---|---|
| Abstract syntax | The metamodel: Class, Property, Association, Lifeline… | UML 2.5.1 (MOF-based) | Tool builders |
| Semantics | What a composition or a join means | UML 2.5.1 semantics clauses | Everyone who argues about arrows |
| Notation | The shapes and the text grammars | UML 2.5.1 notation clauses | Everyone who draws |
| Interchange | Saving models and diagrams between tools | XMI files (UML.xmi), UML DI (Annex B) | Tool migrations |
| Constraints | Precise rules over the model | OCL 2.4 | Model-driven teams |
The text grammars you will actually type
property [+|-|#|~] [/] name [: Type] [[m..n]] [= default] [{readOnly, ordered, unique, id, ...}]
operation [+|-|#|~] name ( [in|out|inout] p : Type [= default], ... ) [: ReturnType] [{query, ...}]
transition trigger [, trigger]* [ [guard] ] [ / effect ]
state name / entry / action / do / activity / exit / action
message [attribute =] name ( arguments ) [: return-value]
multiplicity 1 | 0..1 | * | 0..* | 1..* | m..n
frame sd | stm | act | cmp | dep | pkg | uc <name> [parameters]Diagrams as code: where the text lives and how it renders Must-know
Text-based UML turns a picture into a reviewable diff. PlantUML describes itself as "Text in, diagram out" for use cases, and covers every UML diagram this page uses except communication, interaction overview and profile; Mermaid covers class, sequence and state natively and approximates the rest with flowcharts or its C4 diagrams. GitHub renders Mermaid:
"Diagram rendering is available in GitHub Issues, GitHub Discussions, pull requests, wikis, and Markdown files." — GitHub Docs, Creating diagrams
and "To create a Mermaid diagram, add Mermaid syntax inside a fenced code block with the mermaid language identifier."
| Practice | How | Why |
|---|---|---|
| Keep sources next to code | docs/diagrams/*.puml, *.mmd, or fenced blocks in README.md | The diagram changes in the same PR as the code |
| Render in CI | PlantUML or Mermaid CLI to SVG on merge | Reviewers see the picture, the repo keeps the text |
| Generate what can be generated | Class/package diagrams from code (goplantuml, the umlgen tool below, the Laravel command below) | Generated diagrams cannot rot |
| Hand-write what carries intent | Sequence, state, deployment | Code does not show intent, order or topology well |
| Test hand-written diagrams | Parse the text in a test and compare with code | Drift fails the build (Lab) |
| One question per diagram | Filename says the question: checkout-declined.puml | Fowler: selectivity |
Reading a Go package into a class diagram
Go is the clearest example of the mismatch between UML's object model and a real language. The Go FAQ answers "Is Go an object-oriented language?" with "Yes and no. Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy." And on interfaces:
"A Go type implements an interface by implementing the methods of that interface, nothing more." — The Go FAQ, Why doesn't Go have "implements" declarations?
| Go construct | UML element | Note |
|---|---|---|
type Order struct{...} | Class | Fields are attributes; methods with value or pointer receivers are operations |
| Exported / unexported identifier | + / ~ | Go visibility is per package, so ~ (package), not - (private) |
type PaymentGateway interface{...} | «interface» | Usually declared by the consumer package |
| Type whose method set satisfies an interface | Realization ..|> | Implicit; nothing in the code names it. Assert with var _ I = (*T)(nil) |
Struct embedding type B struct{ A } | Composition plus promoted operations | Not generalization: B is not usable where A is expected |
Field of value or slice type Lines []OrderLine | Composition *-- with multiplicity 0..* | Value semantics: the parts live inside the whole |
| Field of pointer or interface type | Association --> | Shared or replaceable reference |
| Function parameter only | Dependency ..> | |
type Status string with constants | «enumeration» (approximation) | Go has no closed enums; the set is a convention |
| Package | Package; internal/ | Import graph is the package diagram |
Generic type Set[T comparable] | Template class with parameter T | UML templates are rarely drawn in practice |
Two consequences. First, the realization arrow is a fact computed from method sets, so a generator must use go/types (types.Implements), not text search. Second, the interface usually lives next to its consumer, so the package diagram shows checkout owning PaymentGateway and stripe importing nothing from checkout except to satisfy it. That is Dependency Inversion drawn. Existing tools: GoPlantUML ("an open-source library and CLI that generates PlantUML class diagrams from Go source code") and the short umlgen program in this chapter's snippets.
Reading a Laravel module into a class diagram
| PHP / Laravel construct | UML element | Note |
|---|---|---|
class Order extends Model | Class (stereotype «entity» if you like) | Eloquent attributes are not declared fields: read the migration or $casts/casts() |
public / protected / private | + / # / - | PHP has no package visibility |
hasMany(OrderLine::class) | Association "1" -- "0..*" | Composition only if the foreign key cascades (cascadeOnDelete()) |
belongsTo(Customer::class) | Association "0..*" --> "1" | Navigable from the child |
hasOne | Association "1" -- "0..1" | |
belongsToMany(...)->withPivot(...) | Association class | The pivot (or custom pivot model) is the association class |
morphTo / morphMany | Association to an abstract type or «interface» | Polymorphic association; draw the abstraction |
implements PaymentGateway | Realization ..|> | Explicit in PHP, unlike Go |
extends | Generalization --|> | |
use SomeTrait | No UML equivalent | Draw as «trait» stereotype with a dependency, or flatten its members into the class |
Backed enum OrderStatus: string | «enumeration» | Cases are literals; methods are operations |
| Service provider binding contract → implementation | Component assembly (ball and socket) | The container is the wiring on the component diagram |
| Module folder / Composer package | Package | composer.json require is a package dependency |
Go
Example: the checkout from the diagrams
order.go is the class diagram (Money, OrderLine, Order) and the state machine (a transition table plus a guard). The line number is the qualifier; Lines []OrderLine is the composition.
// Package checkout is the code behind the class and state machine
// diagrams of the UML chapter: every type here is one box on the
// class diagram, and Status/Fire are the state machine.
package checkout
import (
"errors"
"fmt"
)
// Money is a value object: two Money values with the same fields are equal.
// UML: «dataType» Money, no identity.
type Money struct {
Cents int64
Currency string
}
// Add returns a new Money; Money is immutable.
func (m Money) Add(o Money) Money {
return Money{Cents: m.Cents + o.Cents, Currency: m.Currency}
}
// Times multiplies the amount by a quantity.
func (m Money) Times(n int) Money {
return Money{Cents: m.Cents * int64(n), Currency: m.Currency}
}
// OrderLine is a part of an Order (composition, filled diamond):
// it has no life outside its order and is deleted with it.
type OrderLine struct {
LineNo int // qualifier: Order[lineNo] -> 0..1 OrderLine
SKU string
Qty int
UnitPrice Money
}
// Subtotal is a derived attribute (/subtotal in UML).
func (l OrderLine) Subtotal() Money { return l.UnitPrice.Times(l.Qty) }
// Status is the state of the Order state machine diagram.
type Status string
// The states, in the order they appear on the diagram.
const (
Pending Status = "pending"
Reserved Status = "reserved"
Paid Status = "paid"
Shipped Status = "shipped"
Canceled Status = "canceled"
)
// Event is a trigger on a transition.
type Event string
// Triggers of the Order state machine.
const (
StockReserved Event = "stockReserved"
PaymentOK Event = "paymentCaptured"
PaymentFailed Event = "paymentDeclined"
Dispatch Event = "dispatched"
Cancel Event = "cancel"
)
// transitions is the state machine as a table: source --trigger--> target.
// Anything missing from the table is an illegal transition.
var transitions = map[Status]map[Event]Status{
Pending: {StockReserved: Reserved, Cancel: Canceled},
Reserved: {PaymentOK: Paid, PaymentFailed: Canceled},
Paid: {Dispatch: Shipped},
}
// ErrIllegalTransition is returned when a trigger has no transition
// from the current state.
var ErrIllegalTransition = errors.New("illegal transition")
// Order is the aggregate root. Lines are owned by composition;
// CustomerID is a plain association by identity, not by pointer.
type Order struct {
ID string
CustomerID string
Lines []OrderLine
Status Status
}
// NewOrder is the «create» message on the sequence diagram.
func NewOrder(id, customerID string) *Order {
return &Order{ID: id, CustomerID: customerID, Status: Pending}
}
// AddLine appends a line; the guard keeps lines immutable after reservation.
func (o *Order) AddLine(sku string, qty int, price Money) error {
if o.Status != Pending {
return fmt.Errorf("add line in state %s: %w", o.Status, ErrIllegalTransition)
}
o.Lines = append(o.Lines, OrderLine{LineNo: len(o.Lines) + 1, SKU: sku, Qty: qty, UnitPrice: price})
return nil
}
// Total is the derived attribute /total : Money.
func (o *Order) Total() Money {
total := Money{Currency: "EUR"}
for _, l := range o.Lines {
total = total.Add(l.Subtotal())
}
return total
}
// Fire applies a trigger. Guard: [lines not empty] on stockReserved.
func (o *Order) Fire(e Event) error {
if e == StockReserved && len(o.Lines) == 0 {
return fmt.Errorf("%s with no lines: %w", e, ErrIllegalTransition)
}
next, ok := transitions[o.Status][e]
if !ok {
return fmt.Errorf("%s --%s-->?: %w", o.Status, e, ErrIllegalTransition)
}
o.Status = next
return nil
}ports.go holds the required interfaces from the component diagram. Nothing in the package says which types provide them.
package checkout
import "context"
// The interfaces below are the provided/required interfaces of the
// component diagram (lollipop on the adapter, socket on the service).
// No Go type says "implements": satisfaction is implicit.
// PaymentGateway is required by Service and provided by a PSP adapter.
type PaymentGateway interface {
Charge(ctx context.Context, orderID string, amount Money) (paymentID string, err error)
}
// Inventory is required by Service and provided by the inventory adapter.
type Inventory interface {
Reserve(ctx context.Context, orderID string, lines []OrderLine) error
Release(ctx context.Context, orderID string) error
}
// Orders is the repository port.
type Orders interface {
Save(ctx context.Context, o *Order) error
}
// Publisher sends domain events (asynchronous messages on the sequence diagram).
type Publisher interface {
Publish(ctx context.Context, topic string, payload any) error
}service.go is the sequence diagram, one message per statement, including the alt fragment and the asynchronous publish.
package checkout
import (
"context"
"fmt"
)
// Service is the «control» lifeline of the checkout sequence diagram.
// It depends on four interfaces (dashed «use» arrows on the class diagram).
type Service struct {
Orders Orders
Inventory Inventory
Payments PaymentGateway
Events Publisher
}
// Item is one requested line in a PlaceOrder command.
type Item struct {
SKU string
Qty int
Price Money
}
// PlaceOrder follows the sequence diagram message by message.
func (s *Service) PlaceOrder(ctx context.Context, id, customerID string, items []Item) (*Order, error) {
o := NewOrder(id, customerID) // create message
for _, it := range items {
if err := o.AddLine(it.SKU, it.Qty, it.Price); err != nil {
return nil, err
}
}
// 1: reserve stock (synchronous call, filled arrow head)
if err := s.Inventory.Reserve(ctx, o.ID, o.Lines); err != nil {
return nil, fmt.Errorf("reserve: %w", err)
}
if err := o.Fire(StockReserved); err != nil {
return nil, err
}
// 2: charge; the alt fragment has two operands
if _, err := s.Payments.Charge(ctx, o.ID, o.Total()); err != nil {
// [declined]: compensate, then cancel
_ = s.Inventory.Release(ctx, o.ID)
_ = o.Fire(PaymentFailed)
_ = s.Orders.Save(ctx, o)
return o, fmt.Errorf("charge: %w", err)
}
// [captured]
if err := o.Fire(PaymentOK); err != nil {
return nil, err
}
if err := s.Orders.Save(ctx, o); err != nil {
return nil, err
}
// 3: asynchronous message (open arrow head): fire and forget
_ = s.Events.Publish(ctx, "order.paid", map[string]any{"id": o.ID, "total": o.Total().Cents})
return o, nil
}memory.go is an adapter that satisfies Orders implicitly; the compile-time assertion is the only written trace of the realization arrow.
package checkout
import (
"context"
"sync"
)
// MemoryOrders is an in-memory adapter. It never says "implements Orders",
// yet umlgen draws `Orders <|.. MemoryOrders`, because its method set
// satisfies the interface. The compile-time assertion below is the only
// place the relationship is written down.
type MemoryOrders struct {
mu sync.Mutex
byID map[string]Order
}
var _ Orders = (*MemoryOrders)(nil)
// Save stores a copy of the order.
func (m *MemoryOrders) Save(_ context.Context, o *Order) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.byID == nil {
m.byID = make(map[string]Order)
}
m.byID[o.ID] = *o
return nil
}The Go angle
Generate structure, hand-write behaviour. The class and package views of a Go module can be produced from source: go list -deps and go list -f with an imports template give the package diagram; go/types gives fields, method sets and interface satisfaction. The generator in this chapter prints PlantUML:
// Command umlgen reads one Go package and prints a PlantUML class diagram.
// It makes the Go/UML mismatch explicit. Exported identifiers become +
// (public) and unexported ones ~ (package), because Go visibility is per
// package, not per type. Interface satisfaction is implicit, so
// realizations are computed with types.Implements instead of being read
// from an "implements" keyword. A value or slice field of a local type
// becomes composition (*--); an interface or pointer field becomes an
// association (-->).
//
// Usage:
//
// go run ./cmd/umlgen ./checkout > checkout.puml
package main
import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"os"
"path/filepath"
"sort"
"strings"
)
func main() {
if len(os.Args) != 2 {
fmt.Fprintln(os.Stderr, "usage: umlgen <package-dir>")
os.Exit(2)
}
pkg, err := load(os.Args[1])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Print(render(pkg))
}
func load(dir string) (*types.Package, error) {
fset := token.NewFileSet()
paths, err := filepath.Glob(filepath.Join(dir, "*.go"))
if err != nil {
return nil, err
}
var files []*ast.File
for _, p := range paths {
if strings.HasSuffix(p, "_test.go") {
continue
}
f, err := parser.ParseFile(fset, p, nil, 0)
if err != nil {
return nil, err
}
files = append(files, f)
}
if len(files) == 0 {
return nil, fmt.Errorf("no Go files in %s", dir)
}
conf := types.Config{Importer: importer.ForCompiler(fset, "source", nil)}
return conf.Check(files[0].Name.Name, fset, files, nil)
}
func vis(name string) string {
if token.IsExported(name) {
return "+"
}
return "~"
}
func short(t types.Type, pkg *types.Package) string {
return types.TypeString(t, types.RelativeTo(pkg))
}
func render(pkg *types.Package) string {
var b, rel strings.Builder
scope := pkg.Scope()
names := scope.Names()
sort.Strings(names)
var ifaces []*types.Named
for _, n := range names {
if tn, ok := scope.Lookup(n).(*types.TypeName); ok {
if named, ok := tn.Type().(*types.Named); ok && types.IsInterface(named) {
ifaces = append(ifaces, named)
}
}
}
fmt.Fprintf(&b, "@startuml\npackage %s {\n", pkg.Name())
for _, n := range names {
tn, ok := scope.Lookup(n).(*types.TypeName)
if !ok {
continue
}
named, ok := tn.Type().(*types.Named)
if !ok {
continue
}
switch u := named.Underlying().(type) {
case *types.Interface:
fmt.Fprintf(&b, " interface %s {\n", n)
for i := 0; i < u.NumMethods(); i++ {
m := u.Method(i)
fmt.Fprintf(&b, " %s%s%s\n", vis(m.Name()), m.Name(), strings.TrimPrefix(short(m.Type(), pkg), "func"))
}
b.WriteString(" }\n")
continue
case *types.Struct:
fmt.Fprintf(&b, " class %s {\n", n)
for i := 0; i < u.NumFields(); i++ {
f := u.Field(i)
fmt.Fprintf(&b, " %s%s : %s\n", vis(f.Name()), f.Name(), short(f.Type(), pkg))
relate(&rel, n, f.Type(), pkg)
}
default:
fmt.Fprintf(&b, " class %s <<%s>> {\n", n, short(u, pkg))
}
ms := types.NewMethodSet(types.NewPointer(named))
for i := 0; i < ms.Len(); i++ {
m := ms.At(i).Obj()
fmt.Fprintf(&b, " %s%s%s\n", vis(m.Name()), m.Name(), strings.TrimPrefix(short(m.Type(), pkg), "func"))
}
b.WriteString(" }\n")
for _, it := range ifaces {
iface := it.Underlying().(*types.Interface)
if iface.NumMethods() > 0 && types.Implements(types.NewPointer(named), iface) {
fmt.Fprintf(&rel, "%s <|.. %s\n", it.Obj().Name(), n)
}
}
}
b.WriteString("}\n")
b.WriteString(rel.String())
b.WriteString("@enduml\n")
return b.String()
}
// relate turns a field type into a UML relationship line.
func relate(w *strings.Builder, owner string, t types.Type, pkg *types.Package) {
mult := "1"
if s, ok := t.(*types.Slice); ok {
t, mult = s.Elem(), "0..*"
}
ptr := false
if p, ok := t.(*types.Pointer); ok {
t, ptr = p.Elem(), true
}
named, ok := t.(*types.Named)
if !ok || named.Obj().Pkg() != pkg {
return
}
target := named.Obj().Name()
switch {
case types.IsInterface(named) || ptr:
fmt.Fprintf(w, "%s --> \"%s\" %s\n", owner, mult, target)
default:
fmt.Fprintf(w, "%s *-- \"%s\" %s\n", owner, mult, target)
}
}Run on the checkout package it prints Orders <|.. MemoryOrders, Order *-- "0..*" OrderLine and Service --> "1" PaymentGateway: the arrows of the hand-drawn diagram, derived from code. Behaviour cannot be derived the same way, so the state machine is protected by a test that parses its PlantUML source and compares it with the transition table:
package checkout
import (
"regexp"
"strings"
"testing"
)
// stateDiagram is the PlantUML source of the Order state machine (top level
// only). The test fails when code and diagram drift apart, in either direction.
const stateDiagram = `
@startuml
[*] --> Pending
Pending --> Reserved : stockReserved
Pending --> Canceled : cancel
Reserved --> Paid : paymentCaptured
Reserved --> Canceled : paymentDeclined
Paid --> Shipped : dispatched
Shipped --> [*]
Canceled --> [*]
@enduml
`
var edge = regexp.MustCompile(`^(\w+) --> (\w+) : (\w+)$`)
func TestCodeMatchesStateDiagram(t *testing.T) {
drawn := map[string]bool{}
for _, line := range strings.Split(stateDiagram, "\n") {
if m := edge.FindStringSubmatch(strings.TrimSpace(line)); m != nil {
drawn[strings.ToLower(m[1])+"-"+m[3]+"-"+strings.ToLower(m[2])] = true
}
}
coded := map[string]bool{}
for from, out := range transitions {
for ev, to := range out {
coded[string(from)+"-"+string(ev)+"-"+string(to)] = true
}
}
for k := range drawn {
if !coded[k] {
t.Errorf("drawn but not coded: %s", k)
}
}
for k := range coded {
if !drawn[k] {
t.Errorf("coded but not drawn: %s", k)
}
}
}
func TestGuardBlocksEmptyOrder(t *testing.T) {
o := NewOrder("o-1", "c-1")
if err := o.Fire(StockReserved); err == nil {
t.Fatal("guard [lines not empty] did not hold")
}
}The demo command prints its own execution as PlantUML sequence lines, so you can render what the code actually did and compare it with the designed diagram:
// Command demo runs PlaceOrder against in-memory adapters and prints every
// message as a PlantUML sequence line, so the trace IS a sequence diagram.
//
// go run ./cmd/demo # happy path
// go run ./cmd/demo -decline # alt [declined] operand
package main
import (
"context"
"errors"
"flag"
"fmt"
"academy/uml-diagrams/checkout"
)
type trace struct{}
func (trace) msg(from, to, arrow, text string) { fmt.Printf("%s %s %s : %s\n", from, arrow, to, text) }
type inventory struct{ t trace }
func (i inventory) Reserve(_ context.Context, id string, lines []checkout.OrderLine) error {
i.t.msg("Service", "Inventory", "->", fmt.Sprintf("reserve(%s, %d lines)", id, len(lines)))
i.t.msg("Inventory", "Service", "-->", "ok")
return nil
}
func (i inventory) Release(_ context.Context, id string) error {
i.t.msg("Service", "Inventory", "->", "release("+id+")")
return nil
}
type payments struct {
t trace
decline bool
}
func (p payments) Charge(_ context.Context, id string, m checkout.Money) (string, error) {
p.t.msg("Service", "PSP", "->", fmt.Sprintf("charge(%s, %d %s)", id, m.Cents, m.Currency))
if p.decline {
p.t.msg("PSP", "Service", "-->", "declined")
return "", errors.New("card declined")
}
p.t.msg("PSP", "Service", "-->", "pay_123")
return "pay_123", nil
}
type orders struct{ t trace }
func (r orders) Save(_ context.Context, o *checkout.Order) error {
r.t.msg("Service", "OrderRepo", "->", "save(status="+string(o.Status)+")")
return nil
}
type bus struct{ t trace }
func (b bus) Publish(_ context.Context, topic string, _ any) error {
b.t.msg("Service", "Broker", "->>", "publish "+topic)
return nil
}
func main() {
decline := flag.Bool("decline", false, "make the PSP decline the card")
flag.Parse()
t := trace{}
svc := &checkout.Service{Orders: orders{t}, Inventory: inventory{t}, Payments: payments{t, *decline}, Events: bus{t}}
fmt.Println("@startuml")
t.msg("Client", "Service", "->", "placeOrder(o-1)")
o, err := svc.PlaceOrder(context.Background(), "o-1", "c-7", []checkout.Item{
{SKU: "BOOK-1", Qty: 2, Price: checkout.Money{Cents: 1500, Currency: "EUR"}},
{SKU: "PEN-9", Qty: 1, Price: checkout.Money{Cents: 300, Currency: "EUR"}},
})
if err != nil {
t.msg("Service", "Client", "-->", "error: "+err.Error())
} else {
t.msg("Service", "Client", "-->", "201 "+string(o.Status))
}
fmt.Println("@enduml")
}Laravel
Example: the same checkout
The state machine as a backed enum; each case is a state and allowedTransitions() lists the outgoing arrows.
<?php
namespace App\Enums;
/**
* The Order state machine diagram as a backed enum.
* Each case is a state; allowedTransitions() is the set of outgoing arrows.
*/
enum OrderStatus: string
{
case Pending = 'pending';
case Reserved = 'reserved';
case Paid = 'paid';
case Shipped = 'shipped';
case Canceled = 'canceled';
/** @return list<self> */
public function allowedTransitions(): array
{
return match ($this) {
self::Pending => [self::Reserved, self::Canceled],
self::Reserved => [self::Paid, self::Canceled],
self::Paid => [self::Shipped],
self::Shipped, self::Canceled => [], // final states
};
}
public function canTransitionTo(self $next): bool
{
return in_array($next, $this->allowedTransitions(), true);
}
}The Eloquent model: hasMany and belongsTo are the associations, the casts() entry links the attribute to the enumeration, and transitionTo() refuses any arrow that is not on the diagram.
<?php
namespace App\Models;
use App\Enums\OrderStatus;
use DomainException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* Class diagram: Order "1" *-- "1..*" OrderLine, Order "0..*" --> "1" Customer.
* The composition is enforced by the foreign key ON DELETE CASCADE,
* not by Eloquent: hasMany() alone is only an association with multiplicity.
*/
class Order extends Model
{
protected $fillable = ['customer_id', 'status'];
protected function casts(): array
{
return ['status' => OrderStatus::class];
}
public function lines(): HasMany
{
return $this->hasMany(OrderLine::class);
}
public function customer(): BelongsTo
{
return $this->belongsTo(Customer::class);
}
/** Derived attribute /total in cents. */
public function total(): int
{
return (int) $this->lines->sum(fn (OrderLine $l) => $l->qty * $l->unit_price_cents);
}
/** One transition of the state machine; illegal arrows throw. */
public function transitionTo(OrderStatus $next): void
{
if (! $this->status->canTransitionTo($next)) {
throw new DomainException("Illegal transition {$this->status->value} -> {$next->value}");
}
$this->status = $next;
$this->save();
}
}The sequence diagram as an Action. The interfaces at the top are the sockets of the component diagram; a service provider binds them to adapters.
<?php
namespace App\Checkout;
use App\Enums\OrderStatus;
use App\Events\OrderPaid;
use App\Models\Order;
use Illuminate\Support\Facades\DB;
/** Required interfaces (sockets on the component diagram). */
interface PaymentGateway
{
/** @throws PaymentDeclined */
public function charge(int $orderId, int $amountCents): string;
}
interface Inventory
{
/** @param array<int, array{sku: string, qty: int}> $lines */
public function reserve(int $orderId, array $lines): void;
public function release(int $orderId): void;
}
final class PaymentDeclined extends \RuntimeException {}
/**
* The checkout sequence diagram as an Action: one method per lifeline message.
*/
final class PlaceOrder
{
public function __construct(
private readonly Inventory $inventory,
private readonly PaymentGateway $payments,
) {}
/** @param array<int, array{sku: string, qty: int, unit_price_cents: int}> $items */
public function handle(int $customerId, array $items): Order
{
// «create» message: the order and its lines appear in one transaction
$order = DB::transaction(function () use ($customerId, $items) {
$order = Order::create(['customer_id' => $customerId, 'status' => OrderStatus::Pending]);
$order->lines()->createMany($items);
return $order;
});
// 1: synchronous call
$this->inventory->reserve($order->id, $order->lines->map->only('sku', 'qty')->all());
$order->transitionTo(OrderStatus::Reserved);
// 2: alt [captured] / [declined]
try {
$this->payments->charge($order->id, $order->total());
} catch (PaymentDeclined $e) {
$this->inventory->release($order->id); // compensation
$order->transitionTo(OrderStatus::Canceled);
throw $e;
}
$order->transitionTo(OrderStatus::Paid);
// 3: asynchronous message (open arrow head); listeners may be queued
OrderPaid::dispatch($order);
return $order;
}
}The Laravel angle
Eloquent relationships declare return types (HasMany, BelongsTo, BelongsToMany), which makes reverse engineering cheap: reflection finds relationship methods without running a query, and getRelated() names the other class. This Artisan command prints a Mermaid class diagram you can paste into a pull request:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\Relation;
use ReflectionClass;
use ReflectionMethod;
use ReflectionNamedType;
/**
* php artisan uml:models > docs/models.mmd
*
* Reads app/Models, finds relationship methods by their declared return
* type, and prints a Mermaid classDiagram. Relationships become plain
* associations with multiplicities: Eloquent cannot tell aggregation from
* composition; only the foreign key's ON DELETE rule can.
*/
final class UmlModels extends Command
{
protected $signature = 'uml:models';
protected $description = 'Print a Mermaid class diagram of the Eloquent models';
/** Relation class => [multiplicity at this end, multiplicity at the other end] */
private const MULTIPLICITY = [
HasMany::class => ['"1"', '"0..*"'],
HasOne::class => ['"1"', '"0..1"'],
BelongsTo::class => ['"0..*"', '"1"'],
BelongsToMany::class => ['"0..*"', '"0..*"'],
];
public function handle(): int
{
$this->line('classDiagram');
foreach (glob(app_path('Models/*.php')) as $file) {
$class = 'App\\Models\\'.basename($file, '.php');
$ref = new ReflectionClass($class);
if (! $ref->isSubclassOf(Model::class) || $ref->isAbstract()) {
continue;
}
$this->line(' class '.$ref->getShortName());
foreach ($ref->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
$this->relationLine($ref, $method);
}
}
return self::SUCCESS;
}
private function relationLine(ReflectionClass $ref, ReflectionMethod $method): void
{
$type = $method->getReturnType();
if ($method->class !== $ref->getName()
|| $method->getNumberOfRequiredParameters() > 0
|| ! $type instanceof ReflectionNamedType
|| ! is_subclass_of($type->getName(), Relation::class)) {
return;
}
$kind = $type->getName();
[$here, $there] = self::MULTIPLICITY[$kind] ?? ['', ''];
// Building a relation object does not run a query; it only needs the related model.
$related = $ref->newInstance()->{$method->getName()}()->getRelated();
$arrow = $kind === BelongsTo::class ? '-->' : '--';
$this->line(sprintf(
' %s %s %s %s %s : %s',
$ref->getShortName(), $here, $arrow, $there, class_basename($related), $method->getName(),
));
}
}What it cannot see is just as instructive: aggregation versus composition lives in the migration (foreignId('order_id')->constrained()->cascadeOnDelete()), not in the model; association classes are pivots declared with withPivot('active', 'created_by') or ->using(CustomPivot::class); traits have no UML element. Draw those by hand, and keep the generated part generated.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Diagrams rot after one sprint | Generate structure, test behaviour | umlgen, uml:models, the state-machine drift test | Wrong diagrams fail CI | Only works for what code can express |
| Diagram shows everything, says nothing | One question per diagram | Hide members, show 5–9 boxes, name the file after the question | Readable in a review | More, smaller files |
| Arguments about arrows | Agree on the six lines and three rules | Composition = lifecycle; dependency = temporary; aggregation = avoid | Shorter reviews | Some precision lost on purpose |
| Wrong diagram for the question | Use the choosing table | Ordering question → sequence; legality question → state | Answers the real question | Needs a little UML literacy |
| Go code "has no classes" | Map types, method sets and packages | Go mapping table | Honest diagrams of Go | Realization arrows must be computed |
| Architecture diagrams mix levels | C4 zoom levels for structure, UML for behaviour | UML and C4 | Each picture has one audience | Two notations to know |
| Images in the repo nobody can edit | Text sources, rendered on demand | PlantUML/Mermaid in Markdown | Diffable, reviewable | Auto-layout is sometimes ugly |
The worked system: checkout end to end
One system, six views, all describing the same code. Read them in this order when you join the team.
| View | Question | Figure | Code |
|---|---|---|---|
| Class | What is an order made of? | Below | checkout/order.go, Order.php |
| Sequence | What happens on "Place order"? | Sequence | service.go, PlaceOrder.php |
| State machine | Which status changes are legal? | State machine | transitions map, OrderStatus enum |
| Activity | Who does what, what runs in parallel? | Activity | Workflow / saga orchestration |
| Component | Which parts plug into which interfaces? | Component | ports.go, service provider bindings |
| Deployment | What runs where? | Deployment | Container images, k8s manifests |
The class diagram also decides the schema. Each notation choice becomes a concrete database rule:
-- Composition (filled diamond): lines die with their order.
-- Qualified association Order[lineNo] -> 0..1 OrderLine: composite unique key.
-- {qty > 0}: a CHECK constraint. «enumeration» OrderStatus: a CHECK list.
CREATE TABLE orders (
id BIGSERIAL PRIMARY KEY,
customer_id BIGINT NOT NULL REFERENCES customers(id), -- association 0..* -> 1
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending','reserved','paid','shipped','canceled'))
);
CREATE TABLE order_lines (
order_id BIGINT NOT NULL REFERENCES orders(id) ON DELETE CASCADE, -- composition
line_no INT NOT NULL, -- qualifier
sku TEXT NOT NULL REFERENCES products(sku), -- association -> 1 Product
qty INT NOT NULL CHECK (qty > 0), -- constraint {qty > 0}
unit_price_cents BIGINT NOT NULL,
PRIMARY KEY (order_id, line_no)
);
-- Association class (Student, Course) -> Enrollment: a join table with its own columns.
CREATE TABLE enrollments (
student_id BIGINT NOT NULL REFERENCES students(id),
course_id BIGINT NOT NULL REFERENCES courses(id),
grade TEXT,
enrolled_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (student_id, course_id)
);
-- Generalization Payment <|-- CardPayment, WalletPayment: single table with a type column
-- (or one table per subclass; UML does not decide this, your queries do).
CREATE TABLE payments (
id BIGSERIAL PRIMARY KEY,
order_id BIGINT NOT NULL REFERENCES orders(id),
kind TEXT NOT NULL CHECK (kind IN ('card','wallet')),
amount_cents BIGINT NOT NULL,
last4 TEXT,
provider TEXT
);This maps the same way on PostgreSQL, MySQL with InnoDB (the MySQL manual: "As of MySQL 8.0.16, CREATE TABLE permits the core features of table and column CHECK constraints, for all storage engines"), SQL Server and Oracle; SQLite enforces foreign keys only after PRAGMA foreign_keys = ON. Document stores such as MongoDB express composition by embedding the lines in the order document, and association by storing an id.
UML and the C4 model
The C4 model is "an easy to learn, developer friendly approach to software architecture diagramming" built on "A set of hierarchical abstractions - software systems, containers, components, and code." Its creator, Simon Brown, is direct about scope: "you don’t need to use all 4 levels of diagram; only those that add value - the system context and container diagrams are sufficient for most software development teams."
| C4 level | Shows | Audience (C4 site) | Closest UML | Prefer which? |
|---|---|---|---|---|
| System context | People and systems around yours | "Everybody, both technical and non-technical people" | Use case (actors + boundary) | C4 |
| Container | Applications and data stores, technologies, protocols | Architects, developers, operations | Component + deployment | C4 |
| Component | Components inside one container | Architects, developers | Component | Either; generate if long-lived |
| Code | Classes inside one component | Developers | Class | UML class diagram, generated by an IDE |
| Supporting: dynamic | Numbered interactions | Developers | Communication / sequence | UML sequence |
| Supporting: deployment | Mapping containers to infrastructure | Operations | Deployment | Either |
| (none) | States of one entity | Developers, product | State machine | UML (C4 has nothing) |
"Unfortunately, UML usage seems to be in decline, and many teams have reverted to using ad hoc boxes and lines diagrams once again." — C4 model FAQ, c4model.com
The practical split: C4 for the static architecture map, UML for behaviour and for code-level structure. C4's own FAQ recommends supplementing with UML state and timing diagrams, and says that to document "a library, framework or SDK, you might be better off using something like UML." Mermaid supports C4 (C4Context, C4Container, C4Component, C4Dynamic, C4Deployment), and "Mermaid's C4 diagram syntax is compatible with plantUML."
C4Context
title Shop, system context
Person(customer, "Customer", "Buys products")
System(shop, "Shop", "Catalogue, checkout, orders")
System_Ext(stripe, "Stripe", "Card payments")
System_Ext(mail, "E-mail provider")
Rel(customer, shop, "Places orders", "HTTPS")
Rel(shop, stripe, "Charges cards", "HTTPS")
Rel(shop, mail, "Sends confirmations", "SMTP")Choosing the diagram
| Situation / question | Recommendation | Extra technique | Reason |
|---|---|---|---|
| "Who calls whom, in what order?" | Sequence | One diagram per scenario; alt for the failure path | Order is the vertical axis |
| "Is this status change allowed?" | State machine | Drift test against the code's transition table | The missing arrows are the rules |
| "What is this domain made of?" | Class (5–9 boxes) | Object diagram for one tricky example | Multiplicity and lifecycle are explicit |
| "Which modules may import which?" | Package | Architecture tests; Go internal/ | Arrows become enforceable rules |
| "Where are the seams for testing/swapping?" | Component with ball and socket | Fakes for every required interface | Shows ports and adapters |
| "What runs where?" | Deployment, one per environment | Label protocols and ports | Incidents happen on the lines |
| "What is the whole system and who uses it?" | C4 context + container | Keep it on one page | Non-technical readers |
| "Who does what across teams, with parallel steps?" | Activity with swimlanes | Fork/join for parallel work | Concurrency and ownership visible |
| "What are the user goals?" | Use case text (+ one diagram) | Stories with acceptance criteria | The diagram alone says little |
| Timeouts and durations | Timing (PlantUML) or state machine with after() | Time is the axis | |
| Explaining a design in a PR | Mermaid fenced block | Renders on GitHub | Zero tooling for reviewers |
| Regulated blueprint | Full UML tool, XMI export | Model reviews | Completeness is the requirement |
In architecture: from a single process to a distributed system
UML scales by changing which diagram carries the weight: inside one process the class and state diagrams matter most; across processes the sequence and deployment diagrams do.
Monolith: one process, one database
How it shows up: a class diagram of the domain, a state machine per lifecycle entity, a sequence diagram per important use case. Everything is a method call, so sequence diagrams are mostly synchronous arrows.
Simplest correct usage: keep docs/diagrams/ with three files per bounded area (<area>-class.puml, <area>-states.puml, <area>-<usecase>.puml) and generate the class diagram where possible.
Example (simple): a blog: Post *-- Comment, Post --> Author, state machine Draft → Published → Archived.
Example (complex): the checkout on this page in one Laravel app: PlaceOrder Action, OrderStatus enum, Eloquent models; the activity diagram's fork becomes Bus::batch([...])->then(...).
Modular monolith and multiple databases
How it shows up: the package diagram becomes the most important picture: one package per module, arrows only through published interfaces, and a component diagram for each module's provided and required interfaces. Each module owns its tables; the class diagram stops at the module boundary and refers to other modules' entities by id only (an association to an id type, not to the class).
Module boundary rule UML expression
1 checkout may call payments checkout ..> payments «use» (package diagram)
2 only through PaymentGateway socket on Checkout, lollipop on Payments (component)
3 checkout stores customer_id, not Customer attribute customerId : CustomerId, no association line
4 payments must not import checkout no arrow; an architecture test fails if one appearsMicroservices: sequence and deployment carry the weight
What survives: component diagrams (now each component is a service), state machines (each service's entities), class diagrams inside each service. What changes: sequence diagrams gain asynchronous arrows, par fragments and failure operands, because every arrow can now fail independently (Distribution of Components). Draw the network as part of the design, not as an implementation detail.
Checkout saga (choreography) as a sequence
1 checkout-svc ->> broker : OrderPlaced (async, open head; via outbox)
2 broker ->> inventory-svc : OrderPlaced
3 inventory-svc ->> broker : StockReserved
4 broker ->> payment-svc : StockReserved
5 alt [declined] payment-svc ->> broker : PaymentFailed ; inventory-svc releases stock
6 every lifeline is a service; every arrow needs a timeout, retry rule and idempotency keyExample: the outbox makes arrow 1 reliable; the saga page draws the compensation path. A C4 container diagram replaces the old component diagram as the overview; UML sequence diagrams document each saga.
Distributed data: replicas, caches and regions
Where diagrams break: a sequence diagram with one :Database lifeline hides the primary/replica split, the cache in front, and the region boundary. Draw them as separate lifelines; that is where the bugs live.
Read-your-writes bug, drawn honestly
1 Client -> api : POST /orders -> api -> primary : INSERT (commit)
2 Client -> api : GET /orders/42 -> api -> replica : SELECT (replica lag 300 ms)
3 replica --> api : not found -> api --> Client : 404 for an order that exists
4 fix drawn: alt [read after own write within 1 s] api -> primary ; else api -> replicaA deployment diagram with regions, replicas and cache nodes, labelled with replication mode (synchronous or asynchronous) and failover direction, belongs in every incident runbook. The database side of this is on Replication & Failover; in Redis-backed caches, draw the cache as its own lifeline with the TTL on the arrow.
Scaling path: 1×, 10×, 100×
| Scale | Structure | Diagram practice |
|---|---|---|
| 1× (one team, one app) | Monolith | Class + state + a few sequence diagrams, as Mermaid in Markdown |
| 10× (several teams, one repo) | Modular monolith | Package and component diagrams enforced by tests; generated class diagrams per module |
| 100× (many teams, many services) | Services, regions | C4 context/container per system, UML sequence per cross-service flow, deployment per environment, state machines per aggregate |
Lab: generate, render and test diagrams
Everything runs offline with Go installed.
Setup.
cd docs/snippets/design/uml-diagrams/go
go vet ./... && go test ./...
# ok academy/uml-diagrams/checkoutStep 1: generate the class diagram from code.
go run ./cmd/umlgen ./checkout > /tmp/checkout.puml
grep -E '<\|\.\.|\*--|-->' /tmp/checkout.puml
# Item *-- "1" Money
# Orders <|.. MemoryOrders
# Order *-- "0..*" OrderLine
# Order *-- "1" Status
# OrderLine *-- "1" Money
# Service --> "1" Orders
# Service --> "1" Inventory
# Service --> "1" PaymentGateway
# Service --> "1" PublisherCompare with the hand-drawn checkout class diagram. Expected differences: the generator draws Status as composition (it is a value field) where the hand drawing shows an association to an enumeration, and it cannot know the qualifier. Note also ~mu and ~byID on MemoryOrders: unexported means package visibility.
Step 2: render it. Paste /tmp/checkout.puml into any PlantUML renderer (IDE plug-in or PlantUML server). As an exercise, add a -mermaid flag to umlgen that prints a classDiagram instead (the header, the package wrapper and the interface syntax all change), and paste its output into a GitHub comment.
Step 3: record the actual sequence.
go run ./cmd/demo
# @startuml
# Client -> Service : placeOrder(o-1)
# Service -> Inventory : reserve(o-1, 2 lines)
# Inventory --> Service : ok
# Service -> PSP : charge(o-1, 3300 EUR)
# PSP --> Service : pay_123
# Service -> OrderRepo : save(status=paid)
# Service ->> Broker : publish order.paid
# Service --> Client : 201 paid
# @enduml
go run ./cmd/demo -decline
# ... PSP --> Service : declined
# Service -> Inventory : release(o-1)
# Service -> OrderRepo : save(status=canceled)
# Service --> Client : error: charge: card declinedThe two runs are the two operands of the alt fragment. Render both and lay them next to the designed sequence diagram.
Step 4: make the diagram fail the build. In checkout/order.go add Paid: {Dispatch: Shipped, Cancel: Canceled} to the transition table and run go test ./checkout. Expected: coded but not drawn: paid-cancel-canceled. Either draw the arrow (and decide who refunds) or remove the code.
Step 5: break the guard. Remove the len(o.Lines) == 0 check from Fire. Expected: TestGuardBlocksEmptyOrder fails with "guard [lines not empty] did not hold".
Step 6 (Laravel, optional). Register UmlModels in a Laravel 13 app with Order, OrderLine and Customer models and run php artisan uml:models. Expected output starts with classDiagram and contains Order "1" -- "0..*" OrderLine : lines and Order "0..*" --> "1" Customer : customer; paste it into a PR description and GitHub renders it.
Common misconceptions
| Belief | Reality |
|---|---|
| UML is a process | It is a notation; processes (RUP, agile) are separate |
| A diagram must be complete | A diagram is a view; omitted means "not shown", not "absent" |
| Hollow diamond = has-a, filled = strong has-a | Every association is has-a; only composition has defined lifecycle semantics |
| Arrows on associations mean data flow | They mean navigability (who can reach whom) |
| Go embedding is inheritance | It is composition with promoted methods; no subtyping |
| Interfaces in Go are drawn like Java's | Realization is implicit and must be computed from method sets |
| Use case diagrams capture requirements | The text scenarios do; the diagram is a table of contents |
| A sequence diagram documents the algorithm | It documents one trace; branch-heavy diagrams belong in code |
| A status column is a state machine | Only if illegal transitions are rejected somewhere |
| C4 replaced UML | C4 covers static architecture; behaviour still needs UML |
| Mermaid renders all UML | Class, sequence and state natively; others are approximations |
| Diagrams always rot | Generated diagrams and diagram tests do not |
| Communication and sequence diagrams carry different information | Same interaction, different layout |
Cheat sheet
| Topic | Remember |
|---|---|
| Families | 7 structure, 7 behaviour (4 of them interaction) |
| Daily seven | Class, package, component, deployment, activity, state machine, sequence |
| Visibility | + public, - private, # protected, ~ package (Go unexported) |
| Multiplicity | 1, 0..1, *, 1..*; not shown ≠ one |
| Six lines | Association, aggregation (hollow ◇), composition (filled ◆), dependency (dashed →), generalization (△), realization (dashed △) |
| Composition | Part in at most one whole; deleted with it → ON DELETE CASCADE |
| Association class | Link with data → join table / pivot with columns |
| Sequence arrows | Filled = sync, open = async, dashed = reply/create, X = destroy |
| Fragments | alt, opt, loop, par, break, critical, ref |
| Transition label | event [guard] / effect |
| History | H shallow (top substate), H* deep (full configuration) |
| Component | Lollipop = provided, socket = required |
| Modes | Sketch (selective), blueprint (complete), programming language (generated) |
| C4 | Context and container for everyone; UML for behaviour and code |
| Diagrams as code | Text in repo, render in CI, generate structure, test behaviour |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Name the two diagram families and two diagrams of each. Must-know
Answer
Answer: Structure (class, object, package, component, composite structure, deployment, profile) and behaviour (use case, activity, state machine, plus interaction diagrams: sequence, communication, interaction overview, timing). See The 14 diagrams.
2 — What exactly does a filled diamond promise that a hollow one does not? Important
Answer
Answer: A part belongs to at most one composite at a time, and when the composite is deleted its parts are deleted with it. Shared aggregation's semantics "varies by application area and modeler". See Class diagram.
3 — Which visibility symbol should a Go unexported field get, and why? Must-know
Answer
Answer: ~ (package), because Go hides identifiers per package, not per type; any code in the same package can use it. See Reading Go.
4 — How do you draw "Order line has quantity and price at time of sale, linking Order and Product" in UML and in SQL? Important
Answer
Answer: An association class OrderLine attached by a dashed line to the Order–Product association; in SQL a join table with its own columns (in Laravel a pivot with withPivot or a custom pivot model). See association class and the schema.
5 — In a sequence diagram, how do you tell a synchronous call from an asynchronous one? Must-know
Answer
Answer: Synchronous: solid line with a filled arrowhead (and usually a reply). Asynchronous: solid line with an open arrowhead. Replies are dashed. See Sequence diagram.
6 — What is the difference between alt and opt? Must-know
Answer
Answer: alt chooses at most one of several guarded operands; opt has one operand that either happens or not, equivalent to an alt with an empty second operand.
7 — Read this transition label: paymentDeclined [attempts < 3] / scheduleRetry(). Important
Answer
Answer: Trigger paymentDeclined, guard attempts < 3, effect scheduleRetry(): when the event arrives and the guard is true, the effect runs and the state changes. See State machine.
8 — A composite state is left via hold and re-entered via H*. What state is the machine in after resume? Good to know
Answer
Answer: Deep history restores the full configuration of the last visit: in every orthogonal region, the same nested substate as before hold (e.g. InTransit and Invoiced). Shallow history H would restore only the top-level substates and enter them by their defaults.
9 — Why is the use case diagram considered weak, and what do you use instead? Important
Answer
Answer: It shows names of goals but no order, data or failure paths. Use the use case text (main scenario and extensions), user stories with acceptance criteria, and sequence diagrams for the flows. See Use case.
10 — When would you choose a C4 container diagram over a UML deployment diagram, and when the other way round? Important
Answer
Answer: C4 container for the system overview (applications, data stores, technologies) for a broad audience; UML/C4 deployment for one environment's nodes, replicas and network paths, for operations and incident work. See UML and C4.
11 — How can a hand-written state diagram be kept from rotting? Important
Answer
Answer: Keep it as text in the repository and add a test that parses the diagram's transitions and compares them with the code's transition table in both directions. See the Lab, step 4.
Glossary
| Term | Meaning |
|---|---|
| UML | Unified Modeling Language, OMG standard; current version 2.5.1 (formal/2017-12-05) |
| OMG | Object Management Group, the standards body that owns UML, OCL, XMI, SysML |
| Booch, OMT, OOSE | The three methods UML unified (Booch; Rumbaugh's Object Modeling Technique; Jacobson's Object-Oriented Software Engineering) |
| Model vs diagram | The model holds elements; a diagram is one graphical view of part of it |
| Structure diagram | Shows elements "irrespective of time": class, object, package, component, composite structure, deployment, profile |
| Behavior diagram | Shows dynamic behaviour: use case, activity, state machine, interaction diagrams |
| Interaction diagram | Sequence, communication, interaction overview, timing |
| Frame / heading | Optional border with sd, stm, act, cmp, dep, pkg, uc + name |
| Classifier | Abstract metaclass for things with features: class, interface, component, use case… |
| Visibility | + public, - private, # protected, ~ package |
| Multiplicity | Allowed number of values or linked objects, lower..upper |
Derived (/) | Computed from other values, e.g. /total |
| Association | Structural relationship between classifiers; ends have multiplicity and navigability |
| Navigability | Open arrowhead on an association end: you can reach that end efficiently |
| Aggregation (shared) | Hollow diamond; whole–part with unspecified semantics |
| Composition (composite) | Filled diamond; part in at most one whole, deleted with it |
| Dependency | Dashed arrow; client uses supplier; keywords «use», «create», «import» |
| Generalization | Hollow triangle; subtype relationship |
| Realization / interface realization | Dashed line with hollow triangle; implements a specification |
| Association class | An association that is also a class with its own attributes |
| Qualifier / qualified association | Key on an association end that partitions the linked set |
| Abstract class | Cannot be instantiated; name in italics or {abstract} |
| Interface | «interface»: set of operations a classifier promises to provide |
| Enumeration | «enumeration»: data type with a fixed set of literals |
| Stereotype / keyword / profile | Guillemet tags extending (stereotype, via a profile) or built into (keyword) UML |
| Constraint | Rule in braces, e.g. {qty > 0}, {ordered} |
| OCL | Object Constraint Language (OMG, v2.4): invariants, pre- and postconditions |
| Instance specification | An object on an object diagram: name : Type underlined, with slots |
| Package / «import» / «access» / «merge» | Namespace; public import; private import; package merge |
| Component | Modular, replaceable unit with provided and required interfaces |
| Provided / required interface | Lollipop (ball) / socket; ball-in-socket = assembly connector |
| Port | Named interaction point on a classifier's boundary |
| Composite structure | Parts, ports and connectors inside one classifier |
| Node / device / execution environment | Computational resource on a deployment diagram (3D box) |
| Artifact / «manifest» / communication path | Physical deliverable (binary, image, file); artifact embodies a component; link between nodes |
| Actor / use case / «include» / «extend» | External role; user goal; mandatory reuse; conditional extension at an extension point |
| Action / control flow / object flow / object node | Activity step; ordering edge; edge carrying data; data holder such as o : Order [paid] |
| Initial / activity final / flow final | Start dot; bullseye ending the whole activity; circled X ending one flow |
| Fork / join / decision / merge | Split into concurrent flows / wait for all / choose by guard / rejoin without waiting |
| Activity partition (swimlane) | Group of nodes with a common owner or location |
| State / composite state / region / orthogonal state | Condition of an object; state with substates; container of substates; state with several concurrent regions |
| Transition / trigger / guard / effect | Arrow between states; event; Boolean condition in [ ]; behaviour after / |
| entry / do / exit | Behaviours run on entering, while in, and on leaving a state |
| Pseudostate | Initial, choice, junction, fork, join, entry/exit point, terminate, history |
Shallow / deep history (H, H*) | Re-enter last top-level substate / full last configuration |
| Time event / change event | after(15 min) / when(condition) |
| Lifeline | Participant in an interaction (vertical dashed line) |
| Execution specification (activation) | Thin rectangle on a lifeline while it is executing |
| Synchronous / asynchronous / reply message | Filled head / open head / dashed line |
| Create / destroy (destruction occurrence) | Dashed open-headed message to a new lifeline; X ending a lifeline |
| Lost / found message | Known send, no receive / known receive, no known send |
| Gate | Message end on the boundary of an interaction or fragment |
| Combined fragment / interaction operator | Box with alt, opt, loop, par, break, critical, neg, assert, seq, strict, ignore, consider |
Interaction use (ref) | Reference to another interaction |
| Communication diagram | Interaction drawn on links with numbered messages (UML 1: collaboration diagram) |
| Interaction overview / timing diagram | Activity of interactions / states on a time axis |
| Sketch / blueprint / programming language | Fowler's three modes of using UML |
| Forward / reverse / round-trip engineering | Diagram → code / code → diagram / both kept in sync |
| MDA | Model Driven Architecture, OMG's approach to generating code from models |
| XMI / UML DI | XML interchange format for models / diagram interchange metamodel (Annex B) |
| PlantUML | Text-to-diagram tool covering most UML diagrams (@startuml … @enduml) |
| Mermaid | Markdown-inspired text-to-diagram tool rendered by GitHub; class, sequence, state, flowchart, C4 |
| Diagrams as code | Keeping diagram sources as text in the repository, rendered on demand |
| C4 model | Simon Brown's context, container, component and code diagrams (+ landscape, dynamic, deployment) |
| Structural typing / implicit interface satisfaction | Go: a type implements an interface by having its methods, without declaring it |
| Struct embedding | Go composition that promotes the embedded type's methods; not subtyping |
| Eloquent relationship | Laravel hasOne, hasMany, belongsTo, belongsToMany, morph*: associations with multiplicity |
Pivot / withPivot | Laravel's association class for many-to-many |
| ISO/IEC 19501 / 19505 | ISO publications of UML 1.4.x (2005) and UML 2 (2012) |
References
- Object Management Group, OMG Unified Modeling Language (OMG UML) Version 2.5.1, formal/2017-12-05, December 2017. PDF; specification page; all versions. Clauses used: 1 (Scope), 6.1, 7.7.4, 9.2.4, 9.5.3–9.5.4, 9.8.3, 10.4.4, 11.5, 11.6 (Components), 12.3 (Stereotypes), 14.2 (State machines), 15 (Activities), 17 (Interactions), 18 (Use cases), 19 (Deployments), Annexes A and B.
- Object Management Group, Object Constraint Language 2.4. omg.org/spec/OCL
- Martin Fowler, UML Distilled (3rd ed., 2003), book page; bliki: UmlMode, UmlAsSketch, UmlAsBlueprint, UmlAsProgrammingLanguage, UseCasesAndStories
- PlantUML documentation: class, sequence, state, activity, component, deployment, use case, object, timing
- Mermaid documentation: class diagram, sequence diagram, state diagram, flowchart, C4
- GitHub Docs, Creating diagrams
- Simon Brown, The C4 model: home, diagrams, abstractions, system context, container, component, code, FAQ
- The Go Authors, Frequently Asked Questions (object orientation, implements declarations); The Go Programming Language Specification (interface types); go/ast
- GoPlantUML, README
- Laravel 13: Eloquent: Relationships, Eloquent, Migrations, Queues
- MySQL 8.0 Reference Manual, CHECK Constraints; SQLite, Foreign Key Support
- Wikipedia, Unified Modeling Language (secondary source for the 1994–2005 dates and ISO numbers)