Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Concept · 20 min · revision 1

Deployment and dynamic views, and where UML still helps

Add the runtime picture to a C4 model: deployment views that place container instances on infrastructure for each environment, dynamic views that number the steps of one scenario, and UML-style sequence and state diagrams for timeouts, races and lifecycles.

Contentsand lesson path

What you will learn

  • Add deployment and dynamic views (C4 or UML sequence and state diagrams) where static structure alone does not explain runtime behavior.

01. Why it matters

The context, container and component views from the previous lesson show what exists and who talks to whom. They are static views: they leave out time and place. They cannot tell an on-call engineer how many copies of the Booking API run in production, or which managed service holds the trips. They cannot show a reviewer the order of calls when a rider requests a ride. And they say nothing about what happens when a driver ignores an offer, or which states a trip may move between.

Those are different concerns, held by different readers, so they need different kinds of diagram. The C4 model adds two supporting views for runtime questions, the deployment view and the dynamic view. Its own guidance also says to borrow UML state diagrams, timing diagrams and similar notations where they say something better. This lesson covers all three, using the ride-booking model you already have.

02. Deployment views: one per environment

A deployment view shows where instances of your software run in one environment, such as staging or production. C4 deployment views use four kinds of element; the ride-booking model needs the first three:

  • A deployment node is somewhere software runs: a phone, a virtual machine, a Kubernetes cluster, a pod, a managed database service. Nodes nest, from region down to pod, and a node can carry an instance count.
  • An infrastructure node is part of the platform that is not one of your containers, such as a load balancer, a DNS service or a firewall.
  • A container instance places one container from the model on a node. The container is defined once; each environment decides how many copies run and where.
  • A software system instance places a whole software system on a node without opening it up, for example a neighbouring system that runs in the same data centre. Use it when the reader needs to know where another system runs, not what is inside it.

Because the containers are defined only once, staging and production can look completely different without copying the model. Add the lines below to the lesson 2 file, inside the model block after the last relationship. Staging is one virtual machine running everything with Docker Compose. Production spreads the stateless services over Kubernetes pods, puts the data stores on managed services and adds a load balancer that only production has.

Structurizr DSL · workspace.dsl, lines 105–154 (end of the model block)
        staging = deploymentEnvironment "Staging" {
            deploymentNode "Staging VM" "One virtual machine." "Ubuntu 24.04, Docker" {
                deploymentNode "Docker Compose" "Runs deploy/compose.yaml." "Docker" {
                    containerInstance api
                    containerInstance dispatch
                    containerInstance gateway
                    containerInstance tripDb
                    containerInstance locStore
                    containerInstance queue
                }
            }
        }

        production = deploymentEnvironment "Production" {
            deploymentNode "Rider's phone" "Rider's own device." "iOS or Android" {
                containerInstance riderApp
            }
            deploymentNode "Driver's phone" "Driver's own device." "iOS or Android" {
                containerInstance driverApp
            }
            deploymentNode "Agent's PC" "Support office computer." "Web browser" {
                containerInstance console
            }
            deploymentNode "Cloud region" "One region, three zones." "Public cloud" {
                lb = infrastructureNode "Load balancer" \
                    "Terminates TLS, routes /api and /ws." "Managed L7 load balancer"
                deploymentNode "Kubernetes" "Runs the stateless services." "Managed" {
                    deploymentNode "booking-api" "Pod" "Docker" "" 3 {
                        apiPod = containerInstance api
                    }
                    deploymentNode "dispatch-worker" "Pod" "Docker" "" 2 {
                        containerInstance dispatch
                    }
                    deploymentNode "location-gateway" "Pod" "Docker" "" 2 {
                        gatewayPod = containerInstance gateway
                    }
                }
                deploymentNode "PostgreSQL" "Primary and standby." "Managed, v18" {
                    containerInstance tripDb
                }
                deploymentNode "Redis" "Rebuilt from GPS updates." "Managed, v8" {
                    containerInstance locStore
                }
                deploymentNode "RabbitMQ" "Three-node cluster." "Managed, v4" {
                    containerInstance queue
                }
                lb -> apiPod "Forwards API requests to" "HTTPS"
                lb -> gatewayPod "Forwards WebSocket connections to" "WSS"
            }
        }

To review a deployment view as text, export the model to JSON and print each environment as a tree of nodes, with the containers that run on them. The script follows the children of each deployment node, which is how the JSON export nests them.

Python 3.12 · deployment_tree.py
"""Print the deployment nodes of each environment as an indented tree."""
import json
import sys
from pathlib import Path


