drumlin
drumlin turns a small text format into UML diagrams that look drafted by hand: aligned boxes, even spacing, orthogonal lines and restrained lettering. You write what the diagram contains; drumlin decides where everything goes and writes an SVG file.
It draws five kinds of diagram: component, package, sequence, state and activity. Here is a component diagram, with the source that produced it:
diagram component "Order Platform"
direction right
package "Edge" {
component "Web Gateway" as gateway {
requires IOrders
requires IIdentity
}
}
component "Order Service" as orders {
port api provides IOrders
port events requires IEventBus
component "API Handler" as handler { requires IPricing }
component "Pricing Engine" as pricing { provides IPricing }
component "Outbox" as outbox
api --> handler
handler --> outbox : persist
outbox --> events
}
component "Identity" as identity <<external>> { provides IIdentity }
package "Infrastructure" as infra {
component "Event Bus" as bus { provides IEventBus }
component "Postgres" as db <<database>>
align bus db
}
component "Billing" as billing {
requires IEventBus
provides IInvoices
}
orders ..> db : SQL
note outbox: Publishes at least once. Consumers deduplicate on event id.
Every diagram in this book is rendered from the source shown with it, while the book is built (see
Rendering at docs build time). In the diagram above you never draw the dashed
arrows between the interfaces: a component that requires IOrders is wired to one that
provides IOrders by name. See Interface.
Why drumlin
- One small binary. It is written in Rust and needs no JVM, browser or Graphviz.
- A readable format. One statement per line, in the spirit of PlantUML, with one regular grammar.
- No layout work. You state structure. Layout hints adjust the arrangement when you need to, and never take coordinates.
- Deterministic output. The same input gives byte-identical SVG, so diagrams diff cleanly in review.
- Precise errors. Each error has a line, a column and, where possible, a suggested fix.
Get started
Build drumlin from source with a Rust toolchain, write a three-line file and render it: Getting started takes about five minutes.
Finding your way
The book has four main parts. Each answers a different question:
| Part | Answers | Use it when |
|---|---|---|
| Guide | How do I start? | You are new, or you want the file header, styles or agent instructions. |
| Diagrams | How do I write a whole diagram of this kind? | You are drawing. One how-to page and one page of examples per kind. |
| Elements | What does this one symbol look like, and what is its syntax? | You are looking something up. One page per symbol, with its UML clause. |
| Reference | What exactly is allowed? | You need the grammar, the command line, an error message, a layout hint or a term. |
Two further parts explain how drumlin works. Drawing principles states the rules a good drawing follows, with their sources. Internals describes the layout pipeline, the documentation build and the roadmap.
Status
drumlin is a prototype, at version 0.2.0. The input format, the command line and the drawings may still change. The symbols follow UML 2.5.1. Which elements each diagram kind accepts, and how a drawing looks, are drumlin’s own choices: see UML conformance. Known limitations are listed on the roadmap.
Getting started
This page takes you from nothing to a rendered SVG in about five minutes. You need a Rust toolchain
(cargo); drumlin has no other dependencies.
Install
Install the published crate from crates.io:
cargo install drumlin
This puts drumlin into Cargo’s binary folder (usually ~/.cargo/bin, which must be on your PATH).
If you only want to use drumlin (without checking out the source), continue at Your first diagram.
Build from source
To work on drumlin, or to run a version that is not released yet, get the source and build it:
git clone https://github.com/davidpettersson/drumlin.git
cd drumlin
cargo build --release
The binary is target/release/drumlin. To run it as drumlin from anywhere, install it into
Cargo’s binary folder (usually ~/.cargo/bin, which must be on your PATH):
cargo install --path . --locked
The commands below assume drumlin is on your PATH. Otherwise, write target/release/drumlin
instead.
Your first diagram
Create a file hello.uml:
diagram component "Hello"
component Client { requires IGreeting }
component Server { provides IGreeting }
Render it:
drumlin render hello.uml -o hello.svg
Open hello.svg in a browser to see the drawing above. Both components name IGreeting, so drumlin
wires the socket on Client to the lollipop on Server with a dashed dependency arrow. You did not draw
that line. (Between two ports with one interface each, drumlin draws a
joined ball-and-socket instead. See Interface.)
Check a file
drumlin check reads a file and reports the first error, without writing anything. It exits with 0
when the file is valid, so it suits scripts, editors and coding agents.
drumlin check hello.uml
A mistake is reported with its line and column, and a suggestion where drumlin has one. If you add a
fifth line, Client --> Sever, drumlin says:
hello.uml:5:12: error: unknown element `Sever`; did you mean `Server`?
Errors lists the common ones.
Grow the diagram
Add a package and an ordinary connector, -->, with a label after ::
diagram component "Hello, again"
package "Backend" {
component Server { provides IGreeting }
component Store <<database>>
Server --> Store : read
}
component Client { requires IGreeting }
Choose a style
Drawings use the pens style unless you ask for another. Two more styles exist: plain, with one line
weight, and lettering, with hand-lettered text. Try one from the command line:
drumlin render hello.uml -o hello.svg --style lettering
See Styles for pictures of each.
Component, package and state diagrams can also take a different layout engine with --layout. The
default suits nearly every diagram; File basics explains when to try the
other.
Where next
- File basics: the header, direction, layout engine and comments.
- A how-to page for the kind you want to draw: component, package, sequence, state or activity.
- The component examples, to see what larger diagrams look like.
- The command line reference, for every option.
File basics
This page covers what every drumlin file shares: the header, the drawing direction, the layout engine, the style and comments. Read it after Getting started. The statements of each diagram kind are on its page under Diagrams.
A file may begin with a header line that names the diagram kind and a title, and a few statements that set up the drawing:
diagram component "Title"
direction right
layout longest-path
style pens
All four lines are optional:
diagram <kind> ["Title"]names the diagram kind:component,package,sequence,stateoractivity. A file without it is a component diagram. The title is drawn as a caption above the diagram.directionsets which way the diagram flows (below).layoutpicks a layout engine.stylepicks how the drawing is inked: see Styles.
direction, layout and style may stand on any line, and the last one wins. Put them under the
header, where a reader expects them.
Direction
direction right places dependencies left to right. It is the default for component diagrams, and suits
most of them, because labels read naturally on horizontal lines.
diagram component "direction right"
direction right
component A
component B
component C
A --> B
B --> C
direction down places dependencies top to bottom. It is the default for package and state diagrams,
and suits pipelines and layers.
diagram component "direction down"
direction down
component A
component B
component C
A --> B
B --> C
Sequence and activity diagrams always run top to bottom and take no direction.
Layout engine
A layout engine decides where the boxes of a component, package or state diagram go. Routing, labels and drawing are the same for every engine, so you can compare two engines on one file. There are two:
longest-path, the default. Each box goes one rank after the furthest box that points to it, and a box that nothing points to moves down next to what it points to.network-simplexranks the boxes so that the lines are as short as possible in total (network simplex, after Gansner and others, 1993). A box with one line in from high up and several lines out to boxes far below moves down next to them.
For nearly every small diagram the two draw the same:
diagram state "layout longest-path"
layout longest-path
[*] --> Idle
Idle --> Running
Running --> Stopping
Stopping --> [*]
Try network-simplex when a box sits far above the boxes it points to and its lines run long. Here
Flags points to Orders and Billing at the bottom. Longest path puts it under Web, so both its
lines run the height of the drawing:
diagram component "Checkout, longest-path"
direction down
layout longest-path
component Web
component Gateway
component Cart
component Pricing
component Orders
component Billing
component Flags
Web --> Gateway
Gateway --> Cart
Cart --> Pricing
Pricing --> Orders
Pricing --> Billing
Web ..> Flags
Flags ..> Orders
Flags ..> Billing
Network simplex moves Flags down beside Pricing, which makes one line longer and two shorter:
diagram component "Checkout, network-simplex"
direction down
layout network-simplex
component Web
component Gateway
component Cart
component Pricing
component Orders
component Billing
component Flags
Web --> Gateway
Gateway --> Cart
Cart --> Pricing
Pricing --> Orders
Pricing --> Billing
Web ..> Flags
Flags ..> Orders
Flags ..> Billing
To choose an engine from the command line, use drumlin render --layout <engine> or
drumlin check --layout <engine>. The option wins over the file’s layout statement. An unknown name
is an error that lists the engines. Sequence and activity diagrams have layouts of their own, so they
reject both the statement and the option.
An element may still be called layout: layout --> parser is a connector, and only layout followed
by a name is the statement. How the engines work is in
How layout works.
Style
style <name> picks how the drawing is inked: pens (the default), plain or lettering. It applies
to every diagram kind, and --style <name> on the command line wins over it. Styles shows
each one.
Comments
# and // start a comment that runs to the end of the line.
Names and quoting
A name without spaces needs no quotes. A bare name may contain letters, digits, _, and single - or
. between them. Any other name is written in double quotes, and can be given a short alias with as
for use in the rest of the file:
component "Order Service" as orders
Styles
A style decides how a drawing is inked: line weights, corners and lettering. This page shows the three styles and how to choose one. You can skip it until you want a different look.
| Style | Look |
|---|---|
pens (default) | Three pen weights in one warm black, text in bold, regular and a softer grey |
plain | One ink, one line width, one text weight; only font sizes differ |
lettering | The pens of pens, with all text lettered in single pen strokes |
Choose a style with a style <name> statement in the file, or with --style <name> on the command
line, which wins over the statement:
drumlin render station.uml -o station.svg --style plain
Styles apply to all five diagram kinds. Like direction and layout, the statement may stand on any
line, and the last one wins. An unknown name is an error that lists the styles. An element may still
be called style: only style followed by a name is the statement.
pens
pens is the default; every diagram in this book that names no style uses it. It inks with three pen
weights in one warm black (#22201c): a heavy pen for boxes that hold other boxes, a medium pen for
ordinary boxes, symbols and solid lines, and a fine pen for dashed lines, notes and small details. Bends
are sharp. Names are bold; keywords such as «service» are a step smaller in a warm grey, as are notes,
so the names stand out. Draw with three pens says which pen draws
what.
diagram component "style pens"
style pens
component "Weather Station" as station {
component Sensors
component Logger
Sensors --> Logger : samples
}
component Forecast <<service>> { provides IForecast }
component Display { requires IForecast }
component Archive <<database>>
Logger --> Forecast : readings
Logger ..> Archive : nightly
note Logger: Keeps 30 days of readings.
plain
plain is as plain as a drawing gets: one black ink, one line width for every outline and line, and
regular text throughout, with only the font size changing between names and small text. Bends are
sharp. Compare the same diagram above in pens.
diagram component "style plain"
style plain
component "Weather Station" as station {
component Sensors
component Logger
Sensors --> Logger : samples
}
component Forecast <<service>> { provides IForecast }
component Display { requires IForecast }
component Archive <<database>>
Logger --> Forecast : readings
Logger ..> Archive : nightly
note Logger: Keeps 30 days of readings.
lettering
lettering keeps the pens of pens and letters every piece of text in single pen strokes, as a
draftsman letters a drawing with a lettering guide: names and the title in spaced capitals, labels and
notes in upright mixed case, and a pen for each size: heaviest for the title, finest for keywords. See
Letter with a pen per size.
diagram component "style lettering"
style lettering
component "Weather Station" as station {
component Sensors
component Logger
Sensors --> Logger : every 10 s
}
component Forecast <<service>> { provides IForecast }
component Display { requires IForecast }
component Archive <<database>>
Logger --> Forecast : readings
Logger ..> Archive : nightly
note Logger: Keeps 30 days of readings, 1 per 10 s.
Things to know about lettering:
- The letters are drawn as paths, not set as text, so a browser cannot select them or find them with
search. Each run of text keeps its words as an accessible name (
aria-label) for screen readers. - The lettering covers ASCII, Latin-1, much of Latin Extended-A, common punctuation, arrows and super- and subscript digits. Any other character is drawn as an open box.
- Files are about three to four times the size of the same drawing in
pens. - The glyphs are drumlin’s lettering, derived from Routed Gothic by Darren Embry and licensed under the SIL Open Font License 1.1.
What a style changes
pens and plain change only the strokes and the colour of the marks: every box, line and label stays
where the layout put it. lettering sizes boxes, labels and notes for its own letters, so its drawing
may be laid out a little differently.
Working with agents
This page is for people who let a coding agent write drumlin files, and for the agent itself. It gives the loop to follow, an instruction to paste, and the rules an agent most often needs.
drumlin suits coding agents, because the text is the design and the picture is for the humans reviewing it:
- One regular grammar. Each statement fits on one line, and nothing depends on visual layout in the source.
- No layout work. An agent states structure. drumlin places every box.
- Deterministic output. Regenerating an unchanged model changes no bytes.
- Errors an agent can act on.
drumlin checkreports a line, a column and a likely fix.
A typical loop
The agent writes the model, drumlin check reports errors until the file is clean, and
drumlin render produces the SVG a person reviews:
Suggested instruction for an agent
Describe architecture in drumlin (.uml) files. Start each file with
`diagram <kind> "Title"`, where kind is component, package, sequence, state
or activity. In component diagrams, declare components with `provides` and
`requires`, and let matching interface names wire them; do not draw those
connectors yourself. Run `drumlin check <file>` after each edit and fix every
reported error before rendering. Do not add layout hints unless a reviewer
asks for a specific arrangement.
Rules agents most often miss
- Quote names with spaces, and give them an alias with
asto refer to them:component "Order Service" as orders. - Sequence diagrams: declare every
participantoractorbefore its first message. The declaration order is the left-to-right order. - State diagrams: a transition is written with
-->, and its label has the formtrigger [guard] / effect. A transition leaving a choice or other pseudostate has no trigger. - Activity diagrams: quote any name or guard with spaces (
action "Ship order",if "card valid" { ... }), putstartfirst, and write nothing afterstoporendin the same flow. - Declare both ends of a line. In component and package diagrams each end must be declared somewhere in the file, before or after the line. In state diagrams, naming a state in a transition declares it.
- One error at a time.
checkreports the first error only; fix it and run again.
Where to look things up
- Grammar: every statement of every kind on one page.
- Errors: common messages and the source that causes them.
- The how-to page of each kind under Diagrams, and the examples beside it.
Component diagrams
A component diagram shows a system’s parts, the interfaces they offer and need, and how
they are wired. This page walks through writing one, section by section. It is drumlin’s default
kind: a file with no diagram line is a component diagram. Write the header anyway when you want a
title.
The notation follows UML 2.5.1 clauses 11.2, 11.3 and 11.6. Each symbol has its own page under Elements, the full syntax is in the grammar, and the examples come from real kinds of system.
diagram component "Title"
direction right
The default direction is right, with direction down for layered pictures. See
File basics.
Parts
Declare a component by name. Quote a name with spaces,
and give it a short alias with as. A block nests components, and a <<stereotype>> shows as a
keyword. Group loosely related parts in a package, which is
a folder around them.
diagram component "Parts and grouping"
package "Platform" {
component "Request Router" as router <<service>> {
component Parser
component Dispatcher
Parser --> Dispatcher
}
component "Orders DB" as db <<database>>
router --> db
}
Connecting parts
A connector joins two elements. --> is a solid
connector with an open arrow and ..> is a dashed dependency. Text after : becomes the label.
diagram component "Connectors"
component Producer
component Consumer
component Metrics
Producer --> Consumer : batches
Producer ..> Metrics : reports
Interfaces
Inside a component, provides and requires declare
interfaces. You name them and drumlin draws them. When one
component requires an interface and another provides one of the same name, drumlin wires them. What
it draws depends on where the two ends are declared, as UML requires:
| Ends | What is drawn |
|---|---|
| Two simple ports (one interface each) | Ball-and-socket: the ball seated in the socket |
| A port with several interfaces at either end | A plain connector named after the interface |
| Anything else (a component with no port at one end) | Socket and lollipop kept apart, joined by a dashed dependency arrow |
An interface with no partner stays a stub on the boundary: a lollipop if it is provided, a socket if it is required.
diagram component "Matched by name, no ports"
component Client { requires IOrders }
component Server { provides IOrders, IHealth }
Ports and delegation
A port is a named point on a component’s boundary, drawn as a small square. A connector from a composite’s port to a part inside it is a delegation: the port forwards to the part. Two ports with one interface each, matched by name, form a ball-and-socket.
diagram component "Ports"
component Gateway {
port uplink requires IEvents
}
component Bus as bus {
port in provides IEvents
component Queue
in --> Queue
}
Notes and layout hints
note target: text attaches a note. Layout hints
such as left-of and align adjust the arrangement and never set coordinates.
diagram component "Notes and hints"
component Cache
component Store
Cache --> Store : writes through
note Cache: Entries expire after 30 seconds.
Next: the component examples, or look up any symbol under Elements of component diagrams.
Component diagram examples
Twenty-three component diagrams from systems software, embedded work, compilers and tools, services and data platforms, grouped by domain. Each model is illustrative. Use them as starting points: copy the source and change it. For the notation, see Component diagrams and the component elements.
Systems software
Monolithic kernel
diagram component "Kernel subsystems"
direction down
component "System Call Interface" as sci
package "Core" as core {
component "Process Scheduler" as sched
component "Memory Manager" as mm
sched --> mm : page faults
}
package "I/O" as io {
component VFS
component "Network Stack" as net
component "Block Layer" as block
VFS --> block
}
component "Device Drivers" as drivers
sci --> sched
sci --> VFS
sci --> net
block --> drivers
net --> drivers
Storage engine
diagram component "LSM storage engine"
direction right
component Client { requires IKeyValue }
component Engine as engine {
port kv provides IKeyValue
component "Write Path" as write
component "Read Path" as read
component Memtable
component "Write-Ahead Log" as wal
component Compactor
kv --> write
kv --> read
write --> wal : append
write --> Memtable : insert
read --> Memtable : probe
}
component "Block Cache" as cache { provides ICache }
component "SSTable Files" as sst <<filesystem>>
engine ..> cache : uses
engine --> sst : flush, read
note wal: Replayed on startup before the engine accepts writes.
Hypervisor
diagram component "Type 1 hypervisor"
direction down
package "Guests" as guests {
component "Linux Guest" as linux { requires IVirtio }
component "RTOS Guest" as rtos { requires IVirtio }
}
component "Virtual Devices" as vdev {
provides IVirtio
requires IDriver
}
package "Hypervisor" as hv {
component "vCPU Scheduler" as vcpu
component "Stage-2 MMU" as mmu
vcpu --> mmu
}
component "Hardware Drivers" as drv { provides IDriver }
guests ..> hv : traps
Container runtime
diagram component "Container runtime"
direction right
component CLI { requires IRuntimeApi }
component Daemon {
provides IRuntimeApi
requires IOci
requires IImages
}
component "Image Store" as images { provides IImages }
component Shim {
provides IOci
requires ISyscalls
}
component "Linux Kernel" as kernel <<platform>> { provides ISyscalls }
note Shim: Outlives the daemon so that containers survive restarts.
Embedded
Motor controller firmware
diagram component "Motor controller firmware"
direction right
package "Application" as app {
component "Speed Loop" as speed
component "Fault Monitor" as fault
fault --> speed : limits
}
package "Drivers" as drivers {
component PWM { provides IPwm }
component ADC { provides IAdc }
component CAN { provides ICan }
}
component "Control Task" as control {
requires IPwm
requires IAdc
}
component Telemetry { requires ICan }
speed --> control : setpoint
note control: Runs at 20 kHz in interrupt context.
Sensor node
diagram component "Battery sensor node"
direction down
component "Sampling Task" as sampler {
requires II2c
provides ISamples
}
component "I2C Driver" as i2c { provides II2c }
component "Radio Task" as radio {
requires ISamples
requires IRadio
}
component "LoRa Driver" as lora { provides IRadio }
component "Power Manager" as power
power ..> sampler : wake
power ..> radio : wake
RTOS layers
diagram component "RTOS layers"
direction down
package "Middleware" as mid {
component "File System" as fs
component "TCP/IP" as tcp
}
package "Kernel" as kernel {
component Tasks
component Queues
component Timers
Tasks --> Queues
Tasks --> Timers
}
component HAL <<port layer>>
fs --> Tasks
tcp --> Tasks
Queues --> HAL
Timers --> HAL
Bootloader
diagram component "Secure boot chain"
direction right
component "ROM" as rom <<immutable>>
component "First Stage" as fsbl
component "Verifier" as verify { provides IVerify }
component "Second Stage" as ssbl { requires IVerify }
component "Kernel Image" as image
rom --> fsbl : verifies
fsbl --> ssbl : loads
ssbl --> image : verifies, starts
note rom: Holds the root public key hash.
Vehicle gateway
diagram component "Vehicle gateway"
direction right
component "Powertrain ECU" as ptrain { port can requires IFrames }
component "Body ECU" as body { port can requires IFrames }
component Gateway {
port bus provides IFrames
port uplink requires IEthernet
component Router
component Firewall
bus --> Firewall
Firewall --> Router
Router --> uplink
}
component "Telematics Unit" as tcu { provides IEthernet }
Compilers and tools
Compiler pipeline
diagram component "Compiler pipeline"
direction down
component Driver { requires ITokens }
package "Front End" as front {
component Lexer { provides ITokens }
component Parser
component "Type Checker" as sema
Lexer --> Parser : tokens
Parser --> sema : AST
}
package "Back End" as back {
component "IR Builder" as ir
component Optimizer
component "Code Generator" as codegen { provides ITarget }
ir --> Optimizer
Optimizer --> codegen : SSA
}
sema --> ir : typed AST
Driver ..> codegen : invoke
Language server
diagram component "Language server"
direction right
component Editor { requires ILsp }
component Server as server {
port lsp provides ILsp
component Dispatcher
component "Incremental Parser" as parser
component "Symbol Index" as index
component Diagnostics
lsp --> Dispatcher
Dispatcher --> parser : didChange
parser --> index : update
parser --> Diagnostics : errors
}
component "File Watcher" as watcher
watcher --> server : changes
Build system
diagram component "Build system"
direction right
component "Build Files" as files <<input>>
component "Graph Builder" as graph
component Scheduler { requires IExecutor, ICache }
component "Local Executor" as local { provides IExecutor }
component "Content Cache" as cache { provides ICache }
files --> graph : parse
graph --> Scheduler : actions
note cache: Keyed by a hash of each action's inputs.
Debugger
diagram component "Debugger"
direction right
component "Debug UI" as ui { requires IDebug }
component Engine {
provides IDebug
requires ISymbols
requires ITarget
}
component "DWARF Reader" as dwarf { provides ISymbols }
component "ptrace Backend" as ptrace { provides ITarget }
This site’s toolchain
diagram component "Documentation build"
direction right
component "Markdown Chapters" as md <<input>>
component mdBook { requires IPreprocessor }
component "mdbook-drumlin" as pre {
provides IPreprocessor
requires IRender
}
component "drumlin library" as lib { provides IRender }
component "Static Site" as site <<output>>
md --> mdBook
mdBook --> site : HTML with inline SVG
Distributed services
Hexagonal service
diagram component "Hexagonal service"
direction right
component "HTTP Adapter" as http { requires IUseCases }
component Core as core {
port api provides IUseCases
port repo requires IRepository
port publish requires IEvents
component "Use Cases" as cases
component "Domain Model" as model
api --> cases
cases --> model
cases --> repo
cases --> publish
}
component "SQL Adapter" as sql { provides IRepository }
component "Kafka Adapter" as kafka { provides IEvents }
Consensus group
diagram component "Replicated state machine"
direction right
component Client { requires IPropose }
component Replica as replica {
port propose provides IPropose
port peers requires IRaftRpc
component "Consensus Module" as raft
component Log
component "State Machine" as sm
propose --> raft
raft --> Log : append
Log --> sm : apply committed
raft --> peers
}
component "Peer Replicas" as others { provides IRaftRpc }
Cache-aside
diagram component "Cache-aside read"
direction right
component Service
component Redis <<cache>>
component Postgres <<database>>
Service --> Redis : 1. get
Service --> Postgres : 2. on miss
Service ..> Redis : 3. set, ttl 60s
API gateway
diagram component "API gateway"
direction right
component "Mobile App" as mobile { requires IPublicApi }
component "Web App" as web { requires IPublicApi }
component Gateway {
provides IPublicApi
requires IAuth
requires ICatalog
requires ICheckout
}
package "Services" as services {
component Auth { provides IAuth }
component Catalog { provides ICatalog }
component Checkout { provides ICheckout }
}
Event-driven checkout
diagram component "Event-driven checkout"
direction right
component Checkout { requires IBus }
component "Message Bus" as bus { provides IBus }
component Payments
component Inventory
component Shipping
bus --> Payments : OrderPlaced
bus --> Inventory : OrderPlaced
Payments --> Shipping : PaymentCaptured
Inventory --> Shipping : StockReserved
note bus: Delivery is at least once. Handlers are idempotent.
Data platforms
ETL pipeline
diagram component "Nightly ETL"
direction right
component "Source Databases" as src <<database>>
component Extract
component Transform
component Load
component Warehouse <<database>>
component "Data Quality" as dq
src --> Extract
Extract --> Transform : parquet
Transform --> Load
Load --> Warehouse
Transform ..> dq : assertions
Stream processor
diagram component "Stream processor"
direction right
component Producers { requires ILog }
component "Partitioned Log" as log {
provides ILog
provides ISubscribe
}
component Job as job {
port source requires ISubscribe
component Windowing
component Aggregator
component Sink
source --> Windowing
Windowing --> Aggregator
Aggregator --> Sink
}
component "State Backend" as state <<rocksdb>>
job ..> state : checkpoints
Query engine
diagram component "Query engine"
direction down
component "SQL Parser" as parser
component Planner { requires ICatalog }
component Catalog { provides ICatalog }
component Optimizer
component Executor
component "Storage Layer" as storage
parser --> Planner : AST
Planner --> Optimizer : logical plan
Optimizer --> Executor : physical plan
Executor --> storage : scans
ML serving
diagram component "Model serving"
direction right
component Client { requires IPredict }
package "Serving" as serving {
component Router { provides IPredict }
component "Model A" as a
component "Model B" as b
Router --> a : 95%
Router --> b : 5%
}
component "Feature Store" as features <<database>>
component "Metrics Sink" as metrics
serving ..> features : lookup
serving ..> metrics : latency
Package diagrams
A package diagram shows how a system is grouped into packages and how those packages depend on each
other. This page walks through writing one. Start a file with diagram package.
The notation follows UML 2.5.1 clause 12. Each symbol has its own page under Elements, the full syntax is in the grammar, and there is a page of examples.
diagram package "Title"
direction down
The default direction is down, which suits layered dependencies. direction right
is also available. Both lines are optional except for diagram package, because a
file with no header is a component diagram.
Packages
A package is drawn as a folder. When it shows its contents its name sits in the tab, and when it does not its name sits in the body, as UML 2.5.1 specifies.
diagram package "Names in the tab, or in the body"
package Empty
package Types {
class Integer
class Time
}
Packages nest to any depth, and a <<stereotype>> becomes a keyword above the name.
diagram package "Nesting and keywords"
package "Platform" as pf <<model>> {
package "Kernel" as kernel {
class Scheduler
class Timer
}
package Drivers
Drivers ..> kernel : <<access>>
}
package Empty
Empty left-of pf
Classifiers
class, interface and enum declare classifiers: simple
name boxes. An interface carries the
«interface» keyword and an enumeration the «enumeration» keyword. A declared
stereotype joins that keyword list, except <<abstract>>, which sets the name in italics.
class Order
interface Repository <<abstract>>
enum Status
Relations
A relation is a line between two packages or classifiers. The arrow you type chooses its kind:
| Arrow | Meaning | Drawn as |
|---|---|---|
a ..> b | Dependency | Dashed line, open head |
a --> b | Directed association | Solid line, open head |
a -- b, a .. b | Plain line | Solid or dashed, no head |
a --|> b | Generalization | Solid line, hollow triangle |
a ..|> b | Realization | Dashed line, hollow triangle |
a +-- b | Containment | Solid line, circle-plus on a |
Reversed forms such as <.., <--, <|--, <|.. and --+ swap the two ends.
A <<x>> in a label becomes «x», which is how «import», «access» and «merge»
are written. Any other label text is kept as it is.
diagram package "Relations"
package App
package Lib
package Util
package Base
App ..> Lib : <<import>>
App ..> Util : <<access>>
Lib ..> Base : <<merge>>
Util ..> Base : uses
diagram package "Classifiers"
direction right
interface Shape <<abstract>>
class Circle
class Square
class Base
enum Kind
Circle ..|> Shape
Square ..|> Shape
Circle --|> Base
Base --> Kind : tags
Containment
owner +-- member draws UML’s containment connector, with the circle-plus on the
owner. Use it for members declared outside the owner’s block. Members in the next
rank share one trunk.
diagram package "Containment"
package Types
class Shape
class Point
class Color
Types +-- Shape
Types +-- Point
Types +-- Color
diagram package "Containment, left to right"
direction right
package "api" as api
package "core" as core
class Router
class Handler
core +-- Router
core +-- Handler
api ..> core : <<import>>
A dependency may run between an element and the package drawn around it, for example
a nested package importing its parent. The line runs to the inside of the package
boundary. Containment with +-- needs no line when the member is already drawn inside
the owner, so that is an error.
diagram package "Nested import"
package Core {
package Scheduler
Scheduler ..> Core : <<import>>
}
diagram package "Containment"
package Types { class Shape }
Types +-- Shape
drumlin says:
3:1: error: `Shape` is drawn inside `Types`, so containment needs no line; declare `Shape` outside the `Types` block
Notes and layout hints
Notes and layout hints work as they do in
component diagrams. A note attaches to a package or a classifier and sits next to it, inside the same
container. left-of, right-of, above, below and align set relative order.
diagram package "Notes and hints"
package Core {
package Parser
package Checker
package Emitter
package Runtime
package Stdlib
Parser left-of Checker
}
class Tool
Tool ..> Core : <<import>>
note Tool: Built separately.
Siblings with no relations between them are folded into a compact block, unless a hint names them.
diagram package "Unconnected members fold into rows"
package Kernel {
class Scheduler
class Timer
class Mutex
class Channel
class Pipe
class Signal
}
Statements on one line
A semicolon separates statements, which suits small packages.
package "Core" as core { class Foo; interface IBar; enum Mode; package inner { } }
Next: the package examples, or look up any symbol under Elements of package diagrams.
Package diagram examples
Five package diagrams of common software structures. For the notation, see Package diagrams and the package elements.
Layered architecture
A note marks the rule for the domain layer: it depends on nothing else.
diagram package "Layered architecture"
package "Presentation" as ui {
package Web
package Mobile
}
package "Application" as app {
package Commands
package Queries
}
package "Domain" as domain {
class Order
class Customer
interface Repository
enum Status
Order --> Customer
Order ..> Status
}
package "Infrastructure" as infra {
package Persistence
package Messaging
}
ui ..> app : <<import>>
app ..> domain : <<import>>
infra ..> domain : <<access>>
note domain: Depends on nothing else. Keep it free of framework types.
Library dependency graph
Left-to-right flow fits a dependency graph with labelled imports.
diagram package "Library dependency graph"
direction right
package app
package "http-client" as http
package "json" as json
package "tls" as tls
package "logging" as log
package "platform" as plat
app ..> http : <<import>>
app ..> json : <<import>>
app ..> log : <<import>>
http ..> tls : <<access>>
http ..> log
json ..> plat
tls ..> plat
log ..> plat
Package merge
Dashed arrows with the «merge» keyword point from the receiving package to the merged one.
diagram package "Package merge"
package P { class A; class B }
package Q { class C }
package R { class D }
package S
package T
R ..> P : <<merge>>
R ..> Q : <<merge>>
S ..> Q : <<merge>>
T ..> R : <<merge>>
T ..> S : <<merge>>
Plugin system
Realizations cross package boundaries. align keeps the interface in reach of the plugins.
diagram package "Plugin system"
package Host {
class Registry
interface Plugin
Registry --> Plugin : loads
align Registry Plugin
}
package "plugins" as plugins <<framework>> {
package Markdown { class MarkdownPlugin }
package Search { class SearchPlugin }
}
MarkdownPlugin ..|> Plugin
SearchPlugin ..|> Plugin
note plugins: Discovered at startup from the plugin directory.
Domain model
Classifiers relate across packages, and the packages show their dependency too.
diagram package "Domain model"
package Ordering {
class Order
class LineItem
enum OrderState
interface Pricing
Order --> LineItem : contains
Order ..> OrderState
Order ..> Pricing
}
package Catalog {
class Product
class Category
Product --> Category
}
LineItem --> Product
Ordering ..> Catalog : <<import>>
Sequence diagrams
A sequence diagram shows the messages exchanged between participants over time, with time running
down the page. This page walks through writing one. Start a file with diagram sequence; the optional
title follows it.
The notation follows UML 2.5.1 clause 17. Each symbol has its own page under Elements, the full syntax is in the grammar, and there is a page of examples.
diagram sequence "Ordering a pizza"
actor "Customer" as c
participant "Web app" as web
participant "Kitchen" as k
c -> web : place(order) {
web ->> k : cook(order)
return confirmation
}
Participants
participant declares a lifeline drawn as a box, and actor
declares one drawn as a stick figure. A participant has a name, optionally an alias with as, and optionally a
<<stereotype>>. Participants become columns in declaration order, so the file controls
the left-to-right reading order, and a name must be declared before it is used.
diagram sequence "Heads"
actor "Operator" as op
participant "Controller" as ctl <<service>>
participant Disk
op -> ctl : mount()
ctl ->> Disk : spin up
Messages
The arrow you type selects the kind of message, following UML 2.5.1 clause 17.4.4.
| Arrow | Message | Line and head |
|---|---|---|
a -> b | synchronous call | solid, filled head |
a ->> b | asynchronous message | solid, open head |
a --> b | reply | dashed, open head |
A message may carry a label after :. Labels wrap when they are long, and the column
spacing grows to fit the widest label between two lifelines. A label that holds a literal
{ should be quoted: : "set { a }".
A message from a lifeline to itself is drawn as a compact loop with its label on the right. A synchronous self-call also opens a short nested execution bar.
diagram sequence "Kinds of message"
participant Client
participant Server
Client -> Server : request()
Server --> Client : response
Client ->> Server : fire and forget
Server -> Server : log the request
Server ->> Server : schedule cleanup
Execution blocks
Follow a message with { to open an execution on the
receiver: a bar that shows the receiver is active. The block closes with
}, and execution bars nest and step to the right as calls go deeper. return sends a
reply from inside a block, to the block’s caller. If return is the last statement of
the block, the bar ends there; otherwise it ends where the block ends. Inside a block,
return takes free text, so it needs no quoting. The block may be written on one line.
diagram sequence "Nested calls"
participant "main()" as m
participant Parser
participant Lexer
m -> Parser : parse(source) {
Parser -> Lexer : next() {
Lexer -> Lexer : skip whitespace
return token
}
Parser -> Parser : build tree
return ast
}
Creating and destroying
A dashed arrow to a head drawn at the moment of creation shows object creation: write
sender -> new "Name" as alias : label, with optional <<stereotype>>. Inside a block
the short form create Name : label is also accepted, and it uses the block’s receiver
as the sender. destroy name ends a lifeline with an X. A participant that has been
destroyed cannot be used afterwards; a destroy in only one alt branch stays open for
the other branches.
diagram sequence "Worker lifetime"
participant Pool
Pool -> new "Worker" as w : spawn()
Pool -> w : run(job) {
return result
}
Pool ->> w : stop
destroy w
Found and lost messages
[-> a is a found message: its sender is outside the diagram, drawn as a filled circle
to the left. a ->] is a lost message, leaving towards a filled circle on the right.
Inside a block opened by a found message, return goes back to the outside.
diagram sequence "Boundaries"
participant Bus
participant Handler
[-> Bus : interrupt
Bus -> Handler : dispatch() {
Handler ->] : retransmit (no ack)
return handled
}
Combined fragments
A combined fragment groups messages under an operator.
alt, opt, loop, break, critical and neg wrap messages in a frame with the
operator in a pentagon at the top left and a [guard] above the first event. else
adds operands to alt, and adds them to par, and each operand is split by a dashed
line. Frames size themselves around their contents and nest. A loop guard written in
parentheses, such as (1,5), joins the operator as loop(1,5), following the
textual syntax of clause 17.6.4.
diagram sequence "Retries and alternatives"
participant Client
participant Server
participant Cache
loop "(1,3)" {
Client -> Server : fetch(key) {
alt "cached" {
Server -> Cache : get(key)
Cache --> Server : value
} else "miss" {
Server -> Server : recompute
opt "worth caching" {
Server ->> Cache : put(key, value)
}
}
return value
}
}
diagram sequence "Parallel and critical regions"
participant "Task A" as a
participant Lock
participant "Task B" as b
par {
a -> Lock : acquire()
} and {
b -> Lock : acquire()
}
critical "mutex held" {
Lock --> a : granted
a -> a : update state
a -> Lock : release()
}
Interaction references and notes
ref over a, b : Name draws an interaction use: a frame with a ref tab that stands
for another interaction.
note over a: text, note left of a: text and note right of a: text add notes with a
folded corner, on their own row. note over a, b: text spans several lifelines.
diagram sequence "Boot"
participant Bootloader as bl
participant Kernel as k
participant Init as i
ref over bl, k : Verify signature
bl -> k : jump(entry)
note over k: Interrupts stay masked until the scheduler starts.
k -> new "PID 1" as p : exec
note right of p: Everything runs under this process.
Layout
Columns are spaced from the content between them: labels, self-message loops, notes and frame contents. Rows follow an 8px grid, and each row grows to fit its label. Message labels sit above their line, in the gap beside the sender when a message crosses other lifelines, so that text never runs over a lifeline or an execution bar.
Heads stay at the top and are not repeated at the bottom. A diagram has no sd frame:
UML Annex A lets the frame and its heading be omitted when the page bounds the drawing,
and a diagram sequence "Title" title is a caption outside the diagram. A found message
starts, and a lost message ends, on a filled circle (17.4.4), and both keep the arrowhead
of their kind: filled for ->, open for ->>.
One detail of reading labels is worth knowing: a label runs to the end of the line, except for a
comment (# or //) and a space-separated { or }. Quote the label to keep those as text.
Next: the sequence examples, or look up any symbol under Elements of sequence diagrams.
Sequence diagram examples
Six sequence diagrams from protocols and systems work. For the notation, see Sequence diagrams and the sequence elements.
TCP connection: handshake, data and teardown
The three-way handshake, a segment and its acknowledgement, and a graceful close. A lost segment leaves through a lost message.
diagram sequence "TCP connection"
participant "Client" as c
participant "Server" as s
note over c, s: Three-way handshake
c ->> s : SYN seq=x
s ->> c : SYN+ACK seq=y, ack=x+1
c ->> s : ACK ack=y+1
note over c, s: Established
c ->> s : data seq=x+1, len=512
s ->> c : ACK ack=x+513
opt "segment lost" {
c ->] : data seq=x+513
c ->> s : retransmit after RTO
}
note over c, s: Graceful close
c ->> s : FIN
s ->> c : ACK
s ->> c : FIN
c ->> s : ACK
note right of c: TIME_WAIT for 2 MSL before the socket is freed.
Raft log replication
The leader appends locally, replicates to followers in parallel and commits once a majority has acknowledged. One follower rejects the entry.
diagram sequence "Raft: replicating one log entry"
actor "Client" as client
participant "Leader" as leader <<raft>>
participant "Follower 1" as f1
participant "Follower 2" as f2
participant "State machine" as sm
client -> leader : command(x) {
leader -> leader : append to log
par {
leader -> f1 : AppendEntries(term, entry) {
f1 -> f1 : append and persist
return success
}
} and {
leader -> f2 : AppendEntries(term, entry) {
alt "log matches prevLogIndex" {
f2 -> f2 : append and persist
return success
} else "prevLogTerm mismatch" {
return reject (conflict index)
note right of f2: Leader walks nextIndex back and retries.
}
}
}
critical "majority acknowledged" {
leader -> leader : advance commitIndex
leader -> sm : apply(x) {
return result
}
}
return result
}
Interrupt handling with a nested IRQ
A device interrupt enters the CPU as a found message, and a higher priority interrupt preempts the handler. The hardware restores context on return from interrupt.
diagram sequence "Nested interrupt handling"
participant "Timer" as timer
participant "CPU core" as cpu
participant "Kernel entry" as entry
participant "UART ISR" as isr
participant "Timer ISR" as tisr
participant "Scheduler" as sched
[-> cpu : UART IRQ {
cpu ->> entry : vector through IDT
entry -> entry : save registers
entry -> isr : uart_isr() {
isr -> isr : read FIFO
timer ->> cpu : timer IRQ
note over cpu, tisr: Higher priority: the ISR is preempted.
cpu -> tisr : timer_isr() {
tisr ->> sched : mark reschedule
return eoi
}
return eoi
}
entry -> entry : check need_resched
opt "reschedule pending" {
entry -> sched : schedule() {
return next task
}
}
entry ->> cpu : iret
return resumes interrupted task
}
TLS 1.3 handshake
The handshake with a ServerHello carrying the key share, and Finished from both sides. Application data flows once the keys are in place. A failed verification ends with an alert.
diagram sequence "TLS 1.3 handshake"
participant "Client" as c
participant "Server" as s
participant "CA store" as ca
c -> s : ClientHello(key_share, sni, supported_versions) {
s -> s : derive handshake secrets
return ServerHello(key_share)
}
note over c, s: Encrypted from here on: EncryptedExtensions, Certificate, CertificateVerify, Finished
s ->> c : EncryptedExtensions
s ->> c : Certificate
s ->> c : CertificateVerify
c -> ca : verify chain(certificate) {
return ok
}
alt "certificate valid" {
s ->> c : Finished
c ->> s : Finished
note over c, s: Application data, protected by traffic keys
c ->> s : HTTP request
s ->> c : HTTP response
} else "verification failed" {
c ->> s : alert(bad_certificate)
c ->] : close connection
}
RPC with retry and exponential backoff
A client retries a call that times out and gives up after three attempts. A circuit breaker records the outcome.
diagram sequence "RPC with retry"
participant "Client stub" as stub
participant "Circuit breaker" as cb
participant "Service" as svc
loop "(1,3)" {
stub -> cb : allow? {
return true
}
stub -> svc : GetOrder(id, deadline=200ms) {
alt "reply before deadline" {
return order
break "success" {
stub ->> cb : record success
}
} else "deadline exceeded" {
stub -> stub : sleep(backoff with jitter)
stub ->> cb : record failure
}
}
}
stub --> stub : surface error to caller
note right of stub: The stub surfaces the last error once retries run out.
Page fault in a demand-paged kernel
A page fault handled through a lookup and swap-in, showing creation and destruction of a transient object.
diagram sequence "Page fault"
participant "MMU" as mmu
participant "Kernel" as k
participant "Swap device" as swap
[-> mmu : translate(vaddr)
mmu -> k : page fault(vaddr) {
k -> new "Fault context" as fc <<per fault>> : allocate
k -> k : find VMA
alt "anonymous page" {
k -> swap : read(slot) {
note right of swap: The request is queued and the task sleeps.
return page
}
k -> k : map page
} else "invalid access" {
k ->] : SIGSEGV to task
}
destroy fc
return retry the access
}
State diagrams
A state machine diagram shows the states something can be in and the transitions between them. This
page walks through writing one. Start a file with diagram state, optionally followed by a title.
The notation follows UML 2.5.1 clause 14. Each symbol has its own page under Elements, the full syntax is in the grammar, and there is a page of examples.
The flow runs down the page by default, so transition labels sit beside vertical lines.
direction right places labels above horizontal lines instead, at the cost of wide gaps between ranks.
The layout reserves room for every label.
diagram state "Door"
[*] --> Closed
Closed --> Opening : open [unlocked] / start motor
Opening --> Open : fully open / stop motor
Open --> Closing : close
Closing --> Closed : fully closed
Closing --> Opening : obstruction / reverse motor
Closed --> Locked : lock
Locked --> Closed : unlock [valid code]
A name used in a transition declares a state in the deepest block that mentions it.
A name that appears only once and is at most two edits from another name is reported
as a typo. To declare such a state on purpose, write state X first.
Use state "Display name" as alias when a state needs a longer name or a body.
Transition labels
A transition label follows : and has the UML form, in which
every part is optional: the trigger is the event that fires the transition, the
guard a condition that must hold, and the effect what happens.
trigger {, trigger} [guard] / effect
A long label breaks before the effect, then wraps. Transitions between the same pair of states run side by side with their labels on the outside. A self-transition is a loop on the side of its state, with its label beside it.
diagram state "Transition labels"
direction right
[*] --> Waiting
Waiting --> Armed : arm, rearm [sensors ready] / log("armed")
Armed --> Waiting : disarm
Armed --> Armed : tick / count()
Armed --> Armed : drift [abs(x) > limit] / correct()
Armed --> Firing : trigger [armed and not locked] / ignite(); start_timer()
Firing --> [*] : done
UML restricts some labels, and drumlin reports a violation as an error:
- A transition from a nested initial pseudostate is unlabeled. At the top level it may name the creating event.
- A transition leaving a pseudostate has no trigger. It may have
[guard] / effect. - The segments into a join and out of a fork have no trigger or guard.
Internal behaviours
Inside a state block, entry, do and exit lines go in a compartment under the name. The
expression after / is optional. Any other line with a / and no arrow is an internal
transition, in the same form as a transition label. Each of these takes a whole line.
diagram state "Password entry"
[*] --> Typing
state Typing {
entry / set echo invisible
exit / set echo normal
character / handle character
help / display help
}
Typing --> [*] : enter
Composite states and history
A state block with vertices inside is a composite state, and its contents form its region.
[*] --> X starts the enclosing region at the initial pseudostate, which sits first in the
flow. X --> [*] ends it at the final state. Each region has one of each, scoped to the block
they are written in.
[H] is shallow history and [H*] is deep history. Written alone or in a transition inside a
block, they belong to that block. Name[H] and Name[H*] reach the history of a composite
state from outside it. A transition may also start at, end at or cross the border of a
composite state.
diagram state "Composite states and history"
[*] --> Off
Off --> Playing : power
state Playing {
entry / spin up
do / stream
exit / spin down
[*] --> Track
Track --> Track : next / advance
Track --> Seeking : seek
Seeking --> Track : found
[H]
}
Playing --> Paused : pause
Paused --> Playing[H] : resume
Playing --> Off : power
Paused --> Off : power
Orthogonal regions
region "name" { ... } divides a state into regions, drawn tiled and separated by dashed
lines. The name is optional. Regions sit across the flow: side by side when flowing down,
stacked when flowing right. A transition cannot join two regions of one state.
diagram state "Elevator controller"
[*] --> Idle
Idle --> Operating : call received / plan route
Operating --> Idle : queue empty
Operating --> Fault : motor overcurrent / cut power
Fault --> Idle : technician reset
state Operating {
entry / release brake
exit / engage brake
region "motion" {
[*] --> Moving
Moving --> Stopping : near target floor
Stopping --> Levelled : speed zero
Levelled --> Moving : next call
}
region "doors" {
[*] --> Closed
Closed --> Opening : levelled at floor
Opening --> Open : fully open
Open --> Closing : door timer
Closing --> Closed : fully closed
Closing --> Opening : obstruction
}
}
Pseudostates
choice c a diamond
junction j a small filled circle
fork f a thick bar across the flow; one line in, at least two out
join j a thick bar across the flow; at least two lines in, one out
terminate t a cross
A pseudostate is declared with a name, and is used like a state. Lines fan out from the corners of a choice or junction. A bar widens over the states it connects.
diagram state "Every pseudostate"
[*] --> Ready
Ready --> c : request
choice c
c --> Worker : [workers free] / assign
c --> Queued : [all busy]
Queued --> j : worker free
Worker --> j : done
junction j
j --> f : / prepare
fork f
f --> A
f --> B
state Tasks {
region "left" {
A --> [*]
}
region "right" {
B --> [*]
}
}
Tasks --> T : fatal
terminate T
Entry and exit points
entrypoint name and exitpoint name, written directly in a state block, place a small
circle or a crossed circle on the state’s border, with its name beside it. Transitions from
outside attach on the outer side and transitions from inside on the inner side.
diagram state "Entry and exit points"
[*] --> Idle
Idle --> again : retry
state Login {
entrypoint again
exitpoint aborted
again --> Prompt
Prompt --> Check : submit
Check --> aborted : [locked out]
Check --> [*] : [ok]
}
aborted --> Idle
Login --> Done
Local transitions
A transition between a composite state and a vertex inside it is a local transition, and is drawn to or from the inside of the state’s border, on its right side.
diagram state "Local transitions"
[*] --> Active
state Active {
[*] --> One
One --> Two : next
Two --> Active : reset
}
Active --> [*]
Notes and hints
note <target>: text attaches a note to any state or pseudostate. The
layout hints left-of, right-of, above, below and align adjust the
layout when the automatic result needs help.
Next: the state examples, or look up any symbol under Elements of state diagrams.
State diagram examples
Six state machines from protocols, devices and resilience patterns. For the notation, see State diagrams and the state elements.
TCP connection
The TCP connection states from RFC 793, with the segment each transition sends.
diagram state "TCP connection"
[*] --> Closed
Closed --> Listen : passive open / create TCB
Closed --> SynSent : active open / send SYN
Listen --> SynRcvd : rcv SYN / send SYN+ACK
SynSent --> Established : rcv SYN+ACK / send ACK
SynRcvd --> Established : rcv ACK
Established --> FinWait1 : close / send FIN
Established --> CloseWait : rcv FIN / send ACK
FinWait1 --> FinWait2 : rcv ACK
FinWait2 --> TimeWait : rcv FIN / send ACK
CloseWait --> LastAck : close / send FIN
LastAck --> Closed : rcv ACK
TimeWait --> Closed : timeout 2MSL
USB device
The device states of the USB specification. Configured carries its internal behaviours in a compartment.
diagram state "USB device"
[*] --> Attached
Attached --> Powered : hub configured
Powered --> Default : bus reset
Default --> Address : set address
Address --> Configured : set configuration [config != 0]
Configured --> Address : set configuration [config == 0]
Configured --> Suspended : bus idle 3 ms
Suspended --> Configured : bus activity
Powered --> Attached : hub deconfigured
Configured --> Default : bus reset
state Configured {
entry / enable endpoints
exit / disable endpoints
SOF / update frame counter
}
Process lifecycle
A Unix-style process. The self-transition is a compact loop, and a note marks the zombie state.
diagram state "Process lifecycle"
[*] --> New
New --> Ready : admitted
Ready --> Running : dispatch
Running --> Ready : preempt [quantum expired]
Running --> Waiting : wait(event) / block()
Waiting --> Ready : event occurs
Running --> Zombie : exit() / release resources
Zombie --> [*] : reaped by parent
Running --> Running : syscall [fast path] / handle inline
note Zombie: Holds only its exit status until the parent calls wait.
Elevator controller
Motion and doors run in orthogonal regions of one composite state.
diagram state "Elevator controller"
[*] --> Idle
Idle --> Operating : call received / plan route
Operating --> Idle : queue empty
Operating --> Fault : motor overcurrent / cut power
Fault --> Idle : technician reset
state Operating {
entry / release brake
exit / engage brake
region "motion" {
[*] --> Moving
Moving --> Stopping : near target floor
Stopping --> Levelled : speed zero
Levelled --> Moving : next call
}
region "doors" {
[*] --> Closed
Closed --> Opening : levelled at floor
Opening --> Open : fully open
Open --> Closing : door timer
Closing --> Closed : fully closed
Closing --> Opening : obstruction
}
}
OTA firmware update
A download with a nested choice, and a junction that fans out after reboot.
diagram state "OTA firmware update"
[*] --> Idle
Idle --> Downloading : update available / open session
state Downloading {
entry / start watchdog
exit / stop watchdog
chunk received / append to flash
[*] --> Fetching
Fetching --> Verifying : last chunk
Verifying --> c1
choice c1
c1 --> [*] : [hash ok]
c1 --> Fetching : [hash bad] / clear buffer
}
Downloading --> Installing
Downloading --> Idle : network lost
Installing --> Rebooting : image written / mark pending
Rebooting --> j1 : boot complete
junction j1
j1 --> Confirmed : [self test passed]
j1 --> RolledBack : [self test failed] / restore slot A
Confirmed --> [*]
RolledBack --> [*]
Circuit breaker
The resilience pattern, with compact self-transitions on Closed and Open.
diagram state "Circuit breaker"
[*] --> Closed
Closed --> Closed : success / reset failure count
Closed --> Open : failures >= threshold / start timer
Open --> Open : call / fail fast
Open --> HalfOpen : timer expired
HalfOpen --> Closed : probe succeeded / reset failure count
HalfOpen --> Open : probe failed / restart timer
state Closed {
do / count failures
}
Activity diagrams
An activity diagram shows the flow of control and data through a behaviour, like a flowchart. This
page walks through writing one. Start with a diagram activity header, then describe the flow from top
to bottom in blocks, much as you would write code. The layout follows the structure you write, so
nothing needs positioning, and activity diagrams take no layout hints.
The notation follows UML 2.5.1 clause 15 and, for signals, clause 16. Each symbol has its own page under Elements, the full syntax is in the grammar, and there is a page of examples.
diagram activity "Title"
Actions and flow
start is the initial node, a filled circle. action is a rounded rectangle. Statements in
order are joined by flows with open arrowheads. stop is the activity final node, a bullseye, and end
is the flow final node, a circled X: stop ends the whole activity, end ends only its own
flow. Quote a name that has several words.
diagram activity "Actions in a flow"
start
action "Validate request"
action Handle
object "Order"
action "Store order"
stop
Object nodes
object draws an object node, a plain rectangle, on the flow. Flows into and out of it are
object flows. Since an initial node only starts control flows, object cannot directly follow start.
Decisions
if "guard" { ... } draws a decision and a merge. Guards go on the outgoing flows, in square
brackets, near the decision. else gives the other branch; the guard defaults to the predefined
[else], and else "guard" changes it. Write else if "guard" { ... } for more branches on the
same decision node. An if with no else gets an empty [else] branch, so a decision always has a way on.
diagram activity "Decisions"
start
action "Parse header"
if "valid" {
action "Route request"
} else "malformed" {
action "Log error"
}
if "cached" {
action "Serve from cache"
}
if "rejected" {
action "Send 403"
stop
}
action "Run handler"
if "2xx" {
action "Cache"
} else if "4xx" {
action "Count"
} else if "5xx" {
action "Alert"
} else {
action "Mystery"
}
stop
One branch always takes the main axis, so the flow passes straight through the decision and the merge
(see Flow passes straight through a decision).
When exactly one branch continues and the others end in stop or end, that branch takes the axis.
A body beside an empty branch sits on the axis, and the empty branch runs around it. Otherwise the
middle branch takes it: the first declared of two, so in if ... else the if body runs straight down
and the else body sits to its right. The other branches keep their declared order left to right and
rejoin the merge from its sides.
switch "subject" { case "a" { ... } ... } is a multi-way decision. The subject is shown as a
«decisionInput» note on the diamond, as Figure 15.33 draws it. The subject is optional.
diagram activity "Multi-way decision"
start
switch "HTTP method" {
case "GET" {
action "Read"
}
case "POST" {
action "Create"
}
case "PUT" {
action "Replace"
}
case "else" {
action "405"
}
}
stop
A branch that reaches stop or end does not rejoin the flow, and no merge is drawn for it. If only one
branch rejoins, no merge is needed at all.
Loops
while "guard" { ... } tests before each pass and repeat { ... } until "guard" after it. Both
use a merge for the return and a decision for the test. The back edge runs along the left side,
and the loop’s exit leaves on the right, so neither crosses the body.
diagram activity "Loops"
start
while "queue not empty" {
action "Pop task"
action "Run task"
}
repeat {
action "Read block"
action "Verify CRC"
} until "CRC ok"
stop
A while has its body on the [guard] flow and leaves on [else]. A repeat leaves on [guard] and returns
on [else].
Concurrency
fork { ... } and { ... } draws a fork bar, branches side by side, and a join bar. Every branch needs at
least one step. A branch ending in end or stop does not reach the join; if only one branch reaches
it, the join is left out, and the flow carries on from that branch.
diagram activity "Concurrent flows"
start
fork {
action "Fetch profile"
} and {
action "Fetch orders"
} and {
action "Fetch feed"
}
action "Compose page"
fork {
action "Audit"
end
} and {
action "Respond"
}
stop
Signals
send draws a send signal action, a convex pentagon. accept draws an accept event action, a concave
pentagon. An accept needs no incoming flow, so it may begin an activity instead of start.
diagram activity "Signals"
start
action "Request payment"
send "PaymentRequested"
accept "PaymentConfirmed"
action "Ship goods"
stop
Partitions
lane "Name" { ... } puts steps in a swimlane, drawn as a labelled band. Lanes appear left to right in the order
they are first named, so you can return to a lane by naming it again, and a lane block
inside a branch moves only that branch. Flows between lanes turn at right angles in the free row above their target.
diagram activity "Swimlanes"
start
lane "Customer" {
action "Place order"
}
lane "Warehouse" {
action "Pick items"
if "in stock" {
action "Ship"
} else {
lane "Customer" {
action "Choose substitute"
}
}
}
stop
In a diagram that uses lanes, every action, signal and object must be inside a lane block. Control
nodes may stand outside one, and then belong to the lane the flow is in. A lane inside a lane is not a
sub-partition: it simply moves the steps inside it to that lane.
A decision stays in its own lane and its branches run to their lanes. A fork or join bar spans the lanes of its branches, meaning it belongs to all of them (a node may be in several partitions). Branches that interleave lanes are placed one above the other, so a flow crossing lanes never runs through a node.
Notes
note: text attaches a note to the statement before it, with a dashed line. A note on a simple step sits beside it.
On a decision, while, repeat or fork, it sits above the opening node. A flow’s first statement cannot have
a note, as there is nothing before it.
diagram activity "Notes"
start
action "Load config"
note: Falls back to defaults when the file is missing.
if "debug" {
action "Enable traces"
}
note: Checked once at startup.
action "Run"
stop
Rules from the specification
drumlin rejects flows that UML forbids and stops problems early:
startmust be first in the flow, because an initial node has no incoming edge.- A flow cannot end on a merge, a join or a loop exit, because those need one outgoing edge. Add a step, or
stoporend. - Statements after
stoporendare unreachable, and it is an error to write them.
split from other tools is not offered: use fork for concurrent flows, or switch for alternatives.
Common mistakes and their messages are in Errors.
Next: the activity examples, or look up any symbol under Elements of activity diagrams.
Activity diagram examples
Five activity diagrams from build, kernel and firmware work. Each is also a golden test, so what you see
is exactly what drumlin produces. For the notation, see Activity diagrams and the
activity elements.
Build and release pipeline
Compile, tests and lint run concurrently. The note attaches to the fork. A release only happens for a tagged
build, so the signing steps sit on the main axis and the empty [else] branch runs around them.
diagram activity "Build and release pipeline"
start
action "Fetch sources"
action "Resolve dependencies"
object "Lockfile"
fork {
action "Compile"
action "Link"
} and {
action "Run unit tests"
} and {
action "Lint and audit"
}
note: Compile, test and lint run concurrently.
action "Package artifacts"
if "tag build" {
action "Sign artifacts"
send "Publish release"
}
action "Notify the team"
stop
Interrupt service with deferred work
The top half is the hard interrupt handler; the bottom half is the deferred work. The handler is started by an accept event rather than an initial node, and hands off with a signal.
diagram activity "Interrupt service with deferred work"
accept "IRQ line raised"
action "Acknowledge at the controller"
action "Read status register"
if "FIFO has data" {
action "Copy bytes to the ring buffer"
send "Wake softirq"
} else "overrun" {
action "Count overrun"
}
action "Return from interrupt"
accept "softirq scheduled"
while "ring buffer not empty" {
action "Pop one packet"
if "checksum valid" {
action "Deliver to the stack"
} else {
action "Drop and count"
}
}
end
Connection retry
A repeat wraps the handshake with backoff, and early failures step aside so that the successful
path stays straight.
diagram activity "Connection retry with backoff"
start
action "Resolve host"
if "resolved" {
repeat {
action "Open socket"
action "TLS handshake"
if "failed" {
action "Wait for backoff"
}
} until "connected or attempts exhausted"
if "connected" {
action "Send greeting"
} else {
action "Report unreachable"
stop
}
} else {
action "Report DNS failure"
stop
}
action "Mark session ready"
stop
Deployment with parallel checks across lanes
The fork spans the lanes running the checks, and the release decision returns to the developer’s lane.
diagram activity "Deployment with parallel checks"
start
lane "Developer" {
action "Merge to main"
}
lane "CI" {
action "Build image"
send "Image ready"
}
lane "Staging" {
accept "Image ready"
action "Deploy to staging"
}
fork {
lane "Staging" {
action "Smoke tests"
}
} and {
lane "Security" {
action "Scan image"
}
} and {
lane "CI" {
action "Contract tests"
}
}
lane "Developer" {
if "all green" {
lane "Production" {
action "Roll out canary"
}
} else {
action "Roll back and file issue"
}
}
stop
Firmware boot
A switch on the boot slot, with «decisionInput» naming what the guards test.
diagram activity "Firmware boot"
start
action "Clock and RAM init"
if "reset cause is brown-out" {
action "Record fault"
}
switch "boot slot" {
case "A" {
action "Verify slot A"
}
case "B" {
action "Verify slot B"
}
case "else" {
action "Enter recovery"
end
}
}
if "signature valid" {
action "Jump to application"
note: The vector table is relocated first.
} else {
action "Enter recovery"
}
stop
Elements of component diagrams
One page per symbol of a component diagram: what it looks like, its syntax and the UML 2.5.1 clause it follows. Use these pages to look something up; to write a whole diagram, start with Component diagrams.
| Element | Syntax |
|---|---|
| Component | component "Name" as a <<stereotype>> { ... } |
| Interface | provides I, requires I |
| Port | port p left provides I |
| Connector | a --> b : label |
| Package | package "Name" { ... } around components |
| Note | note a: text |
diagram component "All the component elements"
component Client { requires IApi }
package "Backend" {
component Service {
port api provides IApi
component Worker
api --> Worker
}
component Database <<database>>
Service ..> Database : queries
}
note Client: Retries on timeout.
See Component diagrams for how to write one, and the grammar for every statement.
Component
A component is a rectangle with the component icon at its top right and its name inside. The simplest needs only a name.
component Scheduler
Names and aliases
A name with spaces needs quotes. Use as to give it a short alias for references.
component "Memory Allocator" as alloc
component "Page Table" as pages
alloc --> pages
Stereotypes
A stereotype goes in << and >>.
component "Orders DB" as db <<database>>
component "Billing API" as api <<external>>
api --> db
Nesting
Components can contain components. The outer one becomes a composite.
component "Network Stack" as net {
component Socket
component TCP
component IP
Socket --> TCP
TCP --> IP
}
Nesting can go several levels deep.
component Kernel {
component "I/O" as io {
component VFS
component Block
VFS --> Block
}
component Memory
io --> Memory
}
One-line blocks
A short body can share the line with its braces.
component Sensor { provides ISample }
component Logger { requires ISample }
Syntax
component <name> [as <alias>] [<<stereotype>>] [{ ... }]
Specification
UML 2.5.1, 11.6.4 (p. 210). A component is a classifier rectangle; showing the icon lets the «component» keyword be hidden, which drumlin does. In a composite the name is centred, with any keyword above it (9.2.4, p. 101).
Used in
Monolithic kernel, Storage engine, Compiler pipeline.
See also
Component diagrams (how to write the whole diagram), Elements of component diagrams, Grammar.
Interface
A provided interface is a lollipop, a small circle on a stem. A required interface is a socket, a
half-circle on a stem. Interfaces are declared inside a component with provides and requires,
and drumlin decides how to draw them.
Assembly
A required and a provided interface with the same name are wired together. With no ports, the socket and the lollipop are joined by a dashed dependency arrow:
component Consumer { requires IQueue }
component Broker { provides IQueue }
Between two simple ports (ports with one interface each), the ball sits in the socket:
component Consumer { port in requires IQueue }
component Broker { port out provides IQueue }
Which notation drumlin uses depends on where the interfaces are declared, following UML 2.5.1, clause 11.2.4. The ball-and-socket is reserved for simple ports. Anything else keeps the socket and the lollipop apart: when an end has no port, they are joined by a dashed dependency arrow from socket to lollipop, as in Figure 11.46. A port with more than one interface is joined with a plain connector named after the interface.
Unconnected interfaces
An interface with no partner is drawn as a stub at the component boundary. A provided interface has a lollipop and a required interface has a socket.
component Codec {
provides IEncode
provides IDecode
requires IAllocator
}
Several interfaces
Separate names with commas.
component Runtime { provides ITimer, IThreads, IFiles }
component App { requires ITimer, IThreads, IFiles }
Several consumers
Each consumer gets its own connection to the provider.
component Logger { provides ILog }
component Net { requires ILog }
component Disk { requires ILog }
component UI { requires ILog }
Inside composites
Matching also works inside a composite and across nesting levels.
component App {
component Controller { requires IRepo }
component Repo { provides IRepo }
}
Syntax
provides <interface> [, <interface>]...
requires <interface> [, <interface>]...
Both go inside a component. On a port, use port p provides I or port p requires I. See
Port. In a package diagram an interface is a boxed classifier instead:
see Classifier.
Specification
UML 2.5.1, 10.4.4 (p. 172): lollipop and socket; a dependency arrow from a usage to a realization may join socket to lollipop. Components: 11.6.4 (p. 210) and Figure 11.46 (p. 214). Ball-and-socket: 11.2.4 (p. 186), which permits it only for simple ports and forbids it for complex ports and parts without ports.
Used in
Compiler pipeline, Debugger, API gateway, Container runtime.
See also
Component diagrams (how to write the whole diagram), Elements of component diagrams, Grammar.
Port
A port is a small square on a component’s boundary, with its name beside it. It is a named interaction point.
component Modem {
port serial
port radio
}
Ports with interfaces
A port usually provides or requires one interface, which makes it a simple port. Two simple ports matched by name form a ball-and-socket. A port listing more than one interface is complex: its connector is drawn plain and named after the interface. See Interface.
component Radio { port rx provides IPackets }
component Stack { port input requires IPackets }
An unconnected port interface draws as a stub on the port.
component Controller {
port ctl provides IControl
port bus requires ICan
}
Choosing a side
drumlin chooses a side from a port’s connections. To override it, write left,
right, top or bottom.
component Board {
port power top
port ground bottom
port uart left
port spi right
}
Delegation
A connector from a composite’s port to an inner part delegates the interaction, and is drawn solid.
Refer to a port by its bare name when it is unique, or as component.port.
component Client { requires IApi }
component Service as svc {
port api provides IApi
port store requires IStore
component Router
component Worker
api --> Router
Router --> Worker
Worker --> store
}
component Database { provides IStore }
Syntax
port <name> [left | right | top | bottom] [provides <i> | requires <i>]...
Specification
UML 2.5.1, 11.3.4 (p. 191): a small square with the name near it, placed on or inside the boundary. Delegation connector: 11.3.3 (p. 191) and Figure 11.47 (p. 214). Port type labels and multiple interfaces on one lollipop are optional UML notation that drumlin does not draw.
Used in
Hexagonal service, Vehicle gateway, Storage engine.
See also
Component diagrams (how to write the whole diagram), Elements of component diagrams, Grammar.
Connector
A connector is a line between two elements. drumlin draws a solid line for a connector and a dashed line for a dependency; both may end in an open arrow.
| Syntax | Meaning |
|---|---|
a --> b | Solid line, open arrow at b |
a ..> b | Dashed dependency, open arrow at b |
a -- b | Solid line, no arrow |
a .. b | Dashed line, no arrow |
a <-- b | Same as b --> a |
a <.. b | Same as b ..> a |
component A
component B
component C
component D
A --> B
A ..> C
B -- D
C .. D
Labels
Text after : labels a connector.
component Producer
component Consumer
Producer --> Consumer : batches, 64 KiB max
Direction and rank
A connector places its source before its target, along the diagram direction. Cycles are allowed, and drumlin reverses one edge internally to rank them.
component Parser
component Lexer
component Preprocessor
Parser --> Lexer : next token
Lexer --> Preprocessor : include
Preprocessor --> Parser : macro expansion
Connectors drawn from interface names
Interface matching makes connectors too, without any arrow in the source. Two simple ports form a ball-and-socket assembly connector, a port with several interfaces gets a plain connector named after the interface, and an end with no port keeps its socket and lollipop apart with a dashed arrow. See Interface. A connector from a composite’s port to a part inside is a delegation.
Syntax
<ref> (--> | ..> | -- | .. | <-- | <..) <ref> [: <label>]
A connector needs two different components. A <<x>> in a label is written with guillemets, «x».
Specification
UML 2.5.1. Connectors: 11.2.4 (p. 186). Dependency: 7.7.4 (p. 39). An arrow on a connector end is an end adornment, as for an association (11.2.4, p. 186).
Used in
Cache-aside, Event-driven checkout, Build system.
See also
Component diagrams (how to write the whole diagram), Elements of component diagrams, Grammar.
Elements of package diagrams
One page per symbol of a package diagram: what it looks like, its syntax and the UML 2.5.1 clause it follows. Use these pages to look something up; to write a whole diagram, start with Package diagrams.
| Element | Syntax |
|---|---|
| Package | package "Name" { ... } |
| Classifier | class, interface, enum |
| Relations | a ..> b, a --> b, a --|> b, a ..|> b |
| Import and merge | a ..> b : <<import>> |
| Containment | a +-- b |
| Note | note a: text |
diagram package "All the package elements"
direction right
package App {
class Handler
}
package Core {
interface Store
class SqlStore
SqlStore ..|> Store
}
App ..> Core : <<import>>
note App: Only depends on Core.
See Package diagrams for how to write one, and the grammar for every statement.
Package
A package is a folder: a rectangle with a small tab. When it shows its contents its name sits in the tab, and when it shows none its name sits in the body. In component diagrams it groups components; in package diagrams it is the main symbol.
Inside a package diagram:
diagram package "Tab or body"
package Empty
package Types { class Point }
In a component diagram:
package "Domain" {
component Orders
component Customers
Orders --> Customers
}
Connectors may cross package boundaries.
package "Application" as app {
component Handlers
}
package "Domain" as domain {
component Model
}
package "Adapters" as adapters {
component SQL
component Kafka
align SQL Kafka
}
Handlers --> Model
SQL ..> Model : implements
Kafka ..> Model : implements
Packages can nest.
package "Platform" {
package "Storage" {
component Blob
component Index
Index --> Blob
}
package "Compute" {
component Runner
}
Runner --> Index
}
A package may also sit inside a component, as one of its packaged elements.
Syntax
package <name> [as <alias>] [<<stereotype>>] [{ ... }]
Specification
UML 2.5.1, 12.2.4 (p. 248). Packaged elements in a component: 11.6.3 (p. 210).
Used in
Layered architecture, Monolithic kernel, RTOS layers.
See also
Package diagrams (how to write the whole diagram), Elements of package diagrams, Grammar.
Classifier
class, interface and enum declare a named box. An interface carries the keyword
«interface», and an enumeration «enumeration». Other stereotypes join the keywords; <<abstract>>
sets the name in italics instead.
diagram package "Classifiers"
direction right
class Order
interface Repository
enum Status
class Shape <<abstract>>
Looking for lollipops and sockets? Those are the interfaces of component diagrams.
Syntax
class|interface|enum <name> [as <alias>] [<<stereotype>>]
Classifiers cannot have bodies, so attributes and operations are not listed.
Specification
UML 2.5.1. Classifier notation and italics for abstract classifiers: 9.2.4 (p. 101). «interface» keyword: 10.4.4 (p. 172). «enumeration» keyword: 10.2.4 (p. 168).
Used in
See also
Package diagrams (how to write the whole diagram), Elements of package diagrams, Grammar.
Relations
Relations between packages and classifiers in a package diagram.
| Arrow | Relation | Drawn as |
|---|---|---|
a ..> b | Dependency | Dashed line, open head |
a --> b | Directed association | Solid line, open head |
a -- b | Association | Solid line, no head |
a .. b | Plain dashed line | Dashed line, no head |
a --|> b | Generalization | Solid line, hollow triangle |
a ..|> b | Realization | Dashed line, hollow triangle |
diagram package "Relations"
direction right
interface Printable
class Report
class Invoice
class Ledger
Invoice --|> Report
Report ..|> Printable
Report --> Ledger : writes
Ledger ..> Printable : uses
Syntax
a ..> b [: label] a --> b a -- b a .. b a --|> b a ..|> b
Reversed forms such as <.., <--, <|-- and <|.. swap the two ends. A <<x>> in a label becomes «x».
Specification
UML 2.5.1. Dependency and Realization: 7.7.4 (p. 39). Association, open arrowhead for navigable end: 11.5.4 (p. 202). Generalization: 9.2.4 (p. 102).
Used in
See also
Package diagrams (how to write the whole diagram), Elements of package diagrams, Grammar.
Import and merge
A dashed arrow with an open head and a keyword in guillemets. «import» makes another package’s names
public here, «access» makes them private, and «merge» merges the target into the source. The arrow
points from the importing or receiving package to the imported or merged one.
diagram package "Import, access, merge"
direction right
package App
package Lib
package Util
package Base
App ..> Lib : <<import>>
App ..> Util : <<access>>
Lib ..> Base : <<merge>>
A nested package may import its parent, with the line ending on the inside of the boundary:
diagram package "Nested import"
package Core {
package Scheduler
Scheduler ..> Core : <<import>>
}
Syntax
a ..> b : <<import>>
a ..> b : <<access>>
a ..> b : <<merge>>
Any <<x>> in a relation label becomes «x», so other keywords work the same way.
Specification
UML 2.5.1. Import and access: 7.4.4.3 (p. 29). Merge: 12.2.4 (p. 248).
Used in
Package merge, Library dependency graph, Layered architecture.
See also
Package diagrams (how to write the whole diagram), Elements of package diagrams, Grammar.
Containment
Membership is usually shown by nesting. When it is clearer to draw a line, owner +-- member puts a
circle-plus on the owner. Members in the next rank share one trunk.
diagram package "Containment"
package Types
class Shape
class Point
Types +-- Shape
Types +-- Point
Syntax
owner +-- member
member --+ owner
Use it for members declared outside the owner’s block. A member drawn inside its owner needs no line, so
+-- to it is an error.
Specification
UML 2.5.1, 12.2.4 (p. 248).
Used in
Package diagrams: containment.
See also
Package diagrams (how to write the whole diagram), Elements of package diagrams, Grammar.
Elements of sequence diagrams
One page per symbol of a sequence diagram: what it looks like, its syntax and the UML 2.5.1 clause it follows. Use these pages to look something up; to write a whole diagram, start with Sequence diagrams.
| Element | Syntax |
|---|---|
| Lifeline | participant, actor |
| Message | a -> b, a ->> b, a --> b, [-> a, a ->] |
| Execution | a -> b : call { ... }, return |
| Creation and destruction | a -> new "B" as b, create, destroy |
| Combined fragment | alt, opt, loop, break, critical, neg, par |
| Interaction use | ref over a, b : Name |
| Note | note over a: text |
diagram sequence "All the sequence elements"
actor User as u
participant Server as s
u -> s : request() {
opt "cached" {
return hit
}
s -> new "Worker" as w : start
destroy w
return result
}
note over s: Stateless.
See Sequence diagrams for how to write one, and the grammar for every statement.
Lifeline
A lifeline is a box or a stick figure at the top, with a vertical dashed line below it. Declaration order sets the left-to-right order, and a name must be declared before use.
diagram sequence "Heads"
actor Operator as op
participant "Controller" as ctl <<service>>
op -> ctl : mount()
Syntax
participant <name> [as <alias>] [<<stereotype>>]
actor <name> [as <alias>] [<<stereotype>>]
Heads stay at the top and are not repeated at the bottom.
Specification
UML 2.5.1, 17.3.4.1 (p. 572). The head is a rectangle, or the classifier’s shape; a stick figure for an actor.
Used in
Raft log replication, TCP connection.
See also
Sequence diagrams (how to write the whole diagram), Elements of sequence diagrams, Grammar.
Message
A message is a horizontal arrow between lifelines, its kind shown by the line and head.
| Arrow | Message | Line and head |
|---|---|---|
a -> b | synchronous call | solid, filled head |
a ->> b | asynchronous | solid, open head |
a --> b | reply | dashed, open head |
[-> a | found (from outside the diagram) | filled circle at the start |
a ->] | lost (leaves the diagram) | filled circle at the end |
diagram sequence "Message kinds"
participant Client
participant Server
[-> Client : wake
Client -> Server : call()
Server --> Client : reply
Client ->> Server : notify
Server ->] : lost
A self-message draws a compact loop on its lifeline.
Syntax
<a> (-> | ->> | -->) <b> [: label] [{ ... }]
[-> <a> [: label] [{ ... }]
<a> ->] [: label]
A label runs to the end of the line, apart from a comment or a space-separated { or }; quote it to
keep those as text.
Specification
UML 2.5.1, 17.4.4.1 (p. 576): filled heads for synchronous, open for asynchronous and dashed lines for reply. Found and lost messages end on a small black circle (17.4.4, p. 577).
Used in
TCP connection, TLS 1.3 handshake.
See also
Sequence diagrams (how to write the whole diagram), Elements of sequence diagrams, Grammar.
Execution
An execution is a thin white bar on a lifeline, showing where it is active. Write a block after a message to open one. Bars nest and step to the right as calls go deeper.
diagram sequence "Nested executions"
participant App
participant Parser
App -> Parser : parse() {
Parser -> Parser : next token
return ast
}
return sends a reply from inside a block, to the block’s caller, and ends the bar when it is
the last statement.
Syntax
<a> -> <b> : label { ... }
return [text]
A plain synchronous self-call also opens a short nested bar.
Specification
UML 2.5.1, 17.2.4.4 (p. 569).
Used in
Interrupt handling with a nested IRQ, Raft log replication.
See also
Sequence diagrams (how to write the whole diagram), Elements of sequence diagrams, Grammar.
Creation and destruction
A created lifeline’s head is drawn at the moment of creation, and the creating message is dashed with an
open head. destroy ends a lifeline with an X.
diagram sequence "Worker lifetime"
participant Pool
Pool -> new "Worker" as w : spawn()
Pool ->> w : stop
destroy w
Syntax
<a> -> new <name> [as <alias>] [<<stereotype>>] [: label] [{ ... }]
create <name> [as <alias>] [<<stereotype>>] [: label] [{ ... }] inside a block
destroy <a>
A destroyed lifeline cannot be used afterwards. A destroy in one alt branch leaves the lifeline alive in the
others.
Specification
UML 2.5.1. Creation messages: 17.4.4 (p. 577). DestructionOccurrenceSpecification: 17.4.4.2 (p. 578).
Used in
Page fault in a demand-paged kernel.
See also
Sequence diagrams (how to write the whole diagram), Elements of sequence diagrams, Grammar.
Combined fragment
A frame around messages with the operator in a pentagon at its top left. Each operand has a [guard] above
its first event, and dashed lines divide operands.
diagram sequence "Alternatives"
participant Client
participant Server
alt "ok" {
Client -> Server : get
} else "retry" {
loop "(1,3)" {
Client ->> Server : retry
}
}
Operators: alt with else, opt, loop, break, critical, neg, and par with and.
loop "(1,3)" becomes loop(1,3), which is the spec’s textual form.
Syntax
alt ["guard"] { ... } [else ["guard"] { ... }]...
par ["guard"] { ... } [and ["guard"] { ... }]...
opt|loop|break|critical|neg ["guard"] { ... }
Specification
UML 2.5.1. Operands, constraints and frames: 17.6.4.1, 17.6.4.2, 17.6.4.3 (p. 585). Loop:
17.6.4.9 (p. 586). Coregions are an optional shorthand; par covers them.
Used in
Raft log replication, RPC with retry and exponential backoff, TLS 1.3 handshake.
See also
Sequence diagrams (how to write the whole diagram), Elements of sequence diagrams, Grammar.
Interaction use
A frame with a ref tab that stands for another interaction, spanning the lifelines it involves.
diagram sequence "Boot"
participant Bootloader as bl
participant Kernel as k
ref over bl, k : Verify signature
bl -> k : jump(entry)
Syntax
ref over <a>[, <b>]... : <name>
Specification
UML 2.5.1, 17.7.4.1 (p. 591).
Used in
Sequence diagrams: references and notes.
See also
Sequence diagrams (how to write the whole diagram), Elements of sequence diagrams, Grammar.
Elements of state diagrams
One page per symbol of a state diagram: what it looks like, its syntax and the UML 2.5.1 clause it follows. Use these pages to look something up; to write a whole diagram, start with State diagrams.
| Element | Syntax |
|---|---|
| State | state Name { ... }, entry /, do /, exit / |
| Region | region "name" { ... } |
| Pseudostates | [*], choice, junction, fork, join, terminate, [H], [H*] |
| Entry and exit points | entrypoint e, exitpoint x |
| Transition | a --> b : trigger [guard] / effect |
| Note | note a: text |
diagram state "All the state elements"
[*] --> Idle
Idle --> Busy : start [ready] / log()
state Busy {
entry / open()
[*] --> Work
Work --> [*]
}
Busy --> [*]
See State diagrams for how to write one, and the grammar for every statement.
State
A state is a rectangle with rounded corners. Internal behaviours go in a compartment under the name. A composite state holds other states.
diagram state "Simple and composite"
[*] --> Idle
Idle --> Running : start
state Running {
entry / open()
do / work()
[*] --> Step
Step --> [*]
}
Running --> [*]
Syntax
state <name> [as <alias>] [<<stereotype>>] [{ ... }]
entry|do|exit [/ expression] inside a state, one per line
trigger {, trigger} [guard] / effect internal transition, one per line
A name used in a transition declares a state. See State diagrams.
Specification
UML 2.5.1, 14.2.4.4 (p. 319). The final state is 14.2.4.5 (p. 327).
Used in
USB device, Process lifecycle.
See also
State diagrams (how to write the whole diagram), Elements of state diagrams, Grammar.
Region
A region is one orthogonal part of a composite state, drawn as a tile with dashed separators. Regions lie across the flow: side by side when flowing down, stacked when flowing right.
diagram state "Regions"
state Active {
region "input" {
[*] --> Reading
Reading --> [*]
}
region "output" {
[*] --> Writing
Writing --> [*]
}
}
Syntax
region ["name"] { ... } inside a state
A transition cannot join two regions of one state.
Specification
UML 2.5.1, 14.2.4.3 (p. 319).
Used in
See also
State diagrams (how to write the whole diagram), Elements of state diagrams, Grammar.
Pseudostates
| Pseudostate | Syntax | Symbol |
|---|---|---|
| Initial | [*] --> x | Filled circle |
| Final state | x --> [*] | Bull’s-eye |
| Choice | choice c | Diamond |
| Junction | junction j | Small filled circle |
| Fork | fork f | Solid bar, one in and at least two out |
| Join | join j | Solid bar, at least two in and one out |
| Terminate | terminate t | Cross |
| Shallow history | [H], Name[H] | Circle with H |
| Deep history | [H*], Name[H*] | Circle with H* |
diagram state "Choice, fork, join"
[*] --> Ready
Ready --> c : request
choice c
c --> f : [ok]
c --> [*] : [denied]
fork f
f --> A
f --> B
A --> j
B --> j
join j
j --> Done
Done --> [*]
The final state is not strictly a pseudostate but is listed here because it is drawn with them.
Syntax
choice|junction|fork|join|terminate <name>
[*] --> a a --> [*] [H] [H*] Name[H] Name[H*]
Specification
UML 2.5.1, 14.2.4.6 (p. 327). FinalState: 14.2.4.5 (p. 327). Multiplicities of fork, join, choice and junction, and the forbidden triggers on pseudostate transitions, are constraints of clause 14.5, which drumlin checks and reports as errors.
Used in
OTA firmware update, State diagrams: pseudostates.
See also
State diagrams (how to write the whole diagram), Elements of state diagrams, Grammar.
Entry and exit points
A small circle on a state’s border for an entry point, and a crossed circle for an exit point, each with its name beside it. Outside transitions attach on the outer side, inside ones on the inner side.
diagram state "Entry and exit points"
[*] --> Idle
Idle --> again : retry
state Login {
entrypoint again
exitpoint aborted
again --> Prompt
Prompt --> aborted : [locked out]
}
aborted --> Idle
Syntax
entrypoint <name> inside a state
exitpoint <name> inside a state
Specification
UML 2.5.1, 14.2.4.6 (p. 328).
Used in
State diagrams: entry and exit points.
See also
State diagrams (how to write the whole diagram), Elements of state diagrams, Grammar.
Transition
A solid line with an open head, labeled trigger [guard] / effect. Every part is optional. A self-transition is
a compact loop. A transition between a composite state and a vertex inside it is local, drawn to or from the
inside of the border.
diagram state "Transitions"
direction right
[*] --> Waiting
Waiting --> Armed : arm [ready] / log()
Armed --> Armed : tick / count()
Armed --> [*] : done
Syntax
a --> b [: trigger {, trigger} [guard] / effect]
b <-- a
A long label breaks before the effect, then wraps. Pseudostate transitions have limits on which parts they may carry: see Pseudostates and the transition labels section.
Specification
UML 2.5.1. Notation and label syntax: 14.2.4.8 (p. 331). Local and external transitions: 14.2.4.9 (p. 334).
Used in
TCP connection, Circuit breaker.
See also
State diagrams (how to write the whole diagram), Elements of state diagrams, Grammar.
Elements of activity diagrams
One page per symbol of a activity diagram: what it looks like, its syntax and the UML 2.5.1 clause it follows. Use these pages to look something up; to write a whole diagram, start with Activity diagrams.
| Element | Syntax |
|---|---|
| Action | action "Name" |
| Initial and final nodes | start, stop, end |
| Decision and merge | if, switch, while, repeat |
| Fork and join | fork { ... } and { ... } |
| Object node | object "Name" |
| Signals | send "Name", accept "Name" |
| Partition | lane "Name" { ... } |
| Note | note: text |
diagram activity "All the activity elements"
start
action "Receive"
if "valid" {
action "Process"
} else {
action "Reject"
}
stop
See Activity diagrams for how to write one, and the grammar for every statement.
Action
A rectangle with rounded corners. Actions in order are joined by flows with open arrowheads.
diagram activity "Actions"
start
action "Validate request"
action Handle
stop
Syntax
action "name"
A name that is a single word needs no quotes.
Specification
UML 2.5.1. Executable nodes: 15.5.4.1, Figure 15.61 (p. 404). Actions: 16.2.4 (p. 446). Flows: 15.2.4 (p. 379).
Used in
Build and release pipeline, Connection retry.
See also
Activity diagrams (how to write the whole diagram), Elements of activity diagrams, Grammar.
Initial and final nodes
start is the initial node, a filled circle. stop is the activity final, a bull’s-eye, ending the whole activity.
end is the flow final, a circled X, ending only its own flow.
diagram activity "Control nodes"
start
fork {
action "Audit"
end
} and {
action "Respond"
}
stop
Syntax
start
stop
end
start must be first in the flow. Statements after stop or end are unreachable and an error.
Specification
UML 2.5.1, 15.3.4 (p. 391).
Used in
Firmware boot, Interrupt service with deferred work.
See also
Activity diagrams (how to write the whole diagram), Elements of activity diagrams, Grammar.
Decision and merge
A diamond. A decision has guards in square brackets on its outgoing flows; a merge joins flows again. if draws
both. while and repeat build a loop from a merge and a decision.
diagram activity "Decision and loop"
start
if "valid" {
action "Accept"
} else "malformed" {
action "Reject"
}
while "more input" {
action "Read"
}
stop
An omitted guard after else is the predefined [else]. switch "subject" shows the subject as a «decisionInput»
note on the diamond.
Syntax
if "guard" { ... } [else if "guard" { ... }]... [else ["guard"] { ... }]
switch ["subject"] { case "guard" { ... } ... }
while "guard" { ... }
repeat { ... } until "guard"
Specification
UML 2.5.1. Decision and merge: 15.3.4 (p. 391). «decisionInput»: Figure 15.33 (p. 390). Guards and [else]:
15.2.4 (p. 380).
Used in
Firmware boot, Connection retry.
See also
Activity diagrams (how to write the whole diagram), Elements of activity diagrams, Grammar.
Fork and join
A solid bar. A fork splits one flow into concurrent flows, and a join waits for them all.
diagram activity "Fork and join"
start
fork {
action "Fetch profile"
} and {
action "Fetch orders"
}
action "Compose page"
stop
A branch ending in end or stop does not reach the join. When only one branch reaches it, the join is
left out. In lanes, a bar spans the lanes of its branches.
Syntax
fork { ... } and { ... } [and { ... }]...
Each branch needs at least one step.
Specification
UML 2.5.1, 15.3.4 (p. 391).
Used in
Build and release pipeline, Deployment with parallel checks.
See also
Activity diagrams (how to write the whole diagram), Elements of activity diagrams, Grammar.
Object node
A plain rectangle on the flow. Flows into and out of it are object flows.
diagram activity "Object on the flow"
start
action "Resolve dependencies"
object "Lockfile"
action "Compile"
stop
Syntax
object "name"
An object cannot directly follow start, as an initial node starts only control flows.
Specification
UML 2.5.1, 15.4.4 (p. 399).
Used in
See also
Activity diagrams (how to write the whole diagram), Elements of activity diagrams, Grammar.
Signals
send draws a send signal action, a convex pentagon. accept draws an accept event action, a concave pentagon. An
accept needs no incoming flow, so it may begin an activity instead of start.
diagram activity "Signals"
start
action "Request payment"
send "PaymentRequested"
accept "PaymentConfirmed"
action "Ship goods"
stop
Syntax
send "name"
accept "name"
Specification
UML 2.5.1. Send signal: 16.3.4.3 (p. 455). Accept event: 16.10.4 (p. 474).
Used in
Interrupt service with deferred work, Deployment with parallel checks.
See also
Activity diagrams (how to write the whole diagram), Elements of activity diagrams, Grammar.
Partition
A swimlane band with its name at the top. Lanes appear in the order they are first named.
diagram activity "Swimlanes"
start
lane "Customer" {
action "Place order"
}
lane "Warehouse" {
action "Pick items"
}
stop
A lane inside a lane is not a sub-partition: it simply moves the steps inside it to that lane. In a diagram with lanes,
actions, signals and objects must be inside a lane.
Syntax
lane "name" { ... }
Specification
UML 2.5.1, 15.6.4 (p. 408). A node may belong to several partitions, which is how a fork bar spans lanes.
Used in
Deployment with parallel checks.
See also
Activity diagrams (how to write the whole diagram), Elements of activity diagrams, Grammar.
Note
A note is a rectangle with its upper right corner folded, joined to its target by a dashed line. It attaches free text to an element, and drumlin wraps the text. Notes work in every diagram kind; this page shows the component form first, then the forms of the other kinds.
component Cache
note Cache: Write-through. Entries expire after 30 seconds.
A note sits next to its target, inside the same container.
package "Storage" {
component Journal
component Pages
Journal --> Pages
note Journal: fsync before every commit record.
}
Attach several notes where they help.
component Reader
component Writer
Reader --> Writer : wakes
note Reader: Lock-free. May retry.
note Writer: Single owner only.
Other kinds
Notes work in every diagram kind, with the syntax of that kind:
diagram state "A note on a state"
[*] --> Idle
Idle --> [*]
note Idle: Waits here between jobs.
In a sequence diagram, write note over a: text, note left of a: text or note right of a: text.
There the line is suppressed, as the spec allows when the context is clear. In an activity diagram,
write note: text after a statement to attach it.
Syntax
note <target>: text component, package and state diagrams
note over <a>[, <b>]... : text sequence diagrams
note left of <a>: text
note right of <a>: text
note: text activity diagrams, on the statement before it
Specification
UML 2.5.1, 7.2.4 (p. 22): a Comment is a rectangle with the upper right corner bent, connected by a dashed line, which may be suppressed if the context is clear.
Used in
Storage engine, Layered architecture, Process lifecycle, TCP connection, Build and release pipeline.
See also
Grammar, where each kind lists its note statement.
Grammar
Every statement of every diagram kind, in one place, for looking things up. Each kind’s section links to its how-to page, where the same statements are explained with pictures.
Common to every kind
diagram <kind> ["Title"] kind: component, package, sequence, state, activity
style (pens | plain | lettering) every kind
direction (right | down) component, package and state diagrams
layout <engine> component, package and state diagrams
# comment also // comment
- Each statement occupies one line. A
{ ... }body may share the line with its braces. - A file with no
diagramline is a component diagram. - A
<name>is a bare word or a"quoted string". Bare words may contain letters, digits,_, and single-or.between them. <<stereotype>>after a name is drawn as the keyword«stereotype».direction,layoutandstylemay stand on any line; the last one wins. See File basics and Styles.
Component diagrams
diagram component ["Title"]
direction (right | down)
layout <engine>
style <name>
package <name> [as <alias>] [<<stereotype>>] [{ ... }]
component <name> [as <alias>] [<<stereotype>>] [{ ... }]
provides <interface> [, <interface>]...
requires <interface> [, <interface>]...
port <name> [left | right | top | bottom] [provides <i> | requires <i>]...
<ref> (--> | ..> | -- | .. | <-- | <..) <ref> [: <label>]
note <element>: <text>
align <element> <element>...
<element> (left-of | right-of | above | below) <element>
An element is referenced by its alias, or by its name when it has no alias.
A <ref> is an element, a unique port name, or <element>.<port>.
Component rules:
provides,requiresandportbelong inside a component.- A package may be nested inside a component (it is one of its packaged elements).
- A connector needs two different components.
- A requirer and a provider of the same interface name are wired automatically. See Interface.
- Declarations may come after the connectors that use them.
layout <engine>picks the layout engine of component, package and state diagrams:longest-path(the default) ornetwork-simplex. See File basics.
How-to: Component diagrams. Symbols: Elements of component diagrams. Examples.
Package diagrams
diagram package ["Title"]
direction right|down
layout <engine>
style <name>
package <name> [as <alias>] [<<stereotype>>] [{ ... }]
class|interface|enum <name> [as <alias>] [<<stereotype>>]
a ..> b [: label] a --> b a -- b a .. b a --|> b a ..|> b a +-- b
note <target>: text
a left-of|right-of|above|below b
align a b c
Statements can be separated with ; as well as newlines.
How-to: Package diagrams. Symbols: Elements of package diagrams. Examples.
Sequence diagrams
diagram sequence ["Title"]
style <name>
actor|participant <name> [as <alias>] [<<stereotype>>]
<a> (-> | ->> | -->) <b> [: label] [{ ... }]
<a> -> new <name> [as <alias>] [<<stereotype>>] [: label] [{ ... }]
create <name> [as <alias>] [<<stereotype>>] [: label] [{ ... }] inside a block
[-> <a> [: label] [{ ... }] found <a> ->] [: label] lost
return [text] inside a block
destroy <a>
alt ["guard"] { ... } [else ["guard"] { ... }]...
par ["guard"] { ... } [and ["guard"] { ... }]...
opt|loop|break|critical|neg ["guard"] { ... }
ref over <a>[, <b>]... : <name>
note over <a>[, <b>]... : text note left of <a>: text note right of <a>: text
Participants must be declared before use. ; separates statements outside labels. A label
extends to the end of the line, except for a comment after whitespace (# or //) or a
space-separated { or }; quote a label to keep these as text.
How-to: Sequence diagrams. Symbols: Elements of sequence diagrams. Examples.
State diagrams
diagram state ["Title"]
direction right|down
layout <engine>
style <name>
state <name> [as <alias>] [<<stereotype>>] [{ ... }]
region ["name"] { ... } inside a state
entry|do|exit [/ expression] inside a state, one per line
trigger {, trigger} [guard] / effect internal transition, one per line
[*] --> a a --> [*] a --> b [: label] b <-- a
[H] [H*] Name[H] Name[H*] shallow and deep history
choice|junction|fork|join|terminate <name>
entrypoint|exitpoint <name> inside a state
note <target>: text
a left-of|right-of|above|below b
align a b c
A transition label has the form trigger {, trigger} [guard] / effect, with every part
optional. ; separates statements except internal behaviour lines and labels. A label extends
to the end of the line, except for a comment after whitespace.
How-to: State diagrams. Symbols: Elements of state diagrams. Examples.
Activity diagrams
diagram activity ["Title"]
style <name>
start first statement of the flow
action|send|accept|object "name"
if "guard" { ... } [else if "guard" { ... }]... [else ["guard"] { ... }]
switch ["subject"] { case "guard" { ... } case "guard" { ... } ... }
while "guard" { ... }
repeat { ... } until "guard"
fork { ... } and { ... } [and { ... }]...
lane "name" { ... }
note: text
stop activity final
end flow final
A note attaches to the statement before it. Guards are written without brackets. In a diagram with lanes,
actions, signals and objects must be inside a lane block.
How-to: Activity diagrams. Symbols: Elements of activity diagrams. Examples.
Command line
This page lists every command and option of the drumlin binary. For a first run, see
Getting started.
drumlin render <input.uml> [-o <output.svg>] [--layout <engine>] [--style <name>]
drumlin check <input.uml> [--layout <engine>] [--style <name>]
Commands
| Command | Effect |
|---|---|
drumlin render <file> | Renders the file and writes the SVG to standard output. |
drumlin render <file> -o <out.svg> | Writes the SVG to a file instead. |
drumlin check <file> | Reads and checks the file, and writes nothing. |
drumlin reads one file per run. Options may come before or after the file name.
Options
| Option | Effect |
|---|---|
-o <out.svg> | With render: the file to write. |
--layout <engine> | The layout engine: longest-path (the default) or network-simplex. Component, package and state diagrams only. Wins over the file’s layout statement. |
--style <name> | The style: pens (the default), plain or lettering. Every diagram kind. Wins over the file’s style statement. |
Run drumlin with no arguments to print the usage text, with the engines and styles.
Exit status and errors
Both commands exit with 0 on success and 1 on any error. An error in the file is printed to standard
error as file:line:col: error: message, and only the first error is reported:
hello.uml:5:12: error: unknown element `Sever`; did you mean `Server`?
An unknown engine or style given on the command line is reported without a file or position, for example
error: unknown style `plan`; did you mean `plain`?. Errors lists the common messages
with the source that causes them.
Layout hints
drumlin places everything for you. When you want a different arrangement, a layout hint adjusts the result. Hints describe relations, never coordinates, so the source stays readable. They work in component, package and state diagrams; sequence and activity diagrams take their order from the file. Most diagrams need no hints: add one only when the drawing needs help.
| Hint | Effect |
|---|---|
a left-of b, a right-of b | Horizontal order |
a above b, a below b | Vertical order |
align a b c | Places elements in the same rank |
Same rank
Connectors normally give each element its own rank. align overrides that and
places elements in one rank, which shortens a wide diagram.
diagram component "Without align"
component Gateway
component Auth
component Orders
Gateway --> Auth
Auth --> Orders
diagram component "With align"
component Gateway
component Auth
component Orders
Gateway --> Auth
Auth --> Orders
align Auth Orders
Forcing order
With direction right, above and below order elements within a rank.
diagram component "Metrics above Logs"
component App
component Logs
component Metrics
App --> Logs
App --> Metrics
Metrics above Logs
Along the diagram direction, a hint forces a rank order even with no connector.
diagram component "Order without connectors"
component Boot
component Init
component Run
Boot left-of Init
Init left-of Run
Hints across containers
A hint between elements in different containers applies to the containers that
hold them. Here Reader left-of Query places the Ingest package left of Serve.
package "Ingest" { component Reader }
package "Serve" { component Query }
package "Admin" { component Console }
Reader left-of Query
Console left-of Query
See also
Hints win over the layout’s own choices: see Honour hints over heuristics. Package and state diagrams use the same hints as the examples above: see Package diagrams and State diagrams.
Errors
This page lists the errors you are most likely to meet, grouped by cause, with the source that causes each. Search the page for the words of your message.
Errors have the form file:line:col: error: message, and drumlin reports only the first error in a file.
The messages below are real: drumlin produced them while this book was built, without the file prefix.
For the command-line errors, see Command line.
Unknown names
An element must be declared somewhere in the file. drumlin suggests the closest declared name.
component Scheduler
component Worker
Scheduelr --> Worker
drumlin says:
3:1: error: unknown element `Scheduelr`; did you mean `Scheduler`?
Duplicate declarations
A name or alias may be declared once.
component Worker
component Worker
drumlin says:
2:11: error: `Worker` is already declared
Unclosed blocks
component Outer {
component Inner
drumlin says:
2:1: error: missing `}` for `Outer`
Unmatched braces
component Lonely
}
drumlin says:
2:1: error: unmatched `}`
Invalid nesting
A member drawn inside its owner needs no containment line: see Containment.
diagram package
package Outer { class Inner }
Outer +-- Inner
drumlin says:
3:1: error: `Inner` is drawn inside `Outer`, so containment needs no line; declare `Inner` outside the `Outer` block
Misplaced statements
provides, requires and port belong inside a component: see
Interface.
provides IFoo
drumlin says:
1:1: error: `provides` and `requires` belong inside a component
Ambiguous ports
A port name used by two components must be written as <component>.<port>: see
Port.
component A { port data }
component B { port data }
component C
data --> C
drumlin says:
4:1: error: port `data` is ambiguous; write `<component>.data`
Unimplemented diagram kinds
drumlin draws five kinds: see File basics.
diagram timing "Handshake"
drumlin says:
1:1: error: diagram kind `timing` is not implemented; this prototype supports `component`, `package`, `sequence`, `state`, `activity`
Layout engines
An unknown engine name lists the engines, or suggests a near one. See Layout engine.
diagram state
layout dot
[*] --> Idle
drumlin says:
2:8: error: unknown layout engine `dot`; the engines are `longest-path`, `network-simplex`
Sequence and activity diagrams have their own layouts.
diagram sequence
layout longest-path
participant Client
drumlin says:
2:1: error: sequence diagrams have their own layout; layout engines apply to component, package and state diagrams
drumlin render --layout <engine> reports an unknown name as error: unknown layout engine ..., without a
file or position, and a sequence or activity file at its diagram header.
Styles
An unknown style name lists the styles, or suggests a near one. Every kind takes a style; see Styles.
diagram sequence
style sketch
participant Client
drumlin says:
2:7: error: unknown style `sketch`; the styles are `pens`, `plain`, `lettering`
drumlin render --style <name> reports an unknown name as error: unknown style ..., without a file or
position, for example error: unknown style plan; did you mean plain?.
Sequence diagrams
See Sequence diagrams for the syntax. Names must be declared before use, so a typo is caught where it happens.
diagram sequence
participant Server
Servre -> Server : ping
drumlin says:
3:1: error: unknown participant `Servre`; did you mean `Server`?; declare it with `participant` before its first use
A return needs a message block to return from.
diagram sequence
participant A
return done
drumlin says:
3:1: error: `return` belongs inside a message block
A fragment continuation must match its opener.
diagram sequence
participant A
participant B
opt "x" {
A -> B : y
} else {
B -> A : z
}
drumlin says:
6:3: error: `else` must follow the `}` of an `alt`
State diagrams
See State diagrams and Pseudostates for the rules. Rules from UML 2.5.1 clause 14 are checked. A fork, for example, needs one incoming and at least two outgoing transitions.
diagram state
fork f
A --> f
f --> B
drumlin says:
2:6: error: fork `f` needs exactly one incoming and at least two outgoing transitions
A name used only once, close to another name, is reported as a likely typo. Write
state Idel first if the state really has that name.
diagram state
state Idle
[*] --> Idle
Idle --> Idel : wait
drumlin says:
4:10: error: unknown state `Idel`; did you mean `Idle`? declare it with `state Idel` if intended
A transition leaving a pseudostate cannot have a trigger.
diagram state
choice c
A --> c
c --> B : go
drumlin says:
4:7: error: a transition leaving a pseudostate cannot have a trigger; use `[guard] / effect`
A transition cannot join two orthogonal regions of one state.
diagram state
state A {
region {
[*] --> B
}
region {
[*] --> C
C --> B
}
}
drumlin says:
8:5: error: a transition cannot join two orthogonal regions of `A`
Activity diagrams
See Rules from the specification. Statements after the end of a flow can never run.
diagram activity
start
stop
action "Late"
drumlin says:
4:1: error: this statement can never run: the flow already ended with `stop` on line 3; remove it, or move it before the end
Every branch of a fork needs a step.
diagram activity
start
fork {
action "A"
} and {
}
stop
drumlin says:
5:3: error: this `fork` branch is empty; each branch needs a step, or remove the branch
A flow must not end on a merge, because a merge has one outgoing flow.
diagram activity
start
if "x" {
action "A"
}
drumlin says:
3:1: error: the flow continues after this `if` but nothing follows; add a step, or end it with `stop` or `end`
When a diagram uses lanes, every action must be in one.
diagram activity
lane "A" {
}
start
action "B"
stop
drumlin says:
5:1: error: this diagram uses lanes, so this `action` must be inside a `lane` block
What follows UML, and what is drumlin’s choice
drumlin says its notation is checked against UML 2.5.1. This page says exactly what that covers, because the specification defines some things firmly and leaves others open.
What UML 2.5.1 defines
- The notation of each element. The clauses on structured classifiers, packages, state machines, activities and interactions say how a component, a port, a pseudostate, a decision or a message is drawn. Each page under Elements cites the sub clause its symbol follows.
- The keywords between guillemets, such as
«import»and«merge»(Annex C). - A taxonomy of diagram kinds, loosely. Annex A names the kinds (activity, class, component, deployment, interaction, package, state machine, use case, and the more specific ones such as the sequence diagram) and says which clause describes the constructs of each. It also says that a diagram’s kind comes from the primary symbols in it, that kinds may be mixed, and that “the boundaries between the various kinds of diagram types are not strictly enforced”.
- How a diagram’s layout is interchanged between tools. Annex B (UML Diagram Interchange), built on the OMG Diagram Definition specification, describes a file format for the positions of shapes and the points of lines. It has a class for each diagram kind, but it does not list which elements a kind may hold either.
What UML 2.5.1 leaves open
- Which elements a diagram kind accepts. There is no normative list. A tool has to choose.
- How a drawing looks beyond the symbols. Line weight, colour, type, spacing, where a label sits and how a line is routed are not specified. Annex B gives a font name and size as the only style a modeller controls, and says the shapes themselves follow the notation clauses.
- The frame. A diagram may have a frame with a heading, such as
sd Checkout. Annex A makes it optional.
What drumlin does
| Matter | drumlin |
|---|---|
| Element notation | Follows the UML 2.5.1 sub clause cited on each element’s page. Optional notation that drumlin leaves out is listed under known limitations. |
| Keywords | Written between guillemets as in Annex C. Stereotypes you write (<<service>>) are shown the same way. |
| Diagram kinds | Five: component, package, sequence, state and activity. They match the Annex A kinds component, package, sequence (an interaction diagram), state machine and activity. |
| What each kind accepts | drumlin’s own choice: a small set per kind, listed in the grammar. It is narrower than UML allows. A package may hold components in a component diagram and classifiers in a package diagram, but a state machine cannot sit inside a component, although UML would permit that mixture. |
| Frame and heading | Not drawn. The title is a caption above the drawing, not a UML heading. |
| Look | drumlin’s own choice: the drawing principles and the styles. None of it comes from the specification, and none of it contradicts it. |
| Interchange | None. drumlin reads its own text format and writes SVG. It keeps no UML model, so it neither reads nor writes XMI or UML Diagram Interchange files. |
So a drumlin drawing uses standard UML symbols, in diagrams whose scope drumlin chose. Where this book says “component diagram”, it means the kind that Annex A names, restricted to what the grammar accepts.
Glossary
The terms this book uses, one meaning each. UML terms are given in plain words; the Elements pages show each symbol.
Terms of the format
Diagram kind
One of the five diagrams drumlin draws: component, package, sequence, state and activity,
named in the header. The book says kind, not type.
Element
Anything you declare in the source and drumlin draws: a component, a package, a state, a lifeline, an action. A symbol is how an element looks.
Name, alias, title
The name of an element is the text drawn on it. An alias, given with as, is a short identifier for
the rest of the file. The title is the caption of the whole diagram, from the header.
Label
Text written after : on a line between elements: a connector label, a message, a transition’s
trigger, guard and effect, or a keyword such as «import».
Keyword and stereotype
A stereotype is what you write between << and >>, such as <<database>>. drumlin draws it as a
keyword in guillemets, «database», above the name. UML defines some keywords itself, such as
«interface» and «import».
Layout hint
A statement that adjusts the arrangement without coordinates: left-of, right-of, above, below
and align. See Layout hints.
Layout engine
The method that places the boxes of a component, package or state diagram: longest-path or
network-simplex. See File basics.
Style
How a drawing is inked: pens, plain or lettering. See Styles.
Terms of the drawing
Box
The outline drawn for an element: a component’s rectangle, a state’s rounded rectangle, a package’s folder. A container is a box that holds other boxes (a component with parts, a package with members, a composite state).
Line
Any drawn connection between two elements. Each diagram kind has its own UML name for it, used on its
pages: a connector in component diagrams, a relation in package diagrams, a message in sequence
diagrams, a transition in state diagrams and a flow in activity diagrams. Edge is used only for the
layout’s internal graph, and arrow only for the arrow you type (-->) and the arrowhead at a line’s end.
Connector
In a component diagram, a line between two components, ports or packages. A dependency is a dashed
connector (..>). An assembly connector joins a required interface to a provided one; a delegation
connector runs from a component’s port to a part inside it.
Interface, lollipop, socket
An interface is a named set of services. A component provides it (drawn as a lollipop, a circle on a stem) or requires it (a socket, a half circle). Two matched in a joined symbol make a ball-and-socket.
Port
A named point on a component’s boundary, drawn as a small square. A simple port has one interface.
Lifeline, execution
In a sequence diagram, a lifeline is a participant: a head with a dashed line down the page. An execution is the thin bar on a lifeline while it is active.
Combined fragment
In a sequence diagram, a frame around messages with an operator such as alt, loop or par.
Pseudostate
In a state diagram, a small symbol that steers transitions but is not a state: initial, choice, junction, fork, join, terminate, history.
Region
One of the parallel parts of a composite state, separated by dashed lines. Regions run at the same time.
Guard
A condition in square brackets, [ok], that must hold for a transition or flow to be taken.
Partition
In an activity diagram, a swimlane: a band that holds the steps one participant performs.
Rank
One step of the layout’s main direction. Boxes in one rank sit side by side across the flow.
Golden file
A source file and its expected SVG in tests/golden/. The tests fail when a drawing changes by a byte.
Drawing principles
This part of the book states the rules a drumlin drawing follows, and why. Read it if you want to know why a drawing looks the way it does, or if you change the layout: every change is judged against these rules. You do not need it to write diagrams.
drumlin aims to draw like a careful draftsman: someone who knows the notation, works on squared paper with a set of technical pens, and redraws a line rather than leave it crooked. Every line is straight unless it has a reason to turn, every label sits where it can belong to only one thing, and the space between shapes is even.
The state diagram above follows the rules. It flows one way, from top to bottom. The lines are
orthogonal, and none crosses another. Each label sits beside its own line. The reverse pair between
Running and Paused runs as two parallel lines, with their labels on the outside. The one line that
turns, stop, turns because three lines share the bottom of Running.
How rules are written
Each principle has:
- a name, in the imperative, such as Avoid crossings;
- the rule itself;
- why it matters;
- a source: the UML 2.5.1 specification, a published study of graph drawing or diagram reading (such as Purchase 1997 and 2002, Ware et al. 2002, Gansner et al. 1993, Wybrow et al. 2009 or Castelló et al. 2000), drafting practice, or, where none of these settles it, a design decision of this project. The levers study, measured on drumlin’s own drawings, backs some rules too;
- its status in drumlin:
- enforced: drumlin does this in every diagram it lays out, and the linked step of How layout works is where;
- partial: drumlin does this in some diagram kinds or cases, or tries but does not guarantee it; the status says what is not done;
- planned: drumlin does not do this yet.
Where it helps, a rule shows a good drawing, rendered by drumlin, or a bad one, drawn by hand.
Where a status mentions a measure, the quality test in src/diagrams/quality.rs counts it over the
golden files and fails when a change makes the total worse. Run
cargo test --lib quality -- --nocapture for the current numbers; this book does not repeat them.
When rules conflict
Rules conflict all the time. A label wants the straight line’s gap, which another line wants too. Growing a box straightens a connector but makes a row uneven. drumlin settles each conflict in this order, highest first:
- Correct notation. The UML 2.5.1 notation is never traded for looks. A package with contents keeps its name in the tab, even where a line would run straighter without the tab.
- Unambiguous reading. Every line, label and name must belong visibly to one thing. A label floating between two lines, an arrowhead on a corner, or two connectors leaving one point together are worse than any jog.
- No overlaps. No shape on a shape, no line on a line, and no line through a shape or a name. Two lines on one lane cannot be told apart, so this ranks above crossings.
- No crossings. Crossings matter most in every human-factors study of graph drawing (Purchase 1997; 93% preference in Purchase et al. 2002).
- Few bends. Bends come next in the preference data (91%), and continuity of a path helps it be traced (Ware et al. 2002).
- Flow and alignment. A single direction, ranks, centred and symmetric placement.
- Compactness. Small area and short lines, but never at the cost of the rules above.
- Uniformity. Even box sizes and even spacing. This is the first rule to give way: a box may grow to straighten a line.
Within one level, the main thing wins over the secondary thing. The spine of the drawing comes before a side branch, a solid line before a dashed one, a forward line before a return, and any line before a note. So when two lines want one side, or only one of them can be straight, the main one gets it (Give the main line the main side). Symmetry (level 6) gives way to a straight main branch (level 5): a fan is centred only when it has no main branch.
A rule that would make a drawing worse on a higher level is not applied to that drawing. drumlin lays the drawing out with and without the rule and keeps the better one, so a status may say “enforced where it costs no crossing and no bend”.
The order follows the published studies: crossings first, then bends, with orthogonality held throughout by construction. Readability and notation sit above everything, because a drawing that reads wrongly is worse than one that reads slowly.
The pages
- Shapes and spacing: grid, pens, lettering, box sizes and box growth.
- Lines and routing: orthogonal lines, bends, crossings, overlaps, sides, attachment points, channels and arrowheads.
- Labels: closeness to their line, no ambiguity, and never forcing a bend.
- Names and titles: where names go, and when they give way to lines.
- Flow and arrangement: direction, ranks, columns, alignment, symmetry and grouping.
- Notes per diagram kind: where component, package, state, sequence and activity diagrams add or bend rules.
- Background: the levers study: the measurements that chose which rules to build first.
Shapes and spacing
Rules for the grid, the pens and lettering, the size of boxes and the gaps between them.
Snap to the grid
Rule. Every box corner, connection point and line segment lies on an 8px grid. Box sizes are multiples of 16px.
Why. A grid makes alignment the default instead of an accident: two boxes of one height in one rank share their top, centre and bottom, and parallel lines keep whole-step distances. It is the squared paper of hand drafting.
Source. Drafting practice.
Status: enforced. Placement snaps positions; slots and lanes snap in Slots and Routing. Exception: reserved label boxes are measured from their text, so their edges need not lie on the grid.
Draw with three pens
Rule. The default style, pens, inks every line in one warm black (#22201c), with white fills.
Three pen weights make a hierarchy:
| Pen | Width | Draws |
|---|---|---|
| Heavy | 1.75px | Outlines of boxes that hold other boxes: a component with parts, a package with members (tab and body), a composite state, an activity partition with its name head |
| Medium | 1.25px | Outlines of ordinary boxes and symbols: leaf components, classifiers, leaf packages, simple states, actions, object nodes, decisions, lifeline heads, execution bars, ports, balls and sockets, pseudostates, history and final circles, entry and exit points, the circle-plus of containment, the actor figure. Solid connector lines, their open arrowheads and hollow triangles, and the strokes of symbols (the cross of an exit point, a terminate, a flow final or a destroyed lifeline) |
| Fine | 0.75px | Dashed lines: dependencies, note links, lifelines, replies and create messages, dividers between regions, operand dividers. The arrowhead or hollow triangle at the end of a dashed line. Notes and their folded corners. The component icon. Compartment dividers in a state. The frame and name tab of a combined fragment (alt, opt, loop and the rest) and of an interaction use (ref) |
Filled marks, such as the initial dot, fork and join bars, filled arrowheads and the dot of a lost or found message, are solid ink. Dashes are 7 long with gaps of 3, so a fine dashed line still reads as a line. Connector bends are sharp, with mitred joins and butt caps; the rounded corners of states and actions stay, because they are notation.
Text has a hierarchy of its own, made with weight, size and shade but one typeface:
| Text | Size | Weight | Ink |
|---|---|---|---|
| Title | 16px | bold | black |
Names, and keywords in a name’s place (alt, loop) | 13px | bold | black |
| Labels, guards, interface and port names, activities | 11px | regular | black |
Keywords and stereotypes («component») | 10px, spaced 0.2px | regular | warm grey (#5c574f) |
| Note text, region and pseudostate names | 11px | regular | warm grey |
What states the model is black; what classifies or comments on it is grey. Abstract names are italic.
Why. A line weight hierarchy is standard drafting practice: ISO 128 sets line types and groups of thicknesses, so that thick lines carry the visible outlines and thin lines carry dimensions, hatching and other secondary information. Here the heaviest pen marks the structure the eye should find first, the boxes that group others; the medium pen marks the things and the relations between them; the fine pen marks what annotates rather than structures: notes, dependencies, dividers and icons. A fragment frame annotates a stretch of an interaction, so it takes the fine pen. The weights stay within a ratio of about 1:2.3, so the hierarchy is clear but not loud. Dashes still mean a dependency or comment, never emphasis. Text follows the same idea: a draftsman letters names larger and annotations smaller, and a softer ink lets keywords and notes recede behind the names they qualify. The grey keeps a contrast of about 7:1 on white.
Source. ISO 128 (technical drawings: line types and line thicknesses); Tufte’s smallest effective difference.
Status: enforced, by the pens style in core::style: each drawn mark names its role, and the style
maps the role to a class and the class to a pen. style plain is one ink (black), one line width (1.25px) for
every outline, line, icon, frame and lifeline, and regular text throughout: only the font size varies.
Its bends are sharp too. style lettering keeps the three pens and letters the text with pens of its
own: see Letter with a pen per size.
Letter with a pen per size
Rule. In the lettering style every piece of text is single-stroke technical lettering, drawn in
the warm black ink with a round pen. The pen follows the hand, as a draftsman changes pens with the
lettering guide: 1.5px for the title, 1.1px for names, 0.85px for small text and 0.75px for keywords
and stereotypes, which are small text in the finest pen. Names and the title
are in capitals with 0.06em letter spacing (names on a 12.5px em, the title on 16px); labels, keywords,
notes and other small text are upright mixed case on an 11px em, whose x-height matches the default
style’s. Bold names become capitals, abstract names lean 15 degrees, and a label drawn over a line
breaks the line with a white band. The digit one has a flag and no foot, and the zero is slashed and
narrower than the capital O, so neither reads as a letter.
Why. This is how a draftsman letters a drawing with a lettering guide: one pen, vertical or uniformly inclined strokes, capitals for what must be found. ISO 3098 sets the inclined form at 15 degrees from the vertical and asks that similar characters stay distinct. Capitals read larger than mixed case at one em, so names can be a little smaller than the default style’s bold names. One pen for all lettering keeps it apart from the line hierarchy: text is read, not followed.
Source. ISO 3098 (technical product documentation: lettering); ISO 128 for the pens.
Status: enforced, by the lettering style (core::lettering). The glyphs are drumlin’s lettering,
derived from Routed Gothic by Darren Embry (SIL Open Font License 1.1). Each run also carries its words
as invisible text stretched over the strokes, so they can be selected, copied and searched, and as an
accessible name.
Size boxes to their text
Rule. A box is as wide as its name and keyword need, plus padding, and never smaller than the
kind’s minimum (128 by 56 for a component, 96 by 40 for a state). Widths come from embedded Helvetica
metrics, so a box is the same size on every machine. In the lettering style they come from the
lettering’s own advance widths.
Why. A box that fits its text reads as one unit. A fixed size either crowds long names or leaves short ones lost. Measured text keeps the layout deterministic.
Source. A design decision of this project.
Status: enforced, by each adapter’s size function (leaf_size, state_size).
Leave room for what attaches
Rule. A side that carries several ends, ports or interface stubs is long enough to space them at least 24px apart, 16px clear of its corners. Where a line on a left or right side carries a name, its ends are 32px apart, so the name fits between two lines. A box grows across the flow until its sides have that room: three named lines on one side make a box 96px tall, not 64px. A state with many transitions is wider.
Why. Attachment points that crowd at a corner or touch each other make arrows unreadable, and force lines to jog to reach them.
Source. Drafting practice; Spread and order attachment points.
Status: enforced for stubs and ports, by side_needs (component), slot_room (package) and the
incident count in state_size. Partial for connector ends:
- Component diagrams count the ends the flow will put on each side (
side_needs) and lay the box out again with that room. The taller layout is kept only where the first one has an end nearer a corner than 16px or two ends nearer than 24px, and the taller one routes no worse. Ends that share a side are spread 32px apart where a line carries a name (NAMED_SLOT). - Not done: package and state diagrams do not count connector ends.
Keep gaps even and generous
Rule. Ranks are at least 64px apart and neighbours in a rank 40px apart. A gap grows when a label or interface needs it, and never shrinks below that.
Why. Even spacing reads as order. Generous gaps leave channels for lines to run in without crowding, which is cheaper than any later repair.
Source. Gansner et al. 1993 (separation in layered layout); drafting practice.
Status: enforced, by layered::Spacing and the edge gaps each adapter passes.
Grow a box rather than bend a line
Rule. When a connector jogs only because its two end boxes miss each other by a few grid steps, grow one box by up to two grid steps on a side, toward the other end, into free space, so that the line runs straight.
Why. Bends rank above uniform sizes (see When rules conflict).
A box that is 16px wider costs almost nothing, while the jog it removes costs a turn in every reading of
that line. Below, Message Bus grows 8px at its top and bottom, and each target 8px toward it, so all
three connectors run straight; without growth, Message Bus is no taller than Checkout and two of the
connectors jog.
diagram component "Lines straightened by a taller box"
component Checkout
component "Message Bus" as bus
component Payments
component Inventory
Checkout --> bus
bus --> Payments : OrderPlaced
bus --> Inventory : OrderPlaced
A box grows only into free space: 16px clear of every other box, inside its container’s padding, and clear of reserved labels, self-transition loops, interface stubs and ports. A box with stubs, ports or self-transitions keeps its size. Growth across the flow is tried before growth along it. The bounds of the diagram do not change.
Source. Purchase et al. 2002 (bends 91%); Layout levers.
Status: enforced, by core::grow after layout (Box growth), at
up to two grid steps. A growth is kept only when routing again shows the connector lost a bend, no total
rose, and no two connectors came to leave one point together. Not done: growth by four steps, which the
levers study measured as saving more bends at the cost of more uneven rows.
Keep a rank even
Rule. Boxes in one rank share a centre line along the flow, and should look like one row. When a box grows, prefer growth that keeps the row tidy, such as growing toward the gap between rows rather than away from it.
Why. Uneven heights make a row read as a staircase. This is the uniformity that box growth trades away, so it limits how far a box may grow.
Source. Drafting practice; the images in Layout levers.
Status: partial. Items in a rank are centred on one line (place_along). Box growth tries growth
across the flow first, which keeps a rank’s extent along the flow even, and grows at most 16px on a
side. Not done: a box may still end up a step taller or wider than its neighbours (Kafka Adapter in
Hexagonal service, Mobile App in API gateway), and a box that grows on one side only has its name up
to 8px off its neighbours’ line.
Lines and routing
Rules for the lines between boxes: their shape, where they leave and enter a box, and how they share space. They apply to component, package and state diagrams, which share the layered layout and the router. Sequence and activity diagrams have their own layouts; see Notes per diagram kind.
Draw lines orthogonally
Rule. Every connector is a chain of horizontal and vertical runs. In the default style, pens, the
bends are sharp mitred corners, as a pen drawn along a ruler leaves them; in plain they are small
rounded corners (6px radius, less on very short runs). There are no diagonals, except in a note’s link,
which is an annotation (see Note links may be diagonal).
Why. Orthogonal lines match the grid and the boxes, cross at right angles, which readers barely notice (Huang), and ranked second in UML diagram preference (Purchase et al. 2002).
Source. Purchase, Allder and Carrington 2002; Huang 2008; a design decision of this project. UML gives segments no meaning (“The individual segments of the line itself have no semantic significance”, 11.5.4, p. 201), so the style is free.
Status: enforced. Routing searches only orthogonal moves, and
Style::line draws the corners: straight joins for pens and lettering, glyphs::rounded for plain.
Keep lines out of shapes and names
Rule. A line never passes through a box, a symbol, a name, a reserved label or an interface stub. It may cross a container’s border only to reach something inside it.
Why. A line through a shape reads as a connection to that shape. A line through text makes both unreadable.
Source. Castelló, Mili and Tollis 2000 (their motivating figure shows edges through states as the failure to avoid).
Status: enforced. Each connection carries its own obstacles in Routing, and Nudging never moves a segment through one.
Never lay lines on top of each other
Rule. Two different connectors never share a run. Lines may join only where the notation joins them: the branches of a containment tree from one circle-plus, or several connectors meeting at one port.
Why. Two lines on one lane cannot be told apart, and a shared start reads as one connector that forks. That is worse than a crossing, which is still readable.
Bad: two connectors leave A from one point and share a run, so they read as one line that forks.
Source. Wybrow, Marriott and Stuckey 2009, section 5.
Status: enforced. Nudging ranks overlaps above crossings, and the quality test allows no overlap. Ends that slide may not come closer than 16px; an 8px gap lets two ends meet (levers study). The quality test also counts merged ends, two connectors leaving one point together, which the overlap count excuses; only the intended fan-ins to one port are allowed, and box growth is never kept if it merges two connectors.
Avoid crossings
Rule. Lines should not cross. When a crossing cannot be avoided, it is a clean right angle away from any corner, label or arrowhead.
Why. Crossings have the largest effect of any aesthetic on reading graphs (Purchase 1997), and 93% of subjects preferred the UML diagram with fewer (Purchase et al. 2002).
Bad: the lines to C and D cross, although swapping the order of their ends would separate them.
Source. Purchase 1997; Purchase, Allder and Carrington 2002.
Status: partial. Ordering (Crossing reduction), the router’s crossing cost, nudging and box growth remove most crossings. Ends on a shared side are spread in the order of the lines they start, so lines leave a box without crossing. Not done: the Order Platform drawing in the introduction keeps one crossing, because removing it needs ordering across containers, which the recursive layout cannot see (Order across containers too, the five crossings).
Bend only when you must
Rule. A line turns only when its ends are not aligned and cannot be. A Z between two ranks is acceptable when the ends cannot share a coordinate; a jog that a slightly different layout would remove is a defect.
Why. Bends are second only to crossings in the preference data (91%), and a continuous path is traced faster (Ware et al. 2002).
Source. Purchase et al. 2002; Ware, Purchase, Colpoys and McGill 2002.
Status: partial. Most lines run straight through these steps: straight long edges (Placement), slots that slide toward their peers (Slots), jog folding (Nudging), box growth, the 8px corner inset, ends on package tabs, L over Z, state labels that follow their lines, columns and alignment. Meet the middle ranks above this rule: an end alone on its side does not slide off the middle to run straight. Where alignment cannot line the boxes up, the line jogs once. The quality test fails when the total number of bends rises.
Give long lines room
Rule. A connector running beside a shape keeps a clear gap of at least two grid steps (16px), and three (24px) beside a composite state or a container.
Why. A line hugging a box reads as part of its outline: the eye follows the box’s border instead of
the line. A long return line beside a large composite, such as technician reset from Fault back to
Idle in Elevator controller, shows it most.
Source. Drafting practice.
Status: partial. In state diagrams, Routing gives each composite
state that is not an end of the line a soft band 24px deep around it: a line may run there only at a
cost, and nudging does not move one into it. Simple states keep lines off by their 8px wall, and their
spacing holds most lines 16px away. Component diagrams give the same band to every container that is
not an end of the line, and to a container the line reaches at a port. The quality test counts lines
that run beside a shape for more than 8px, closer than 16px (24px for containers). Not done: package
diagrams have no bands; in Composite states, resume runs inside Playing near its border.
Flow passes straight through a decision
Rule. At a choice, junction or decision diamond, one branch is the main one, and it leaves on the side opposite the incoming line, so the flow runs straight through the symbol. The other branches leave from the two sides across the flow. The main branch is the one whose target continues the column; failing that, the first declared. The same holds for merges, whose incoming lines meet on the incoming side.
Why. A decision that turns the flow hides which way is the normal case. Below, [ok] leaves the
choice straight down to Installing, opposite the line from Verifying, and [corrupt] leaves from the
side to return.
diagram state "Straight through"
[*] --> Downloading
Downloading --> Verifying
Verifying --> c
choice c
c --> Installing : [ok]
c --> Downloading : [corrupt]
Installing --> [*]
In an activity diagram the same holds for if and switch. Below, both arms of paid have a body and
both continue, so the first declared takes the axis and [else] leaves from the side; it comes back into
the merge from the side, and [paid] enters the merge from above. The unauthorised arm stops, so the arm
that continues takes the axis although it is declared second.
diagram activity "Straight through"
start
if "unauthorised" {
action "Send 401"
stop
} else {
action "Load account"
action "Check limits"
}
if "paid" {
action "Ship"
} else {
action "Send reminder"
}
stop
Source. Drafting practice for flowcharts.
Status: enforced in state and activity diagrams.
- State diagrams: a choice or junction is a decision (
Constraint::Pivot) to the layered layout, so its first branch keeps its column even against an equal branch, and a bar below it may end that column. In routing, the branch whose target lies straight ahead leaves from the forward side (spoke_sides), and the others from the corners on their sides. - Activity diagrams: a decision puts one arm on its axis (
arm_plan): the one arm that continues while the others end; else the body beside an empty arm; else the one arm in the decision’s own lane; else the middle arm, the first declared of two and the left of the middle two of four. The other arms keep their declared order left to right about it (the side arm of a two-armedifleaves on the right), or leave towards their own lane, and rejoin the merge from the side. - A fork is not a decision and keeps an even count of branches symmetric.
- Not done: turning a whole decision so the flow enters from the side; no drawing needs it yet.
Note links may be diagonal
Rule. A note’s dashed link is one short straight line from the nearest point of the note to the element, diagonal when they share no span. It never jogs and is never a stub. Where the note and its element share a span, the link leaves the middle of the note’s facing side when that middle lies in the shared span.
Why. A note link is an annotation, not a flow. UML 2.5.1 puts no direction on it (7.4.4), and an orthogonal stub of a few pixels reads as a mistake. A link that jogs around the note reads worse than a diagonal link.
Source. UML 2.5.1, 7.4.4; drafting practice.
Status: enforced. Component, package and state note links are routed, so other lines keep clear of
them, but drawn as geometry::note_link: across the middle of the span the note and its element share,
or corner to nearest point when they share none. In activity diagrams a note risen over a decision sits
24px beside the axis and 16px above it, and its link meets the diamond’s upper edge.
Leave from the facing side
Rule. A connector leaves its box on the side that faces the other end. When the boxes are apart on both axes, the side along the flow wins.
Why. The line then takes the short way, and the flow direction stays visible at both ends.
Source. Purchase et al. 2002 (information flow ranked third for UML).
Status: enforced, by router::facing, used by every adapter, as the first choice. Two rules below
may move an end off the facing side: a dashed line that must go round
(Give the main line the main side), and, after routing, an end
whose line arrives from beside the box (Never double back into a box).
Give the main line the main side
Rule. Lines that leave one box are served in order of weight: a solid line (a flow, an assembly, an association) before a dashed one (a dependency), and among equals the line on the main branch first (Line up the main branch). The heaviest line takes the side that faces along the flow and runs straight. A lighter line takes a side that is still free. A dashed line that passes other boxes on its way leaves on the outer side it will travel along and enters its target on that same side.
Why. A dashed line is secondary to a solid one: the reader follows the solid chain first. In
Compiler pipeline, the dashed invoke leaves Driver on the right and enters Code Generator on the
right, with the same number of bends as a route beside the main chain, and leaves the main chain alone.
A symbol that would hang on the crowded side, such as the ITarget ball, moves to the room the dashed
line gave up.
Source. Ware et al. 2002 (continuity of the main path); a design decision of this project.
Status: partial, component diagrams only. A dashed dependency between two leaf components that
overlap across the flow, whose straight way runs through a box linked to neither end, and whose end
shares its facing side with another line or a stub, leaves by a free side across the flow instead: the
right one (the bottom one when the flow runs right) unless it is taken
(Slots, secondary_sides). Where it arrives,
Never double back into a box turns it into its target’s side. A stub
that shares a side with lines goes to the end of the side its name faces. Compiler pipeline in the
component examples shows it. Not done:
- the outer side is chosen by rule (right or bottom first), not from the route the line will take;
- the rule does not apply when the far box lies wholly to one side, where the facing side and L over Z already give that line an L;
- solid lines are not ordered by the main branch beyond what Line up the main branch does;
- package and state diagrams have no dashed rule.
Never double back into a box
Rule. A line enters a box on the side it arrives from. It never passes the box, or runs along one of its sides, to turn back into another side. When the facing side is full, the line takes the side next to it that is nearer to where the line comes from.
Why. A line that turns back reads as if it came from somewhere else, and it spends two bends beside the box, where ends are already close together.
Source. Drafting practice.
Status: enforced where the side is clear, in component, package and state diagrams.
L over Z looks at the last three runs of every line: when the first of
them runs the same way as the last (a Z at the end) or back (a U), and the run across starts beyond the
box’s side, the end moves to that side, at its middle, and the line loses a bend. The same tests as for
an L hold. Ends may move on leaf components (also beside stubs and ports, not onto their sides), on
interface lines, on leaf packages and classes, and on simple states; a state with internal behaviours
takes them on its left and right sides only below its compartment line (Body::head). The test is
ends::doubled_back. Not done: a side held by a stub, port or self-transition loop, or a line so close
to the box that the side has no 16px run, keeps the turn.
Use a free side before you share one
Rule. When a box has more than one line toward the same direction, and a line can leave by a free neighbouring side with no more bends and no new crossing, that line takes the free side instead of a second slot on the shared side. A line that must bend anyway bends at the box: it leaves by the side that faces its target across the flow and makes an L, and leaves the facing side to the line that can be straight.
Why. Two ends on one side force at least one of the lines off the middle, and usually into a Z.
Source. Purchase et al. 2002 (bends); Schulze, Spönemann and von Hanxleden 2014 (free port sides in layered layout).
Status: partial. The free side is taken after routing, by
L over Z on the start of a line: a line that leaves a shared side and
at once turns past the box’s corner leaves by the side it turns toward, and makes its L there. In the
component examples: in Hexagonal service the lines to repo and publish leave Use Cases at the top
and the bottom while the Domain Model line keeps the right side, straight; Gateway’s three lines in
API gateway leave by three sides; IImages leaves Daemon at the top in Container runtime. Ends that
share a side are judged together with their partners and spread 32px apart where the lines carry names.
Not done: there is no side choice before routing for solid lines, so a line that could run straight from
a free side is not moved there; Secure boot chain keeps two ends on one side of Second Stage.
Take a return line around the outside
Rule. A line that runs against the flow (a return, a retry, a reset) is drawn as one loop on one outer side of the drawing: it leaves its source on that side, runs outside the boxes it passes, and enters its target on the same side. It does not leave by the side that faces along the flow, and it does not share a side with the forward lines when the outer side is free. At a decision, the branch that returns leaves the diamond by the side it returns along, not by the side of the forward flow. A return that cannot use a side (the side is taken by a line that runs straight) goes all the way round and enters its target from behind, on the side the forward flow came in by.
Why. Forward lines and return lines then never compete for a side, and the return reads as one bracket beside the flow.
Source. Gansner et al. 1993 (reversed edges kept to one side); drafting practice.
Status: partial.
- State diagrams: Never double back into a box moves both ends of a
return to the outer side it runs along. In USB device,
bus resetleavesConfiguredon the right, below its compartment line, and entersDefaulton the right; in Elevator controller,technician resetleavesFaultand entersIdleon the right. - Activity diagrams: a
whileloop whose body ends in a merge with a free left corner returns from that corner to the left (Interrupt service with deferred work). - Not done: a side that holds a self-transition loop is not freed for the return, so Process
lifecycle’s
wait(event)and Circuit breaker’sprobe succeededstill go round (see Draw self-transitions as compact loops away from the flow). When no clear L exists, the return keeps the start the router’s search gave it.
See also Give the main line the main side, which states the same for a dashed line that passes other boxes.
Prefer an L to a Z when the L is clear
Rule. When two boxes are apart on both axes and an L-shaped line between a side and a top (or bottom) is clear of everything, use the L, with one bend, instead of a Z with two.
Why. It saves a bend without hiding the flow, as long as the last run is long enough for its arrowhead.
Source. Purchase et al. 2002 (bends).
Status: enforced for plain boxes. State diagrams do this for final states, choices, junctions and terminate symbols when choosing sides. After routing, L over Z moves one end of a Z to the side of its box that faces the line, when the L then meets no box, name, reserved label or boundary, keeps 16px from other ends, gains no crossing, overlap or close run, and merges no ends. An end that lands alone on a side lands at its middle. It applies to leaf components (also those with stubs or ports, onto the sides that hold none, and to interface lines), leaf packages and classes (not a package’s top, which holds its tab), and simple states (a state with internal behaviours only below its compartment line). Exception, in component and package diagrams: an end alone on its side does not move when the far end shares its side, because that line is a branch of a fan, and an L that would leave an end alone off the middle of its old side is dropped.
Spread and order attachment points
Rule. Ends on one side are spread at least 24px apart, in the order that keeps their lines from crossing, and each slides toward the line that makes its connector straight.
Why. Evenly spaced ends read as separate connectors. Their order decides whether lines cross just outside the box.
Source. Schulze, Spönemann and von Hanxleden 2014 (port constraints in layered layout).
Status: partial. Slots spreads and orders ends by the position of the other end. In component diagrams, ends that share a side are then spread evenly and centred on it as a group, unless that takes an end off a straight line to another box. Not done: ordering by the side the route arrives from.
Keep ends off corners
Rule. An end stays at least 8px from a square box corner, and 16px from the curve of a rounded state corner. Ends are first spread 16px from corners; nudging may slide them to 8px on square boxes.
Why. An arrowhead at a corner is ambiguous about which side it meets, and on a rounded corner it meets a curve.
Bad: the arrowhead meets B in its rounded corner.
Source. Drafting practice; Layout levers (images of an 8px inset).
Status: enforced: 8px on square component and package boxes (CORNER_INSET in their routing),
16px on states, whose corners have a 10px radius, so that an arrowhead never lands on the curve. The
16px gap between ends stays.
Keep arrowheads apart
Rule. Two ends on one side are at least 16px apart after nudging, and 24px when slots are first spread.
Why. Two arrowheads closer than their own width merge into one mark.
Source. Drafting practice; a design decision of this project (SLIDE_GAP).
Status: enforced, by router::SLIDE_GAP and the slot spacing in each adapter.
End with a straight run
Rule. Every line leaves and enters a box with a straight run of at least 16px, so the arrowhead sits on a straight piece and points squarely at the side.
Why. An arrowhead on a corner points in two directions at once.
Source. Drafting practice.
Status: enforced, by the 16px stems of router::Terminal and, at state pseudostates, the
ARRIVAL_RUN. Ends with a head or start decoration need more: see
Leave room for the head.
Leave room for the head
Rule. The last run before an arrowhead or triangle, and the first run after a start decoration such as the containment circle-plus, is at least the decoration’s length plus 8px, rounded up to the grid: 24px for an open arrowhead (10px), a triangle (12px) or a circle-plus (12px).
Why. When the last bend sits right at the head, the corner runs into it and the arrow looks squashed.
Source. Drafting practice.
Status: partial. Terminal::reaching puts the stem of a decorated end that far out, on the grid,
and nudging, L over Z and the narrow-gap lane all keep it. Component containers pad a side whose port
takes an arrow from inside by 32px, so the run fits between the port and the boxes inside. The quality
test counts runs shorter than the decoration plus 8px. Not done: state transitions that keep a reserved
label keep the 16px stem, because in the 64px gap between two states, two labelled lines going opposite
ways would cross if each needed 24px.
Meet the middle
Rule. An end alone on a side of its box, or a port alone on a side of its component, sits at the middle of that side. A lone connector between two boxes leaves and enters at the middles of its sides. Where the boxes are not in line, first move them so their centres line up; failing that, keep both ends centred and jog once, midway. Only ends that share a side spread along it, evenly and centred as a group, and those may slide toward their lines. Where a line is held in place by its other end or by a straight chain, the box moves under the line, not the line along the side: the line stays, and the box shifts until the end (or the group of ends) is the same distance from both corners.
Why. An end off the middle of an otherwise empty side reads as careless: the line looks as if it slid to avoid something. A box in line with its neighbour and a line through both middles look drawn on purpose.
Source. Drafting practice.
Status: partial.
- Component and package diagrams: a lone end’s slot is the middle of its side, and it does not slide when nudging straightens a line. A port sits at the middle unless connectors inside its component lead to it, when it lines up with them. Alignment moves boxes across the flow so lone connectors run straight between middles. Component ends that share a side are centred as a group together with the group at the other end of their lines, so two boxes joined by several lines keep every line straight. A side that lines from a container’s contents cross counts as shared; note links do not count.
- State diagrams: a state moves under a line into or out of an entry or exit point, rather than the line
sliding off the state’s middle (Entry and exit points:
Idleunderretry). - The quality test counts ends alone on a side but more than 4px from its middle.
- Not done: state diagrams still slide other lone ends to straighten lines. Some component ends stay off the middle to keep clear of a package’s tab or a stub, or because no growth or L could centre them.
One junction per merge
Rule. Lines that merge, such as two connectors into one port, join at one point. A line that joins another turns onto it where the other turns, or onto its straight run, never a few pixels before or after.
Why. Two junctions a step apart look like a drawing error and make the reader wonder whether the lines meet at all.
Source. Drafting practice.
Status: enforced. The last nudging pass (Nudging) moves the
turning segment of the line that runs on back to where the other turns, if its line stands no worse.
The quality test counts pairs of lines that share an end and part less than 24px apart, and allows none.
Vehicle gateway shows it: the two IFrames lines join the trunk to port bus at one point.
Space parallel lines evenly
Rule. Lines that share a channel are spread evenly across it, at least 8px apart, and a lone jog sits in the middle of its gap.
Why. Wybrow et al. report that this nudging step has “a significant impact on the perception of layout quality”. Even spacing looks deliberate. Lines bunched on one side look accidental.
Source. Wybrow, Marriott and Stuckey 2009, section 5.
Status: enforced. The spread pass of Nudging does this.
Do not run along a boundary
Rule. A line never travels along a container’s border. It crosses the border at a right angle.
Why. A line along a border merges with it, and reads as part of the container.
Source. Drafting practice.
Status: enforced. Container borders are soft strips in Routing, and Nudging never moves a segment onto one.
Join lines only where the notation does
Rule. Containment drawn with branching lines has one trunk from the owner’s circle-plus. Other relations each get their own line, even when they share an end.
Why. A shared trunk says “these belong together”, which is true for containment (UML 12.2.4) and false for, say, two dependencies.
Source. UML 2.5.1, 12.2.4, p. 248; Purchase et al. 2002 (76% preferred joined inheritance arcs, where the notation joins them).
Status: enforced. Package containment draws a tree when every member sits in the next rank, and otherwise routes each branch from the shared anchor.
Put arrowheads where the notation says
Rule. Arrowheads, triangles, circles and sockets follow UML 2.5.1 for each relation: an open head for a dependency, a hollow triangle for generalization, a filled head for a synchronous message, the circle-plus on the owner of a containment.
Why. The notation is the meaning, so it is never traded for looks. See When rules conflict.
Source. UML 2.5.1.
Status: enforced, by an audit of every glyph against the specification and the glyphs in
core::glyphs.
Labels
Labels here are the text on lines: connector labels, keywords such as «import», transition triggers
and guards, message names. Names of boxes and containers are in Names and titles.
Keep a label beside its own line
Rule. A label sits next to a straight run of its own line, 6 to 8px from it, and close to the middle of that run.
Why. Closeness is what ties a label to its line (Gestalt proximity). A label far from its line has to be matched by searching.
diagram state "Labels beside their lines"
[*] --> Idle
Idle --> Busy : start [ready] / log()
Busy --> Idle : done
Source. Gestalt proximity; Kakoulis and Tollis 1997.
Status: enforced. A reserved state label sits 8px from its anchor
(Placement), and a state label placed after routing sits with its
ink 8px from its own segment. labels::Placer tries five positions along each segment, 6px off it, and
prefers the middle and longer runs. The quality test counts labels more than 12px from their own line.
Exceptions: a two-line label above a line in a rightward flow, whose upper line is 14px away, and a
self-transition label stacked under its loop.
Never leave a label between two lines
Rule. No other line may be as near to a label as its own line. A label that sits between two parallel lines must move, or one of the lines must.
Why. A label equally near two lines belongs to neither, and a reader guesses. This is the unambiguous reading rule, second only to notation in When rules conflict.
Bad: retry could belong to either line.
Source. Kakoulis and Tollis 1997 (a label must be associated with exactly one edge); drafting practice.
Status: partial. A state label placed after routing must be 12px nearer its own line than any other, or it keeps its reserved spot. The quality test counts every connector label with another line at least as near as its own. Not done: component and package labels are placed by fewest collisions and are not checked for this when placed.
Never let a label touch other ink
Rule. A label does not overlap a box, a name, another label or any line.
Why. Text over ink is hard to read, and a label on a line seems to belong to it.
Source. Purchase et al. 2002 (text legibility); Castelló, Mili and Tollis 2000.
Status: partial. Reserved state labels are obstacles for every line, so no line crosses them, and a state label placed after routing must clear every line, outline, arrowhead, shape and label. The quality test counts labels within 2px of a line or an outline, or on a shape or label. Not done: the placer for component and package labels takes the position with the fewest collisions, but cannot make room when every position collides.
Write labels horizontally
Rule. All text runs left to right, horizontally, including labels on vertical lines.
Why. 86% of subjects preferred horizontal labels in UML diagrams.
Source. Purchase, Allder and Carrington 2002.
Status: enforced. No text is rotated.
Put labels on a consistent side
Rule. In a diagram that flows down, a label sits right of its vertical line. In one that flows right, it sits above its horizontal line. A reverse pair between two items keeps both labels on the outside, so the two lines run close together.
Why. A consistent side lets the eye find each label without searching, and keeps lines and labels from interleaving.
Source. Drafting practice; a design decision of this project.
Status: enforced for state diagrams (label_side, order_label_sides). Component labels go right of
vertical runs and above horizontal runs. Package labels may also take the left of a vertical run, to
avoid a collision.
Reserve room for labels
Rule. The layout makes room for long labels before lines are routed, instead of hoping that a spot will be free afterwards.
Why. A placer that chooses among positions cannot make space, and fails on dense diagrams. Label dummies that take part in the layout guarantee room (dot, KLay).
Source. Gansner et al. 1993; Schulze, Wechselberg and von Hanxleden 2018; Castelló et al. 2000.
Status: partial. State transition labels are dummies in the layered layout (Placement). Component and package diagrams flowing right widen the rank gap by the label’s width. Elsewhere labels are placed after routing.
Never let a label force a bend
Rule. A label follows its line, not the reverse. A line should run as straight as it would without its label, and the label then takes a free spot beside it. When no spot is free, the label keeps its reserved place, and the line goes through it.
Why. Labels serve lines. A transition routed through its label’s reserved anchor jogs just to pass
it: with every label reserved, the lines of near target floor, speed zero, levelled at floor and
fully open in Elevator controller each jog for this reason alone.
Source. Purchase et al. 2002 (bends); Layout levers.
Status: partial, for state diagrams
(Labels after routing). The layout still reserves every
label’s room. Each line that bends is routed again without its waypoint, and its label is placed beside
the new line, on the segment and side that read best. A label keeps its reserved spot when no place is
clear, near (12px) and unambiguous, when its line gains no straightness, or when its line gains a
crossing. A diagram keeps the fully reserved drawing unless the result has fewer bends and no more
crossings, overlaps, merged ends or label flaws. Freed labels include motor overcurrent / cut power
(Elevator controller), close / send FIN (TCP connection) and wait(event) / block() (Process
lifecycle). Not done: near target floor keeps its spot, because right of its straightened line it
would lie on next call, and left of it on the region border. Component and package labels are already
placed after routing, so they never force a bend.
Names and titles
Names are the text that identifies a shape: a component’s or state’s name, a package’s name in its tab, the name beside an entry point. The diagram title is a caption. Labels on lines are in Labels.
Centre a classifier’s name, keyword above
Rule. A component, class, interface or other classifier shows its name centred in bold, with any keyword or stereotype centred in plain text above it, in guillemets. This includes a composite component, whose name is centred in its header.
Why. UML asks for it, and a centred name marks the box as one unit.
Source. UML 2.5.1, 9.2.4.1, p. 101: “The name of the Classifier should be centered in boldface”, with keywords “centered in plain face within guillemets above the Classifier name”.
Status: enforced in component and package diagrams.
Put a package’s name in its tab when it shows its contents
Rule. A package that shows its members carries its name, left-aligned, in the tab. A package without visible contents has a blank tab and its name in the body.
Why. UML specifies both cases. Readers find the name in the same place in every package.
diagram package "Names in tabs"
package Core {
class Order
class Invoice
}
package Util
Core ..> Util : <<import>>
Source. UML 2.5.1, 12.2.4, p. 248.
Status: enforced, in package diagrams and for packages inside component diagrams.
Keep lines off names
Rule. No line crosses a name, a keyword, a composite state’s internal activities, or a package tab.
Why. A line through text hides both. A line through a tab reads as entering the tab, which means nothing.
Bad: the arrow pierces Util’s tab to reach the body below it.
Source. Keep lines out of shapes and names.
Status: enforced. Composite names, state headers and tabs are obstacles for every line that enters their container. The levers study found that, as obstacles, they cost no bend.
Let arrows end on a package’s tab
Rule. A relation arriving at a package from above may end on the top of the tab, when that is where its straight line meets the package.
Why. The tab is part of the package symbol, so a line ending there points at the package. If the top side started right of the tab, a line that would arrive over the tab would jog sideways instead.
Source. UML 2.5.1, 12.2.4, p. 248 (the tab is part of the symbol); Layout levers.
Status: enforced for packages without visible contents, whose tab is blank (tab_takes_ends in the
package routing). An end on the tab stays 8px from its corners and 16px from the step down to the body.
The Relations and Package merge examples show it. A package showing its contents keeps its name in the
tab, so its top side still starts right of the tab.
Let a name give way to a line
Rule. Where the notation leaves the name’s position free, move the name aside instead of bending a line. A composite state’s name may sit left or right in its name compartment, or in a UML name tab, when an entry point or a straight line wants the middle. A classifier’s name stays centred, because 9.2.4.1 asks for it.
Why. The name can move without loss. The line cannot bend without cost: an entry point that slides off a centred name makes the transition into it jog.
Source. UML 2.5.1, 14.2.4.4, p. 319-320, which allows an optional name tab “resting on the outside of the top side of a State”; Layout levers.
Status: enforced for entry points on the top border of a composite state in a downward flow (name_place in the state layout): when the entry point that lines up with its target meets the
centred name, the name moves beside the entry point, 8px clear of its circle, on the side away from the
middle first, keeping 12px from the state’s sides. Only when neither side has room does the entry point
slide off the name instead. In the Entry and exit points example the chain Idle, again, Prompt
runs straight this way. The UML name tab is not used.
Keep connection point names beside their symbols
Rule. An entry or exit point’s name sits next to its circle, clear of the state’s own name, and the state’s name moves aside for the entry point, or, where it has no room, the entry point slides along the border off that name.
Why. Two names overlapping cannot be read, and a connection point name far from its circle is easily taken for the state’s.
Source. UML 2.5.1, 14.2.4.6, p. 327-328 (entry and exit points as circles on the border, “with the name associated with it”).
Status: enforced (name_place and clear_of_name in the state layout).
Caption the diagram, do not frame it
Rule. A diagram kind "Title" title is a caption above the drawing, outside its contents area.
There is no UML frame.
Why. A frame adds a box around every drawing and competes with the content. UML makes the frame optional, and drops its heading with it.
Source. UML 2.5.1, Annex A; a design decision of this project.
Status: enforced, by core::svg::document.
Flow and arrangement
Rules for the arrangement as a whole: which way the diagram flows, how boxes are ranked, ordered and lined up, and where notes go.
Flow one way
Rule. A diagram has one main direction, down or right, and most connectors point along it. Items sit in ranks across that direction, and a connector joins items in later ranks wherever possible.
Why. A single direction lets the reader follow cause to effect without turning the page. Purchase et al. ranked information flow third among UML layout preferences.
diagram component "One direction"
direction right
component Parser
component Checker
component Emitter
Parser --> Checker : AST
Checker --> Emitter : typed AST
Source. Purchase et al. 2002; Sugiyama et al. 1981 and Gansner et al. 1993 (layered drawing).
Status: enforced. Ranking assigns ranks. Component diagrams flow
right by default, and package and state diagrams flow down, because their long labels then sit beside
vertical lines. direction changes it.
Keep connected items close
Rule. Connected items sit in neighbouring ranks where the graph allows. A source pulls next to the first thing it feeds.
Why. Short edges need fewer dummies, fewer bends and less searching.
Source. Gansner et al. 1993 (minimising weighted edge length).
Status: partial. The default engine, longest-path, pulls sources next to their targets.
Network-simplex ranking, which minimises the weighted edge length, is a selectable engine
(layout network-simplex), not the default.
Order ranks to avoid crossings
Rule. Within each rank, items are ordered so that edges between ranks cross as little as possible. Hints and notes are part of the ordering, not applied afterwards.
Why. Most crossings are decided by the order, before any line is routed.
Source. Gansner et al. 1993 (weighted median, transpose).
Status: enforced within a container (Crossing reduction).
Order across containers too
Rule. The order of items inside a container should take the lines that leave the container into account.
Why. A container laid out on its own can put a child on the wrong side of its outside partners. The Order Platform drawing has its one crossing for this reason, and the Compiler pipeline has a jog between its two containers.
Source. Sander 1996; Forster 2002; Layout levers.
Status: planned, not scheduled. It needs a global layering across the hierarchy, which is a rewrite
of arrange.
Keep long edges straight
Rule. An edge that spans several ranks runs as one straight line, where both ends can take it. Where only one end can, it bends once, near the other end.
Why. Long edges that wander become spaghetti (Gansner et al.), and continuity helps path tracing (Ware et al.).
Source. Gansner et al. 1993; Ware, Purchase, Colpoys and McGill 2002.
Status: enforced, by the straightening step of Placement.
Align a pendant with what it hangs from
Rule. An item joined to the rest by a single chain, such as an initial state, a final state or a note-like leaf, sits in line with the item it hangs from, so the chain is straight.
Why. A short spur that jogs looks careless, and it is the easiest jog to remove.
diagram state "Pendants in line"
[*] --> Ready
Ready --> Done : finish
Done --> [*]
Source. Drafting practice.
Status: enforced, by the pendant step of Placement.
Keep a column
Rule. Items along the main flow sit centred over each other in one column, so the lines between them run straight down (or across, when the flow runs right). Side branches move out of the column; the main chain does not. The main chain is the longest path through the graph. Where a box has several onward branches of equal length, it stays centred over them instead, unless it is a decision, which keeps its first branch in its column (see Flow passes straight through a decision).
Why. A straight spine is read at a glance, and every jog in it reads as a turn in the story: in
Process lifecycle, New, Ready, Running and Zombie would each jog a little left of the one before.
diagram state "A column"
[*] --> Idle
Idle --> Busy : start
Busy --> Done : finish
Busy --> Failed : error
Failed --> Idle : retry
Done --> [*]
Source. Brandes and Köpf 2001 (vertical alignment of blocks); Ware et al. 2002 (continuity).
Status: enforced in state diagrams, partial elsewhere. Placement picks one column partner above and below each item and pulls partners onto one line ahead of anything else.
- State diagrams keep their columns unless they route with more crossings, overlaps or failed lines
than the layout without them (in Door, the line back from
ClosingtoClosedwould crosslock). A join bar, which has one line onward, passes the flow on into a column (Choice, fork, join:Doneand the final state sit under the join); a fork bar starts none, so its branches stay symmetric. - Component and package diagrams take the columns only when they route with fewer bends and nothing worse, so their own alignment is kept elsewhere. Line up the main branch carries the column across containers.
- The quality test counts boxes whose flow continues into a chain child with none in line.
Notes come last
Rule. Lay out the main elements and route their connectors first, as if there were no notes. Then put each note beside its element, in the element’s rank, on whichever side is free. A note never bends a main connector and never moves a main element out of its column. Only when neither side has room does it push the items beyond it in that rank outward.
Among the free places beside its element, a note takes the one in empty space: where it makes the drawing no wider or taller, and where no line has to pass it. A place before the element, against the flow, counts as well as one beside it.
Why. A note is a comment on the drawing, not part of it. A note that takes part in the layout can hold boxes apart and push a whole chain sideways.
Source. A design decision of this project.
Status: enforced in state and package diagrams (Constraint::Note in the layered layout, placed by
place_notes), and in activity diagrams (see Notes per diagram kind).
The quality test counts note distortion: boxes a note moves against the rest, and bends it adds,
compared with the same source drawn without notes. Not done:
- Component notes still take part in ordering (
Adjacent). Two component layouts that read well, Motor controller firmware and Storage engine, are as they are only because their notes push boxes apart, and drawing them without that push loses a straight line and a fan’s symmetry. - The choice of empty space: a note takes the first free side in its element’s rank. In LSM storage
engine the note belongs on top of
Write-Ahead Log, where the drawing has room.
Centre and balance
Rule. An item with several neighbours in the next rank sits centred over them. A rank is balanced around the items it connects to, and the layout is symmetric where the graph is.
Why. Symmetry has a measurable but smaller effect than crossings and bends (Purchase 1997), and it is what makes a tree look like a tree.
Source. Purchase 1997; Gansner et al. 1993; Brandes and Köpf 2001.
Status: partial. An order-preserving median solve aligns connected items. It is a heuristic: an item can sit off the line of what it connects to. Centre the parent moves parents over their children afterwards. Not done: network-simplex or Brandes-Köpf coordinate assignment.
Centre the parent
Rule. A box linked to several children further along the flow sits centred over them, at their median or mean across the flow, so its lines fan out evenly. Likewise a box fed by several parents sits centred under them. Moving a parent gives way to an alignment that matters as much: a lone connector already running straight between two middles. Where one of the children continues the main flow, the parent lines up with that child instead (Line up the main branch).
Why. A parent over one child alone makes the other branches run a long way round, and their lines crowd the labels beside them.
Source. Gansner et al. 1993; Brandes and Köpf 2001.
Status: partial. Alignment moves parents, with everything they hold, in component and package diagrams, counting families across containers. A centred family and a lined-up connector weigh the same, so neither is traded for the other. In state diagrams, the median placement centres a parent over equal branches, and Keep a column ranks higher: a parent in line with the child that continues its chain, and a decision, are not moved over the rest. The quality test counts boxes with two or more children in their own container, further along the flow, more than 4px from both the median and the mean (decisions and boxes in a column with one child excepted).
Line up the main branch
Rule. When the flow forks or merges at a box, the branch that carries the main flow runs straight and the others sit beside it; only a fan with no main branch is centred, symmetric. The main branch is, in order: the one branch on the longest path onward (or back, for a merge); else the one branch joined by a lone connector, whose ends can meet on one line; else, when a chain runs through the box (one box on its other side, and the box holds no others), the middle of the branches tied on the longest path, the first of two in order across the flow. Straightness means the connection points line up, not the box centres: a port that follows a line inside its component counts where that line runs. A box that moves to line up takes along the boxes it is already lined up with on its far side, so a straight chain stays straight while it moves.
Why. Without this rule the main flow is often not on one straight line: a box centred between its neighbours bends both of its lines, and the chain reads as unbalanced.
diagram component "One straight, one beside"
direction right
component Loader
component Stage
component Verifier { provides IVerify }
component Boot { requires IVerify }
component Image
Loader --> Stage
Stage --> Boot
Boot --> Image
Source. Brandes and Köpf 2001 (blocks aligned along their longest path); Ware et al. 2002 (continuity).
Status: enforced in component and package diagrams (Alignment). The layout with leaders lined up is kept only when it routes with no more failures, crossings and bends than the layout before alignment, and no more bends than the balanced fans of Centre the parent; otherwise the balanced fans are kept (Battery sensor node, Container runtime, Hexagonal service, Vehicle gateway). A container never leads by a chain through its middle. State diagrams keep columns in the layered placement instead (Keep a column).
Keep the spine on one line
Rule. The spine of a drawing is its longest chain of solid lines along the flow. The spine lies on one straight line from end to end, also where it enters and leaves a container: the port it enters by, the boxes inside, and the port it leaves by share that line. Boxes off the spine sit beside it. When two chains are equally long, the one that the source lists first is the spine. A line that leaves a spine box to the side gives the spine its facing side (Use a free side before you share one).
Why. The spine is what the reader follows first, and every jog in it reads as a change of subject.
In Order Platform, port api, API Handler, Outbox and port events belong on one line, with
Pricing Engine above or below. In state diagrams the same holds: in Choice, fork, join the initial
state, Ready, the choice, Done and the final state belong on one vertical line.
Source. Brandes and Köpf 2001; Ware et al. 2002.
Status: partial. Each of the following is kept only when it routes with no more failures, crossings and bends.
- Component diagrams: alignment sees a chain through a port as one chain. A line to a port that
delegates counts as a link to the box the port leads to, inside or outside (
bridged_links). After the boxes line up, a second pass lines up the line that leaves a spine port with a shared side beyond it. In Order Platform,Web Gateway, portapi,API Handler,Outbox, porteventsandEvent Busshare one line, andPricing Enginesits above. Two equal lines into a port still make a balanced fan. - State diagrams: a state moves under the line into or out of an entry or exit point, with the states lined up with it, and a fork whose branches all meet one join passes the column through, so the state after the join lines up with the state before the fork.
- Not done: when the spine and a branch inside the container are equally long, the branch inside wins
(Replicated state machine:
peersleavesConsensus Moduleat the bottom). A line that must turn back against the flow to stay on the spine (Partitioned Logto portsourcein Stream processor) is not part of it.
Keep a side branch close
Rule. A box beside the main branch sits at the smallest gap that its line, its label and its neighbours allow: one rank gap across the flow, not more. A branch is never pushed out to make a drawing symmetric that has no symmetric fan.
Why. A side branch far from the box it leaves makes a long line and an empty band, and the drawing
leans. In Secure boot chain, Kernel Image sits further down than its line needs.
Source. Purchase 1997 (edge length); compactness in When rules conflict.
Status: planned.
Group what belongs together
Rule. Containers hold their contents. Notes sit beside what they annotate. Unconnected siblings fold into a compact block instead of one long row. Orthogonal regions tile across the flow.
Why. Proximity groups things before any line is read.
Source. Gestalt proximity; UML 2.5.1, 14.2.4 (regions).
Status: enforced: Compound layout, the Note constraint
for notes (component notes: Adjacent), wrap_constraints for package siblings, and region tiling in
the state layout.
Honour hints over heuristics
Rule. A layout hint (left-of, above, align and the others) always wins over what the heuristics would choose.
Why. The author knows what the diagram is for. A hint is the one way to say so without coordinates.
Source. A design decision of this project; Layout hints.
Status: enforced. Constraints apply inside every ordering sweep and win over edges.
Draw the same input the same way
Rule. The same source always gives the same drawing, byte for byte, on every machine.
Why. A diagram in version control should change only when its source does, and readers should not have to find their way around a drawing again after an unrelated edit.
Source. A design decision of this project; the D2 TALA author’s caution about seed-dependent layouts.
Status: enforced. There is no randomness, no HashMap order in the output, and text is measured with embedded metrics. The golden tests check it.
Notes per diagram kind
The general rules hold everywhere. This page lists where a diagram kind adds rules or bends them. Component, package and state diagrams share the layered layout and router. Sequence and activity diagrams have layouts of their own, built so that most line rules hold by construction.
Component diagrams
Flow right, and leave room for the wiring
Rule. Component diagrams flow right by default. A rank gap grows to fit a connector’s label, and an assembly or wired connector’s ball, socket and arrow.
Why. Interfaces and their names sit along horizontal runs, where they have room.
Source. A design decision of this project.
Status: enforced (edge_spec in the component layout).
Keep a delegation straight, and line the outer box up with the port
Rule. A port with connectors inside its component lines up with them, so the delegation is straight. A port without them sits at the middle of its side. A box outside then moves across the flow to meet the port’s line where it can; otherwise the connector outside jogs once.
Why. Inner gaps are narrow, so a jog there crowds the contents. Outside there is room, and a box outside is usually free to move.
Source. Drafting practice; a design decision of this project.
Status: enforced, by Alignment: Client lines up with port kv
in Storage engine, and Telematics Unit with uplink in Vehicle gateway.
Draw ball and socket clear of names
Rule. The ball, the socket and the interface name sit on a straight run of the connector, clear of other labels and names. A name must be clear of every ball and socket, not only of its own, and must sit nearer to its own symbol than to any other.
Why. The glyph is notation. A name over it hides what it says.
Source. UML 2.5.1, 11.2.4 and 10.4.4.
Status: partial (draw_assembly and draw_wired choose a free straight run). Not done: an interface
name can still sit over another symbol’s ball, so it is hard to tell which name belongs to which symbol:
in the unconnected interfaces example,
IEncode lies on the IDecode ball.
Line up the interface symbols of one fan
Rule. When several interface connectors meet one component on one side, their balls and sockets sit on one line across the flow, at the same distance from that component.
Why. Symbols at different distances read as different kinds of connection. In the Several consumers example on the Interface page the lines are good, but the sockets and balls could all sit on one vertical line.
Source. Drafting practice.
Status: planned. Each connector places its symbol on its own longest free straight run.
Give an interface room
Rule. A socket, a ball or a ball and socket on a connector keeps at least 16px of plain line on each side, to the component (or port) it hangs off and to the bend where its straight run ends, so it reads as a symbol of its own with a visible stub each way. An interface connector also leaves a box or a port on a straight run of at least 16px before it turns.
Why. Glued to the box, the socket looks like part of the component’s outline. Nudging centres the middle run of a bent line in its gap, which without this rule can leave the glyph almost touching the box.
Source. Drafting practice.
Status: enforced where the router can give the room. Where a glyph’s segment is too short, its end gets a stem as long as the glyph and both stubs, and the line is routed again. Exception: where that route would cross or bend more, the shorter route stays, and the dependency arrow shortens before the stubs do.
Package diagrams
Draw containment as one tree
Rule. When every member sits in the next rank, an owner’s members hang from one trunk with the circle-plus on the owner. Otherwise each branch is routed from that shared anchor.
Why. UML draws membership as branching lines from one circle-plus (12.2.4).
Source. UML 2.5.1, 12.2.4, p. 248.
Status: enforced.
Fold unrelated siblings into a block
Rule. Four or more siblings with no relations or hints between them fold into a roughly square block of rows.
Why. One long row of unrelated packages wastes width and suggests an order that is not there.
Source. A design decision of this project.
Status: enforced (wrap_constraints).
State diagrams
Reserve label room and keep labels on the flowing side
See Reserve room for labels and Put labels on a consistent side. State diagrams are where labels matter most (Castelló et al.), and where they cost the most bends: Never let a label force a bend.
Draw self-transitions as compact loops away from the flow
Rule. A self-transition is a small loop on the side of the state away from the flow, with its label beside it. A hidden box keeps the state centred in its rank.
A loop also gives way to a line. When a transition could leave the state straight by the side the loop is on, the loop moves to another free side, and the transition takes the side. Two loops on one state take two different free sides, and a side with empty space beyond it comes first.
Why. A loop on the flowing side would collide with the transitions in and out. A loop that does not
give way forces a line round it: in Process lifecycle the syscall loop belongs on the left of
Running, so that wait(event) runs straight out to the right; in Circuit breaker the loop belongs on
the left of Closed, so that probe succeeded can enter on the right.
Source. Drafting practice; a design decision of this project.
Status: partial. The loop on the side away from the flow is enforced. Planned: giving way to a line,
and spreading two loops over two sides (in Transition labels, one of tick and drift could sit on top
of Armed).
Meet small symbols on their sides
Rule. A line into a final state, choice, junction or terminate symbol from a source that cannot line up with it meets the symbol’s facing side, as an L. Lines out of a choice fan from different corners.
Why. Lines meeting at one point of a small symbol merge into one ambiguous junction.
Source. UML 2.5.1, Figure 14.25; a design decision of this project.
Status: enforced.
Tile regions across the flow
Rule. Orthogonal regions sit side by side across the flow, with equal extent along it, separated by dashed lines.
Why. This matches Figures 14.9 and 14.10, and lets each region keep the diagram’s direction.
Source. UML 2.5.1, 14.2.4.3 and Figures 14.9 and 14.10.
Status: enforced.
Sequence diagrams
Sequence diagrams use a timeline layout: lifelines are columns, events are rows on the 8px grid, and there is no router.
Never cross a lifeline with text
Rule. A message label stays within one lifeline gap, the gap nearest the sender that fits it, and the columns widen until it fits.
Why. Text across a lifeline is cut by it, and a reader cannot tell which side it belongs to.
diagram sequence "Labels between lifelines"
actor User as u
participant API as a
participant DB as db
u -> a : place order
a -> db : insert(order)
db --> a : id
a --> u : confirmation
Source. Drafting practice.
Status: enforced. The quality test counts any label within 2px of a lifeline and allows none.
Keep labels off arrowheads and dots
Rule. A message label keeps 4px from the arrowhead it points at. A found or lost message’s stub is long enough to hold its label between the dot and the arrowhead, clear of both, and a creation message’s gap counts the new head’s half width.
Why. Text that touches the arrowhead reads as part of it, and the halo bites into the head.
Source. UML 2.5.1, 17.4.4.1 and Figure 17.11 (lost and found messages); drafting practice.
Status: enforced; the quality test counts labels within 2px of an arrowhead or dot.
Keep frame tabs and notes off execution bars
Rule. A fragment’s operator tab, or a note across lifelines, should not hide part of an execution bar.
Why. A bar cut by a tab or a note looks like an execution that stopped and started again.
Source. UML 2.5.1, 17.2.4 and 17.6.4.
Status: planned. Tabs sit at the frame’s corner, 12px left of the first lifeline’s bar, so a tab over an active bar hides a stretch of it. The quality test counts these cases.
Keep messages horizontal and time downward
Rule. Every message is a horizontal arrow, and later events are lower. Nested executions step right.
Why. That is the notation (17.4.4). Horizontal arrows keep the time order unambiguous.
Source. UML 2.5.1, clause 17.
Status: enforced. Consecutive one-line messages are 32px apart; the quality test counts any other gap between them with nothing drawn in between.
Activity diagrams
Activity diagrams use a structured-flow layout driven by the block tree, so lines are straight by construction and nothing is routed by search.
Keep the main flow on one axis
Rule. The flow that continues takes the straight axis. Side arms branch off and rejoin beside it, and a bypass runs on the right.
Why. The reader follows the main path down a straight line, and the exceptions read as detours.
Below, the [no] arm stops, so Ship and Invoice stay on the axis.
diagram activity "Main flow straight"
start
action "Receive order"
if "in stock" {
action "Ship"
} else "no" {
action "Cancel"
stop
}
action "Invoice"
stop
Source. Drafting practice; Ware et al. 2002 (continuity).
Status: partial. The axis stays straight. Not done: the statement after a branch whose siblings stop
waits below the tallest sibling, so the drop to Invoice is longer than the others. The quality test
counts such drops as uneven gaps.
Space a straight flow evenly
Rule. Consecutive nodes in a straight flow are 32px apart. A guard beside a drop adds the room it needs.
Why. Even spacing makes a straight flow read as one sequence, and a longer gap then signals something.
Source. Drafting practice.
Status: partial. Exceptions: a while loop’s merge and decision sit 24px apart and read as one test; a note rising over a decision lengthens the drop into it; a node with a taller note is centred in the note’s height; and the continuation after a branch whose siblings stop (above).
Keep branches close; notes go outside
Rule. Side-by-side branches sit as close to the main flow as their contents allow. A note on a node in a branch goes on the outer side of that branch, so it never widens the space between branches. A note in the branch on the main axis goes on the side away from the other branches when they all leave on one side, and otherwise keeps the side its flow has.
Why. A note between two arms pushes them far apart around an empty middle. In Firmware boot, the note
on Jump to application therefore sits on its left, away from the [else] arm on its right.
Source. A design decision of this project: Notes come last, applied to the activity layout.
Status: enforced. The split sizes its arms once to plan them, then again with each side arm’s notes on its outer side.
End note links on the shape
Rule. A note’s dashed link ends on the outline of the node it annotates.
Why. A link that stops short in white space does not say which node it means.
Source. UML 2.5.1, 7.4.4 (a note is attached by a dashed line).
Status: enforced: a note above a decision reaches the diamond’s outline, with one diagonal line from the note’s corner to the middle of the diamond’s upper edge (see Note links may be diagonal).
Put guards by the branch they guard
Rule. A guard sits at the start of its flow, by the corner where the flow leaves the decision. Arms that share one run keep their guard over their own drop.
Why. A guard read near the decision is matched to the right arm.
Source. UML 2.5.1, 15.2.4 (guards on outgoing flows).
Status: enforced. The quality test counts guards touching a flow, node, divider or other label, and allows none.
Draw a merge only where flows rejoin
Rule. A merge diamond or join bar is drawn only where at least two flows meet.
Why. A merge with one input is ink without meaning.
Source. UML 2.5.1, 15.3.3.
Status: enforced.
Background: the levers study
This page summarises a study that chose which layout improvements to build first. It is background for contributors; you do not need it to use drumlin. The study measured the layout of an earlier version, so its numbers describe that baseline, not today’s drawings. Every lever it recommended is now built, and the principles it backs say what drumlin does today.
What was measured
Three faults showed in the rendered component, package and state diagrams of the time:
- edge labels forced bends that were not needed;
- container and composite names blocked lines that could run straight if the name moved;
- some boxes were a little too small, so a connector jogged instead of running straight.
Each fix (a lever) was tested as a counterfactual over the 103 golden files of the time: its upper bound, which removes the cause outright, and a realistic variant that keeps every rule in the principles (no label touching ink or reading ambiguously, no arrow through a name, no two connectors merged). Crossings, overlaps and bends were counted with the same metrics the quality test uses, against a baseline of 5 crossings, 0 overlaps and 341 bends. The experiment code was not kept.
| Lever | Bends saved at the time | Became |
|---|---|---|
| Grow end boxes, up to 2 grid steps | 90 | Grow a box rather than bend a line |
| Grow end boxes, up to 4 grid steps | 128, with uneven rows | Not built |
| Corner inset of 8px on square boxes | 12 | Keep ends off corners |
| Arrows may end on a package tab | 6 | Let arrows end on a package’s tab |
| State names give way to entry points | 4 | Let a name give way to a line |
| State labels placed after routing | 26 | Never let a label force a bend |
| An L instead of a Z where the L is clear | 28 (counted by cause, not tested as a variant) | Prefer an L to a Z when the L is clear |
Rejected: dropping label reservation altogether (8 new crossings and many label collisions), shrinking the 16px gap between ends (two connectors then leave one point together), and moving the names of component composites (no gain, and UML 9.2.4.1 asks for them centred).
Labels
Component and package diagrams already placed labels after routing, so labels never caused a bend there. In state diagrams a label was a dummy in the layered layout, the line was routed through the label’s anchor, and every label was an obstacle for every other line. Routing freely saved many bends but added crossings, and placing the labels afterwards left one label in twelve colliding and one in five as close to a foreign line as to its own. The workable variant, a hybrid, frees a label only where it can be placed clear, near and unambiguous, and keeps the reserved drawing for any diagram where the result is worse. That is how Labels after routing works.
Titles
As routing obstacles alone, composite names and package tabs cost no bend at all. They cost bends only by narrowing the span of a side where ends may attach. Arrows ending on top of a blank package tab, and a composite state’s name moving aside for an entry point, recover most of that. Ignoring names outright is not drawable: arrows then pierce package tabs and run through state names.
Box size
For each line with bends, one end box grew by one to N grid steps toward the other end, into free space, when the totals got no worse and no two connectors merged. The diagram’s bounds did not change. Two steps added about 1.6% to the box area and was hard to notice; four steps saved more bends, but boxes in one rank visibly lost their common height. A smaller corner inset of 8px saved bends on square boxes; on rounded state corners it put the arrowhead on the curve. An 8px gap between ends let two ends meet.
The five crossings
The baseline had five crossings in three drawings:
| Drawing | Cause |
|---|---|
| Order Platform (two golden files) | A container orders its children without seeing the lines outside it, so Event Bus and Postgres sit in an order that makes Billing’s line cross the SQL dependency. |
| Compiler pipeline (two golden files) | The slot of invoke on Code Generator was ordered by the position of Driver before routing, though the route came down the other side. |
| Hexagonal service | Slots on the right side of Use Cases were in the wrong order for their routes. |
Box growth with the corner inset removed the Compiler pipeline crossings, and spreading ends in the order of their lines removed the Hexagonal service one. The Order Platform crossing remains: it needs ordering across containers (Order across containers too).
Images checked
Every variant was rasterized and looked at, not only counted. Freed labels straightened lines in Elevator controller and TCP connection, but some then lay on other lines or floated between two parallel returns, which is why the hybrid keeps those reserved. Arrows ending on a package tab read correctly; ignoring names let arrows pierce tabs. Every bend saved by box growth read better, but uneven heights showed at four grid steps. An 8px inset on a rounded state put the arrowhead into the corner, and an 8px gap between ends merged two connectors in Hexagonal service.
How layout works
This page describes how drumlin turns a parsed diagram into positions and lines: the steps of the layered layout for component, package and state diagrams, the separate layouts of sequence and activity diagrams, the layout engines, and how layout quality is measured. It is for contributors and curious readers. The drawing principles say what a drawing should look like; this page says how drumlin gets there, and each step links to the principles it enforces.
Three layouts
- Component, package and state diagrams share the layered layout and router described under
Steps, and the small adapter helpers in
src/diagrams/boxes.rs. Each kind keeps its own alignment, growth and routing stages. The first steps, up to placement, form a selectable layout engine. - Sequence diagrams use a timeline layout: steps resolve execution depth, columns are spaced from labels and frames, and rows follow the page. Nothing is routed.
- Activity diagrams use a structured-flow layout driven by the block tree, with one measure stage and
one place stage. In the measure stage each decision picks the arm that lies on its axis (
arm_plan): the one arm that continues, the body beside an empty arm, the one arm in the decision’s lane, or else the middle arm, the first declared of two. The other arms sit beside it in declared order and rejoin the merge from its sides, so the flow passes straight through both diamonds (see Flow passes straight through a decision). A fork with an even count of branches stays symmetric about its axis. Awhileloop returns along a column left of its body; when the body ends in a merge whose left corner no branch rejoins, the return leaves by that corner (see Take a return line around the outside).
Steps
The steps of the layered layout are described below in pipeline order: compound layout, ranking, crossing reduction, placement (with columns and notes), alignment, box growth, slots, routing, nudging, L over Z, and labels. Several steps (columns, alignment, box growth, labels after routing) route the diagram more than once and keep the better result.
Compound layout
Each container is laid out bottom-up as a layered graph of its direct children. An inner layout becomes one large item in its parent. Component boxes are sized before layout to their name, stubs and ports. A component diagram is also laid out with each side long enough for the connector ends the flow will put on it (24px apart, 32px for named lines, 16px from the corners), and that layout is kept when the other leaves an end nearer a corner than 16px or two ends nearer than 24px, and it routes no worse. See Leave room for what attaches and Group what belongs together.
Ranking
Connectors and hints assign each item a rank. Long edges get invisible dummy items that hold a lane through the ranks between. See Flow one way.
Hints come first, then connectors, and a connector that would close a cycle is turned round. The
default engine gives each item the rank after the furthest item that points to it, then moves an item
that nothing points to down next to what it points to (rank::assign_ranks). The network-simplex
engine solves the same problem for the least total weighted line length instead
(simplex::network_simplex); see Layout engines.
Crossing reduction
Weighted median sweeps reorder each rank, alternating down and up, and a transpose pass swaps neighbours while that removes crossings. The sweeps run twice, from the input order and from a depth-first order, so a tree starts without crossings, and the best ordering seen wins. Hints and notes are applied inside every sweep, so the ordering is scored as it will be drawn. See Order ranks to avoid crossings.
Placement
An order-preserving median solve aligns connected items and snaps everything to an 8px grid. The dummies of each long edge then line up where both ends can take the line, so it runs straight, or where one end can, so it bends only once. Edges between the same two items move as a block. Pendant items, such as an initial state above its first state or a final state below its last, move in line with what they hang from. State transition labels get a reserved place in the gap between ranks. See Keep long edges straight and Reserve room for labels.
Before that, each item may get a column partner above and below it (columns). Every edge between
neighbouring ranks of items is a candidate, scored by the longest path through it, and the best go
first: an item with several onward edges takes one only when its path is strictly the longest or the item
is a decision (Constraint::Pivot, which takes its first branch), two columns between the same ranks
keep the order of their ends, and a bar (Constraint::Spread) starts no column unless it has one edge
onward (a join). In the median solve a
partner’s position is the target, with a weight above everything else, and the dummies of the edge
between two partners follow it; afterwards each column moves onto one line where its rows have room
(hold_columns). A state diagram is laid out with and without columns and keeps them unless they route
with more crossings, overlaps or failed lines, first with every label reserved and, if that is worse,
with labels settled. Component and package diagrams keep columns only when they route with fewer bends
and no more crossings, overlaps, uncentred parents or cramped heads. See
Keep a column.
Notes
A note (Constraint::Note) takes no part in ranking, ordering or placement. It joins its anchor’s rank
for the rank’s depth only, and once everything else is placed (place_notes) it goes beside its anchor,
32px off, on a side where it keeps the item gap from every other item and the dummy gap from every long
edge in the rank; of two free sides the roomier wins. With neither free, it takes the side it misses by
less and pushes what lies beyond it outward. Component notes still use Adjacent. Note links are routed,
so other lines keep clear of them, and drawn as one straight line between the nearest points of note and
element (geometry::note_link). See Notes come last and
Note links may be diagonal.
Alignment
Component and package diagrams (core::align): after placement, boxes move across the flow, each with
everything it holds, in whole grid steps. A move is kept when it lines up more lone connectors or
centres more families than it costs; the two count alike. A lone connector is one whose two ends are
each alone on their side, or at a port: it lines up when both ends lie on one line, so it runs straight
between the middles of its sides. A port that follows a single connector inside its component counts as
part of the box that connector reaches, since it moves with it. A family is a box with two or more others
linked to it from one side along the flow, wholly before or wholly beyond it, in any container.
A family is centred on the member that leads it, when one does (align::families): the
one member on the longest path of links away from the box; else the one member joined to it by a lone
connector (then the connector alone lines it up and no family is counted); else, when exactly one box
lies on the box’s other side and the box holds no others, so that a chain runs through it, the middle
of the members tied on the longest path in their order across the flow, the first of two. Otherwise the
family is centred on all its members, within 4px of their median or mean, as a balanced fan. A led family
may also line up by moving the leader. A box may move together with the boxes its lined-up lone
connectors run on to, on its far side or its near side (train), so that a straight chain stays
straight while one end of it moves.
The links a family and its longest path follow see through ports (bridged_links): a line
to a port that delegates links the box on its far side, the one box the port leads to inside or the one
box beyond it outside. A chain that runs through a container by its ports is then one chain, and a box
inside may lead a family of a box outside. A member reached only through a port never wins a tie by the
chain-through rule, so two equal lines into one port stay a balanced fan (align::families_through).
After the first alignment, a second one adds a pull for each line that leaves a delegating port to a box
whose side it shares with other ends: the line lines up when the port meets that side anywhere its ends
may sit (a span, not a point), so the spine runs straight on beyond the container where that breaks
nothing lined up already.
A moved box pushes the neighbours in its way along with it, never comes nearer a neighbour than the 40px item gap (or the gap it already had), and stays inside its container’s content area; the root grows to hold what moved. Notes move with their anchors. No routing is needed for the moves. The diagram is then routed three ways: unaligned, aligned with leaders (trains allowed), and aligned with every family a balanced fan and boxes moving one at a time (alignment without leaders). Neither aligned layout may fail a route or add a crossing; the leaders’ layout may also add no bends and leave no more ends nearer than 16px to a corner of their box than the unaligned layout did, and where the leaders’ layout has more such ends than the balanced fans, the fans win. Of the two, the one with fewer bends wins; on a tie, both layouts are grown (Box growth) and the one with fewer bends after growth wins, the leaders on a further tie. See Meet the middle, Centre the parent and Line up the main branch.
State diagrams (routing::points_lined_up): after the column choice, a state moves across the
flow under a transition to or from an entry or exit point, and the state after a join lines up with the
state before its fork when every branch of the fork meets that join. Lines that already run between two
middles, and lines that meet a bar anywhere along it, hold. The moved layout is kept when it routes with
no more failures, crossings, overlaps or bends.
Box growth
Where a connector jogs because its end boxes miss each other by a step or two, core::grow grows
one end box by up to 16px on a side toward the other end, into free space, and routes the diagram
again. A growth is kept only when that connector loses a bend, no crossing, overlap or bend total
rises, and no two connectors come to leave one point together. Growth across the flow is tried
first, and only growth that lets the two boxes share a span is routed. See
Grow a box rather than bend a line.
Slots
Attachment points slide along box sides toward their peers. In component and package diagrams, an end
alone on its side sits at the middle instead, and nudging may not slide it; a port sits at the middle
unless connectors inside its component lead to it, and then lines up with them. Component ends that
share a side are spread evenly in their order and centred on the side as a group, unless that takes an
end off a straight line to another box. A container’s side that lines from its contents leave through
counts as shared. Ends are spread 16px from corners, and nudging may slide a shared end to 8px from a
square corner. A package without visible contents also takes ends on top of its blank tab. A component
container pads a side whose port takes an arrow from inside to 32px, to fit the head’s straight run. Ends
that share a left or right side are spread 32px apart where a line carries a name (NAMED_SLOT), else
24px. Groups are judged together: a group is centred when that keeps as many of its lines
straight as settling did, with the groups at the other ends of its lines centred too. A
stub that shares a side with lines goes to the end of the side its name faces (the top of a left or right
side, the right of a top or bottom side), leaving the middle to the lines.
Each end starts on the facing side (router::facing). One exception is made before
routing, in component diagrams (secondary_sides): a dashed dependency between two leaf components that
overlap across the flow, whose straight way runs through a box linked to neither end, and whose end shares
its side with another line or a stub, takes a free side across the flow (right, or bottom when the flow
runs right, unless taken). The solid lines keep the facing side, and the dashed line goes round outside
them. See
Give the main line the main side,
Meet the middle,
Spread and order attachment points,
Keep ends off corners and
Let arrows end on a package’s tab.
An end with an arrowhead, a triangle or a circle-plus gets a stem that reaches the decoration’s length
plus 8px from the box, on the grid (Terminal::reaching), and every later step keeps it. See
Leave room for the head.
Component interface connectors (a wired dependency, or ball and socket between ports) keep their glyph
CLEARANCE (16px) clear of both ends of the straight segment it sits on, and the glyph’s run
(glyph_run) is that clearance twice plus the glyph: 93px for a wired dependency at full length (socket
8px, dashed arrow 48px, ball 5px), 45px for ball and socket. Each interface end at a box leaves on a
run of at least 16px. The diagram is routed once like that. Each glyph whose segment is shorter than its
run, and is the first or last segment of its line, marks that end for a long stem reaching the whole run.
A second route then gives every marked end its long stem and every interface end at a port the 16px run
as well; it is kept when it has no more failures, crossings, overlaps or bends than the first. Otherwise,
if any end was marked, a third route tries the long stems alone under the same test, and failing that
the first route stays. Diagrams with neither marked ends nor interface ports route once, and
alignment, columns and box growth always compare layouts by the first route alone; only the drawn route
tries for more room. Trying beats a fixed rule because the router decides which of two lines in a
channel passes the other by its costs and order, and in Order Platform an 8px longer port stem was enough
to make two lines cross. The drawing places the glyph within the clearance where the segment allows, and
on a segment still too short it shortens the dependency arrow (down to 24px) before the stubs. See
Give an interface room.
Routing
A* runs over a sparse grid with costs for length, bends, crossings, shared lanes and travel along container boundaries. Three rip-up rounds settle conflicts. In state diagrams, each composite state that is not an end of a line gets a soft band 24px deep around it, which costs like a boundary to run along, so long lines keep their room (see Give long lines room). Component diagrams give the same band to every container a line does not end on, and to a container it reaches at a port. A choice or junction sends the branch whose target lies straight ahead out of its forward side (see Flow passes straight through a decision). See Draw lines orthogonally and Avoid crossings.
Nudging
Each segment then moves along its own axis to where its line overlaps, crosses, crowds and bends least, in that order, and never through a box, a reserved label or a container boundary. Two lines tangled in one channel move together. Jogs fold away where a straighter path is clear, and an end may slide along its side, between its neighbours, to straighten its line. Finally, the middle runs of Z-shaped lines that share a channel spread evenly across it, and a lone one sits in the middle of its gap. Last, where two lines that share an end part a few pixels apart, the line that runs on turns where the other turns. If lines still lie on top of each other after L over Z, which may free the room they were fighting over, they get one more nudge. See Never lay lines on top of each other, Space parallel lines evenly and One junction per merge.
L over Z
After nudging, a line shaped like a Z, whose two end runs are parallel, becomes an L when one of its
ends may move to the side of its box that faces the line: the first run continues past the box’s
corner and turns into that side. The same step looks at the last three runs at each end of
every longer line (tail_shapes): when the first of them is parallel to the last, so the line comes down
beside the box (a Z at the end) or past it (a U), and the run across starts beyond the box’s side, the
end moves to that side and the line loses one or two bends. A line never doubles back into a box where
the side it arrives from is clear (see Never double back into a box),
and a line that leaves a shared side and at once turns past the corner leaves by the side it turns toward
(see Use a free side before you share one).
Each line takes up to four such steps. Moving the start of a longer line is also refused when the line
would cross the boundary of a container on another side than before (a line that left its container
through the side facing its target keeps that side). Adapters say which ends may move by giving a terminal its box
(router::Body), with the sides it may take and, for a state with internal behaviours, the band under
its top that its left and right sides keep free of ends (Body::head, down to 16px below the compartment
line). Component ends may move on every leaf component, onto sides that hold no stub or port, on any
line but a note link, interface lines included. The L is kept only when it meets no obstacle or strip more than the Z did, its new end
keeps SLIDE_GAP from other ends on that side and 16px from the corners, it gains no overlap,
crossing or close run, and no two lines come to leave one point together. An end that lands alone on a
side must land at its middle. Among the Ls that pass, the best standing wins, then the end nearest the
middle of its side. Component and package diagrams (Problem::centred) also give every end its box: an
end left alone on the side the L left returns to its middle, and an L that would leave one off the
middle is dropped. There, an end alone on its side does not move when the far end shares its side.
Because it is part of router::route, box growth and the label hybrid see the L. See
Prefer an L to a Z when the L is clear.
Labels after routing
State diagrams (diagrams/state/hybrid.rs): after box growth, the diagram is routed with every label
reserved. Each labelled line that still bends is then freed: routed without its label’s waypoint, with
its label no longer an obstacle. Each freed label is placed beside its new line: five positions along
every segment, on both sides, ink 8px off the line, on a segment that reaches 8px past the label. A
place must touch no line, arrowhead, shape or label (4px air, 8px from other labels, 6px from outlines
and region dividers), stay inside the diagram, sit within 12px of its own line, keep the rest of its own
line as far, and keep every other line 12px further. The best place prefers the flowing side (right of
a vertical run when the flow is down, above a horizontal run when it is right), the middle of long runs,
and room from other lines. A label with no place, or whose line gains no straightness or gains a
crossing, is pinned back to its spot and the rest are routed again, up to four rounds. The result
replaces the reserved drawing only when it has fewer bends and no more crossings, overlaps, merged
ends, failed routes or label flaws (metrics::read_labels). Each round costs one route.
Labels
Component and package labels, and state labels with no reserved room, take the position with the fewest collisions. See Labels.
Layout engines
The steps from compound layout to placement form a layout engine, which component, package and state diagrams can swap. Everything after placement, from alignment to labels, and the drawing itself, is the same for every engine, so two engines can be compared on one file and in the quality measures.
- What an engine is. An entry in
ENGINESinsrc/diagrams/engine.rs: a name, one line on what it does, and acore::layered::Strategy, which picks the method of each layered stage that has a choice. Today only ranking has one:Ranking::LongestPath(rank::assign_ranks) orRanking::NetworkSimplex(simplex::network_simplex).coreknows no engine names; the names and their mapping to strategies live indiagrams. - The engines.
longest-path, the default: longest-path ranks, median ordering and placement, columns and notes last, as described above.network-simplex: ranks that make the total line length as short as possible, then the same steps. Try it when a box hangs far above the boxes it points to. - Network simplex ranking. Gansner, Koutsofios, North and Vo (1993), section 2: minimise the sum of
weight times length over the edges, each at least one rank long. Both rankings work on the same pairs
(
rank::oriented): same-rank groups are one node, a hint pair weighs 0 (it orders but does not pull), a connector’s weight counts (4 for state transitions from an initial state or to or from a bar), and a pair that would close a cycle is turned round in the same order, so both engines agree on which edges point back. Longest path is the feasible start; a tight spanning tree, cut values and leave/enter pivots follow until no cut value is negative, at most64 + 16 * pairspivots. Each connected part is solved alone and starts at rank 0. Where longest path is already optimal its ranks are kept, so the engines differ only where network simplex shortens lines. The paper’s balancing step is left out (it broke parallel columns in the one diagram it changed). On the golden files and the book’s diagrams longest path is already optimal, so both engines draw them the same. - Selection. The parser stores the engine of a
layout <name>statement in the diagram (Diagram::engine, the default when there is none).drumlin::render_withandcheck_withtakeOptions { layout }, which the CLI fills from--layout; each kind’sdrawingreplaces the diagram’s engine with a chosen one, so the option wins. Each kind’s layout adapter builds itsGraphwithstrategy: d.engine.strategy. No global state carries the choice. Sequence and activity diagrams reject both. The mdBook preprocessor needs nothing more: a code block picks an engine with the statement. - Adding an engine. Write the stage’s method in
core::layered(a ranking function besideassign_ranksinrank.rs, returning ranks from 0 with each same-rank group sharing one), add a variant to that stage’s enum (Ranking) and its arm inrank::ranks, then add oneEngineentry toENGINES. A stage that gains its first choice (coordinate placement, for Brandes-Köpf or simplex coordinates) gets a field inStrategyand amatchwherearrangecalls it. An engine that replaces the whole layered layout would makeEngine::strategyan enum with a variant for it, matched in each kind’s layout adapter (layoutsfor component and package,settle_regionsfor state), and return the samelayered::Layout, so the steps after placement stay unchanged. The default engine must keep the golden files byte-identical. - Comparing engines.
DRUMLIN_ENGINES=all cargo test --release --lib compare_engines -- --nocapture(or a comma-separated list of names) prints every component, package and state table below once per engine, then each total side by side with its budget. The budget tests always measure the golden files as written, so the default engine’s budgets are enforced unchanged. SetDRUMLIN_ENGINE=<name>to runexplain_ends,explain_labels,explain_flow,explain_sizeordump_lineswith another engine, and usedrumlin render --layout <name>to look at a drawing.
Measuring quality
The quality test in src/diagrams/quality.rs measures every golden file and holds each total to a
budget: a change that raises a total fails the test, and a change that improves one lowers the budget.
Run cargo test --lib quality -- --nocapture to print the tables and the current totals.
For component, package and state diagrams it counts crossings, overlapping runs, bends and merged ends (two connectors leaving one point together). It also measures how big every drawing is (see the size measures below).
The same test reads every connector label in those files (core::metrics::read_labels): labels within
2px of a line, outline or arrowhead, labels on shapes or other labels, labels with another line at least
as near as their own (ambiguous), labels more than 12px from their own line, and the summed distance
from each label to its own line. Each kind builds this as a Scene with owners in
src/diagrams/<kind>/scene.rs, from the parts src/diagrams/connectors.rs assembles. Interface names on assembly connectors read with their ball and count
only as text to keep clear of. Set DRUMLIN_LABELS=state/<name> and run the explain_labels test to
list the flaws in one golden file.
Sequence and activity diagrams have no router, so the same test measures their whole drawing instead.
Each kind describes its output as a Scene (src/diagrams/<kind>/scene.rs): connectors, opaque shapes,
shapes drawn under them, strokes text must avoid, free text, contained text and gaps meant to be equal.
core::metrics::assess then counts, per kind, only what layout decides:
| Count | Sequence | Activity |
|---|---|---|
| Crossings and overlapping runs | between messages | between flows and note links |
| Bends | not counted: a self message always has two | every flow |
| Lines through shapes | messages through heads, notes, refs, tabs | flows through nodes and notes |
| Shape overlaps | tabs or notes over execution bars, shapes on shapes, shapes across frame edges | nodes and notes on each other or across partition dividers (fork bars may span) |
| Labels on lines | message labels and guards within 2px of a message, lifeline, frame edge, arrowhead or dot | guards within 2px of a flow, link, divider or arrowhead |
| Labels on shapes and labels | against heads, bars, notes, refs, tabs | against nodes, notes, lane heads |
| Text overflow | names in heads, note and ref text, operators in tabs | names in nodes, note text, lane names |
| Uneven gaps | rows of consecutive one-line messages with nothing between | straight drops from node to node, except into a merge or bar |
Messages crossing lifelines and bars are the notation, so they are not counted. Diamonds and circles
count as the largest square inside them, because flows end on their outline. A gap is uneven when it
differs from the most common gap by more than half a grid step. Set DRUMLIN_SCENE=activity/<name> and
run the explain_scene test to list what was counted in one golden file.
The same test counts, per kind, the end measures of core::ends on a Figure that the same
scene.rs builds: ends alone on their side but more than
4px from its middle (ports and stubs count as ends), pairs of lines that share an end and part less than
24px apart, boxes with two or more children in their container that are not centred over them, and
heads or start decorations on a run shorter than their length plus 8px. Decisions, and boxes in a column with one of their children, are not counted as uncentred. Set
DRUMLIN_ENDS=component/<name> and run the explain_ends test to list them in one golden file.
The flow measures of core::flow read the same figure: boxes whose flow continues into chain children
(a link from a box with one forward child, or to a box with one forward parent, or from a decision) with
none of them within 4px of its centre line, and the summed offsets; pairs of a line and a shape it runs
beside, inside or outside, for more than 8px, closer than 16px (24px for containers); and decisions where
no line leaves opposite a line that arrives. Note distortion draws each golden file again without its
notes and counts boxes that moved by more than 4px against the median move, and bends the notes added.
Activity diagrams get the decision and note counts too. Set DRUMLIN_FLOW=state/<name> and run the
explain_flow test to list the flaws in one golden file.
The size measures (core::metrics::size) cover all five kinds. Störrle (MODELS 2014, ESEM 2016)
reports that a diagram’s size hurts readers more than its layout flaws, and every count above can stay
the same while a drawing grows. Per golden file, and totalled per kind:
- Line length: the summed length in pixels of every line the other measures read (for component, package and state every routed connector, note links and self-transitions included; for sequence the messages; for activity the flows and note links), each segment at its straight length, rounded once per drawing.
- Area: the width times the height of the SVG document, as its
widthandheightattributes give it, margins and title included: the space the drawing takes on a page. - Too wide: the drawings wider than 732px, the book’s 750px content column less the figure’s padding and border, which the book scales down. The widest drawing of each kind is printed too.
Each total has a budget. The test prints only the drawings wider than the column; set
DRUMLIN_SIZE=state to list every state drawing’s line length, frame, area and aspect, or
DRUMLIN_SIZE=state/<name> to list the length of each of its lines as well, and run the
explain_size test. On the golden files both engines give equal totals; on a source where network
simplex moves a box, the line length falls (network_simplex_draws_shorter_lines_where_the_engines_differ).
Style rules
These are stated with their reasons in Shapes and spacing.
- Every box and line coordinate sits on an 8px grid.
- Lines are orthogonal. Their bends are sharp in every style.
- One ink colour and a white fill. In
pens, three pen weights by the role of each mark; inplain, one line weight. - Text widths come from embedded Helvetica metrics, so layout needs no font
files and is identical on every platform. The
letteringstyle measures with the advance widths of its own glyphs instead.
pens and plain never move a mark. Layout runs before they are consulted; rendering receives the
diagram’s one core::style::Style (from a style <name> statement, or Options { style }, which the CLI
fills from --style and which wins) and asks it for three things: the class of each mark from its
Role (container, box, line, dashed line, head, note, rule, frame and so on), the path data of a
connector, and the stylesheet. drumlin render --style plain reproduces drumlin’s output from before
styles existed byte for byte; the golden test keeps a few such files under tests/style/plain. The
pens stylesheet is scoped under .drumlin.pens, more specific than plain’s .drumlin, and sets every
property plain sets, so drawings in both styles can share one page.
lettering is the one style that reaches layout. Each kind’s render wraps layout and rendering in
core::text::with_face, which sets the face of the drawing for the thread; every text measure
(text::width, small_width, name_width, wrap) asks the face, so box sizes, label boxes, note
wrapping and the title width come from the lettering’s advance widths without passing the style to each
measure. Outside that scope, and in pens and plain, the face is Helvetica and the measures are the
ones drumlin always had. core::svg::text then draws a run as core::lettering::run: a group with
role="img" and the text as aria-label, holding one <use> per letter of a glyph defined once per
size in the drawing’s <defs> (ids dl- plus the hand and the code point, so drawings on one page that
share a glyph share an identical definition). Names and the title are in spaced capitals, keywords and
small text in mixed case, inclined lettering is a 15 degree shear, and a halo is a white band under the
letters. The glyph data, core/lettering/glyphs.rs, is derived from Routed Gothic by Darren Embry and is
under the SIL Open Font License 1.1; the expected drawings are under tests/style/lettering, and
lettering_text_fits_its_boxes checks every golden source drawn in lettering for text that sticks out of
its box or note.
The study that chose the first of these steps to build is summarised in Background: the levers study.
Rendering at docs build time
No diagram in this book is a checked-in image. Authors write a fenced code block, and a preprocessor replaces it with inline SVG while the book builds. This page shows how to write such a block and how to build the book, for contributors and for anyone who wants the same setup in their own mdBook.
How to write one
Use a code fence with the language drumlin:
```drumlin
component Client { requires IGreeting }
component Server { provides IGreeting }
```
The page then shows the source and this diagram:
Fence options
| Fence | Output |
|---|---|
```drumlin | Source, then diagram |
```drumlin,render-only | Diagram alone |
```drumlin,error | Source, then drumlin’s real error message |
Set up
The preprocessor is a small Rust program that links drumlin as a library.
# book.toml
[preprocessor.drumlin]
command = "mdbook-drumlin"
cargo install --path docs/mdbook-drumlin --locked
mdbook build docs
Why render during the build
- Examples cannot go stale. Each image always comes from the source beside it.
- A broken diagram breaks the build. A parse error stops
mdbook build. So does adrumlin,errorexample that parses successfully. - Error messages stay honest. The Errors page shows output captured at build time.
- Pages need no client-side rendering. Readers get plain SVG with no JavaScript.
- The result is static. The built book is plain HTML and SVG, which any web server can serve. The
repository’s
Dockerfilebuilds it.
Roadmap
What drumlin does today, what is planned, and the known limitations of each diagram kind. Check here before you report a drawing as a bug.
| Area | State |
|---|---|
| Component diagrams, with interfaces, ports and delegation | Prototype |
| Packages as containers | Prototype |
Package diagrams with «import», «merge» and containment | Prototype |
| Sequence diagrams with fragments, activations, creation and destruction | Prototype |
| State diagrams with composite states, regions and pseudostates | Prototype |
| Activity diagrams with decisions, loops, forks, signals, objects and partitions | Prototype |
| Notation audit against UML 2.5.1 | Done for all five kinds |
| JSON diagnostics | Under consideration |
Selectable layout engines (layout statement, --layout) | Done: longest-path, the default |
| Network simplex ranking as a second engine | Done: network-simplex, opt-in |
Drawing styles (style statement, --style) | Done: pens, the default, and plain |
| A lettering style: single-stroke technical lettering with its own text metrics | Done: lettering, opt-in |
| Cross-axis alignment: the main branch of a fork or merge runs straight | Done for component and package diagrams |
| Exit sides: no doubling back, a free side before a shared one, dashed lines and returns round the outside | Partial: after routing in component, package and state diagrams; dashed lines in component diagrams; loop returns in activity diagrams |
| Box growth by four grid steps, ordering across containers (see the levers study) | Not scheduled |
| Rules marked planned in the drawing principles | Not scheduled |
Known limitations
All kinds:
- No diagram has a UML frame, such as
sdorpkg. UML makes the frame optional, and a title is a caption outside the drawing. - Builds have been tested only on Linux so far.
- In the
letteringstyle, text is drawn as pen strokes, with the words as invisible text over them for selecting and searching. A selection is highlighted in the viewer’s sans-serif squeezed to the run’s width, not traced around the strokes. Characters without a glyph (anything beyond Latin-1, Latin Extended-A in part, common punctuation, arrows and super- and subscript digits) are drawn as an open box, though the invisible text still holds them. Files are about three to four times the size of the same drawing inpens.
Component, package and state diagrams:
- Coordinates come from median placement, not an optimal solve, so an item can sit off the line of what it connects to, and the connector then bends. Alignment afterwards lines up the main branch of each fork or merge in component and package diagrams, but only where that adds no bends: a line whose end shares a box side with another keeps the slot offset as a jog, unless the line then turns off to a free side after routing (Container runtime). A fork’s branches in a state diagram are centred on the fork, not on the column through it. Reserved labels can force a long edge to bend around them.
Component diagrams:
- Interface inheritance (
^), port type labels, several interfaces on one lollipop and the optional compartments of a component are not expressible. All are optional in UML. - Connectors sometimes carry a small jog near a box corner. A route can go around a composite’s name.
- An interface glyph keeps 16px of line on each side unless the room for it would make the route cross or bend more; it then sits closer, with a shorter dependency arrow. A line passing a leaf component keeps only the router’s usual distance from it; beside a container it keeps 24px.
- Exit sides change after routing. Alignment compares its layouts by routed bends, which include the turns, but it lines up only lines whose ends are alone on their sides before routing. A free side is used only by turning the start of a line that already bends; a line that could run straight from a free side is not moved there.
Package diagrams:
- Classifiers have no bodies, so attributes and operations cannot be listed.
- A dependency arrow between packages that do not overlap across the flow carries one jog.
Sequence diagrams:
- Gates and coregions are optional UML notation and are not drawn; found and lost messages and
parcover the need. - Lifeline heads are not repeated at the bottom.
- A fragment’s operator tab can hide part of an active execution bar on the first lifeline it covers, and a note across several lifelines hides the bars under it.
State diagrams:
- Long edges in dense machines may still bend around other transitions’ labels.
- Labels of several self-transitions on one side are stacked and offset, which makes them harder to match to their loops.
- A self-transition’s loop always takes the side away from the flow, even when a transition could
run straight from that side, so Process lifecycle’s
wait(event)and Circuit breaker’sprobe succeededstill go round. - Local transitions are drawn on the right side of a composite.
Activity diagrams:
- Flows are block-structured, so unstructured flows cannot be written.
- Interruptible regions, pins, exception handlers, activity parameter nodes and hierarchical partitions are not drawn.
- The next statement after a side arm that stops still waits below that arm, because rows are shared.
- A note above a decision lengthens the flow into it, so a straight flow is not evenly spaced there.
- When branches stack because one crosses lanes another occupies, a flow can cross the stacked branch (Branches that interleave lanes).