def walk(node: dict, names: dict, depth: int) -> None:
    pad = "  " * depth
    count = node.get("instances", "1")
    times = f" x{count}" if count != "1" else ""
    print(f"{pad}{node['name']} [{node.get('technology', '')}]{times}")
    for infra in node.get("infrastructureNodes", []):
        print(f"{pad}  {infra['name']} (infrastructure: {infra['technology']})")
    for instance in node.get("containerInstances", []):
        print(f"{pad}  -> {names[instance['containerId']]}")
    for child in node.get("children", []):
        walk(child, names, depth + 1)


def main(path: str) -> None:
    model = json.loads(Path(path).read_text(encoding="utf-8"))["model"]
    names = {c["id"]: c["name"] for s in model["softwareSystems"]
             for c in s.get("containers", [])}
    for env in sorted({n["environment"] for n in model["deploymentNodes"]}):
        print(f"== {env}")
        for node in model["deploymentNodes"]:
            if node["environment"] == env:
                walk(node, names, 1)


if __name__ == "__main__":
    main(sys.argv[1])
Terminal
java -jar "$STRUCTURIZR_WAR" export -workspace workspace.dsl -format json \
  -output build > export.log && python deployment_tree.py build/workspace.json
Expected output
== Production
  Rider's phone [iOS or Android]
    -> Rider app
  Driver's phone [iOS or Android]
    -> Driver app
  Agent's PC [Web browser]
    -> Support console
  Cloud region [Public cloud]
    Load balancer (infrastructure: Managed L7 load balancer)
    Kubernetes [Managed]
      booking-api [Docker] x3
        -> Booking API
      dispatch-worker [Docker] x2
        -> Dispatch worker
      location-gateway [Docker] x2
        -> Location gateway
    PostgreSQL [Managed, v18]
      -> Trip database
    Redis [Managed, v8]
      -> Location store
    RabbitMQ [Managed, v4]
      -> Ride request queue
== Staging
  Staging VM [Ubuntu 24.04, Docker]
    Docker Compose [Docker]
      -> Booking API
      -> Dispatch worker
      -> Location gateway
      -> Trip database
      -> Location store
      -> Ride request queue

The tree answers questions the container view deliberately leaves out: three API pods behind one load balancer, a database with a standby, a three-node broker cluster. It also shows what staging cannot test, such as load balancing and failover between zones, which is worth knowing before anyone says "it passed in staging". Draw what operations people need to reason about failures and capacity. Subnets, IP ranges and node sizes belong in your infrastructure code unless a particular reader, such as a network security reviewer, needs them.

03. Dynamic views: one scenario, numbered

A dynamic view tells the story of one scenario, such as a use case or a feature, as numbered steps between elements of the static model. The view below and the two deployment views go in the views block, after the component view. Each step reuses a relationship that already exists, with a description that fits this story. Structurizr enforces that rule. If you add the step dispatch -> maps "Estimates the pickup time", validation fails with A relationship between Dispatch worker and Maps platform does not exist in model. Either the worker really calls the maps platform and the static model is missing an arrow, or the story is wrong. Both are worth finding out before a reviewer does.

Structurizr DSL · workspace.dsl, lines 170–189 (dynamic and deployment views)
        dynamic rides "RequestRide" "Rider requests a ride; a driver gets an offer." {
            riderApp -> api "Requests a ride from pickup to drop-off"
            api -> maps "Gets the route distance and time"
            api -> payments "Authorises the quoted fare"
            api -> tripDb "Saves the trip as REQUESTED"
            api -> queue "Publishes the ride request"
            dispatch -> queue "Takes the ride request"
            dispatch -> locStore "Finds online drivers near the pickup"
            dispatch -> push "Sends the offer to the nearest driver"
            push -> driverApp "Shows the offer for 15 seconds"
            autolayout lr
        }
        deployment rides staging "Staging" {
            include *
            autolayout lr
        }
        deployment rides production "Production" {
            include *
            autolayout lr
        }

C4 dynamic diagrams can be drawn in a collaboration style, with boxes placed freely and numbered arrows, or in a sequence style, with one lifeline per element. Both show the same information. Exporting the view in the WebSequenceDiagrams text format shows the sequence style without rendering anything:

Terminal
java -jar "$STRUCTURIZR_WAR" export -workspace workspace.dsl \
  -format websequencediagrams -output build > export.log
cat build/structurizr-RequestRide.wsd
Expected output
title Dynamic View: Ride Booking System\nRider requests a ride; a driver gets an offer.

participant <<Container>>\nRider app as Rider app
participant <<Container>>\nBooking API as Booking API
participant <<Software System>>\nMaps platform as Maps platform
participant <<Software System>>\nPayment provider as Payment provider
participant <<Container>>\nTrip database as Trip database
participant <<Container>>\nRide request queue as Ride request queue
participant <<Container>>\nDispatch worker as Dispatch worker
participant <<Container>>\nLocation store as Location store
participant <<Software System>>\nPush service as Push service
participant <<Container>>\nDriver app as Driver app

Rider app->Booking API: Requests a ride from pickup to drop-off
Booking API->Maps platform: Gets the route distance and time
Booking API->Payment provider: Authorises the quoted fare
Booking API->Trip database: Saves the trip as REQUESTED
Booking API->Ride request queue: Publishes the ride request
Dispatch worker->Ride request queue: Takes the ride request
Dispatch worker->Location store: Finds online drivers near the pickup
Dispatch worker->Push service: Sends the offer to the nearest driver
Push service->Driver app: Shows the offer for 15 seconds

Use dynamic views sparingly, as the C4 guidance advises: for the few flows that are complicated, that recur, or that people keep getting wrong. Ride requests qualify. "Support agent searches for a trip" does not, because the container view already makes it obvious. Each extra view is one more thing to keep true.

04. Where UML still helps

C4 is deliberately about structure. The dynamic view above shows the happy path, but the hard questions in this system are about time. What if the driver does not answer? What if the answer and the timeout arrive at the same moment? UML, the Unified Modeling Language (version 2.5.1 from the Object Management Group), has two diagram types with precise rules for exactly this.

A UML sequence diagram can wrap messages in combined fragments: loop for repetition, alt for alternatives with conditions, opt for an optional part, par for parallel work, break for leaving early. Mermaid, a text format that many code hosts render, supports these as sequenceDiagram. The diagram below shows the offer loop that the dynamic view hides.

Mermaid · offer-timeout.mmd
sequenceDiagram
    participant W as Dispatch worker
    participant DB as Trip database
    participant P as Push service
    participant D as Driver app
    participant API as Booking API
    loop up to 3 nearest drivers, until one accepts
        W->>DB: set OFFERED to this driver, expires in 15 s
        W->>P: send the offer
        P-->>D: show the offer
        alt driver accepts within 15 s
            D->>API: accept the offer
            API->>DB: set ACCEPTED if still OFFERED to this driver
            API-->>D: 200, trip confirmed
        else no answer within 15 s
            W->>DB: set REQUESTED if still OFFERED to this driver
        end
    end
    opt nobody accepted
        W->>DB: set EXPIRED
    end

Read the two updates marked "if still OFFERED to this driver". The driver can tap accept in the same instant that the 15 seconds run out. Without the condition, the worker could move the trip back to REQUESTED and offer it to someone else while the first driver is already on the way. A condition on each update means only one of the two can succeed. This kind of race is invisible on a container diagram, and it is exactly what a reviewer should see before the code is written.

A UML state machine diagram shows the states one thing can be in and the events that move it between them. Mermaid writes it as stateDiagram-v2. Here is the trip lifecycle that both the Booking API and the dispatch worker must respect:

Mermaid · trip-states.mmd
stateDiagram-v2
    [*] --> REQUESTED : rider requests a ride
    REQUESTED --> OFFERED : worker offers it to a driver
    OFFERED --> REQUESTED : driver declines, or 15 s pass
    OFFERED --> ACCEPTED : driver accepts in time
    ACCEPTED --> REQUESTED : driver cancels before pickup
    ACCEPTED --> IN_PROGRESS : driver starts the trip
    IN_PROGRESS --> COMPLETED : driver ends the trip
    REQUESTED --> EXPIRED : no driver after 3 offers
    REQUESTED --> CANCELLED : rider cancels
    OFFERED --> CANCELLED : rider cancels
    ACCEPTED --> CANCELLED : rider cancels, a fee may apply
    COMPLETED --> [*]
    CANCELLED --> [*]
    EXPIRED --> [*]

A state diagram is only useful while it matches the code. When the rules live in one table, a dozen lines of Python can compare the two. The rules module and the check below are the whole mechanism:

Python 3.12 · trip_rules.py
"""Trip lifecycle rules, as the Booking API and the dispatch worker enforce them."""
from enum import StrEnum


class Trip(StrEnum):
    REQUESTED = "REQUESTED"
    OFFERED = "OFFERED"
    ACCEPTED = "ACCEPTED"
    IN_PROGRESS = "IN_PROGRESS"
    COMPLETED = "COMPLETED"
    CANCELLED = "CANCELLED"
    EXPIRED = "EXPIRED"


ALLOWED: dict[Trip, set[Trip]] = {
    Trip.REQUESTED: {Trip.OFFERED, Trip.CANCELLED, Trip.EXPIRED},
    Trip.OFFERED: {Trip.REQUESTED, Trip.ACCEPTED, Trip.CANCELLED},
    Trip.ACCEPTED: {Trip.REQUESTED, Trip.IN_PROGRESS, Trip.CANCELLED},
    Trip.IN_PROGRESS: {Trip.COMPLETED},
    Trip.COMPLETED: set(),
    Trip.CANCELLED: set(),
    Trip.EXPIRED: set(),
}


def move(current: Trip, new: Trip) -> Trip:
    """Return the new state, or raise if the lifecycle does not allow the move."""
    if new not in ALLOWED[current]:
        raise ValueError(f"a trip cannot go from {current} to {new}")
    return new
Python 3.12 · check_states.py
"""Compare the transitions drawn in a Mermaid state diagram with trip_rules.ALLOWED."""
import re
import sys
from pathlib import Path

from trip_rules import ALLOWED

ARROW = re.compile(r"^\s*([A-Z_]+)\s*-->\s*([A-Z_]+)\b")


def drawn(path: str) -> set[tuple[str, str]]:
    lines = Path(path).read_text(encoding="utf-8").splitlines()
    return {(m[1], m[2]) for line in lines if (m := ARROW.match(line))}


def main(path: str) -> int:
    in_code = {(str(a), str(b)) for a, targets in ALLOWED.items() for b in targets}
    in_diagram = drawn(path)
    for a, b in sorted(in_code - in_diagram):
        print(f"allowed in code, missing from diagram: {a} --> {b}")
    for a, b in sorted(in_diagram - in_code):
        print(f"drawn in diagram, not allowed in code: {a} --> {b}")
    if in_code == in_diagram:
        print(f"OK: {len(in_code)} transitions, diagram and code agree")
        return 0
    return 1


if __name__ == "__main__":
    sys.exit(main(sys.argv[1]))

An earlier version of the diagram had no arrow from ACCEPTED back to REQUESTED, the move that happens when a driver cancels before pickup. Recreate that version with grep, then run the check against it and against the current diagram:

Terminal
grep -v "ACCEPTED --> REQUESTED" trip-states.mmd > trip-states-old.mmd
python check_states.py trip-states-old.mmd
python check_states.py trip-states.mmd
Expected output (old diagram, exit code 1)
allowed in code, missing from diagram: ACCEPTED --> REQUESTED
Expected output (current diagram, exit code 0)
OK: 10 transitions, diagram and code agree

The failing check does not say which side is right. Maybe drivers should not be able to cancel after accepting, and the code is wrong. That is a design conversation, and the diagram is what makes it possible. Other UML diagrams have the same role: activity diagrams for workflows with branches, class or entity-relationship diagrams for the few components whose code-level design is tricky. Use them for one concern at a time, and link each one from the C4 view it explains.

05. Check your understanding

Practice check · 3 questions

Runtime views

Decide where runtime information belongs.

Q1. Production puts a managed load balancer in front of the three Booking API pods; it terminates TLS and spreads requests. Staging has no load balancer at all. How should the load balancer appear in the deployment views?
Q2. You add the step `dispatch -> maps "Estimates the pickup time"` to the RequestRide dynamic view, and validation fails because no relationship between the dispatch worker and the maps platform exists. What is the right next step?
Q3. A team decides to write a dynamic view for each of its 40 user stories, including simple ones such as "agent opens a trip". What does the C4 guidance suggest instead?
Practice only: not graded, not saved, not evidence.

06. Apply it

Add the runtime views to your own model:

  1. Write one deployment environment for production and one for the environment developers use most. Include instance counts and the infrastructure nodes that matter for failures.
  2. Pick the one scenario that causes the most questions or incidents and write it as a dynamic view. Fix any relationship the validator says is missing.
  3. If a timeout, retry or race is part of that scenario, draw it as a Mermaid sequence diagram with alt or loop.
  4. If one entity has a lifecycle, draw its state diagram and add a check like check_states.py that compares it with the code.

07. Review prompt

Without looking back: name the four kinds of element a deployment view can contain and say why containers are defined only once. Explain the rule that every step of a Structurizr dynamic view must follow, and why it is useful. Then describe one question a UML sequence diagram answers better than a C4 dynamic view, and one that a state diagram answers.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check