Diagramming a ride-booking system at three zoom levels
Work through one model of a ride-booking system and get three consistent diagrams from it: the system context, the containers, and the components of the booking API, each with clear element types, technologies and labelled one-way arrows.
Contentsand lesson path
On this page
- The problem
- Step 1: people and the systems around yours
- Step 2: open the box into containers
- Step 3: zoom into the Booking API
- Step 4: views, styles and a text check of each zoom level
- Check your understanding
- Apply it
- Review prompt
Lessons of C4 & Architecture Documentation
- Abstractions first: people, systems, containers, components Concept · 20 min
- Diagramming a ride-booking system at three zoom levels Worked example · 25 min
- Deployment and dynamic views, and where UML still helps Concept · 20 min
- Diagrams as code in a docs-as-code workflow Lab · 25 min
- Deciding what to document and for whom Concept · 15 min
- Diagram review check Knowledge check · 6 questions
What you will learn
- Draw C4 system context, container and component diagrams with consistent notation, legends and scope.
01. The problem
A small company runs a ride-booking service. Riders request a car from a phone app, nearby drivers get the offer on their phones, and support agents handle refunds from a web console. The company buys card payments, maps and push notifications from outside providers. Three new engineers start next month, and the only architecture picture is a photo of a whiteboard.
Your task is to describe the system at three zoom levels: the system context for everyone, the containers for engineers and operations staff, and the components of the Booking API, the part the new engineers will change first. Two rules apply to every diagram, taken from the C4 notation guidance:
- Each diagram must stand alone. It has a title, a key for its shapes and colours, a type for every element, a short description, and a technology for every container and component.
- Each line is one-way and labelled with its purpose, and lines between containers name their protocol. Labels such as "uses" are too vague to help anyone.
You will write one Structurizr DSL file (introduced in the previous lesson) and let the tool produce the three views from it, so the names and the arrows agree across all of them.
02. Step 1: people and the systems around yours
Start outside the system. Three roles use it: riders, drivers and support agents. Three external systems matter enough to name, because other companies own and run them and the ride-booking system cannot work without them. Each element gets a one-line description of what it does for this system. The tag External will later give these three a different style, so readers can tell at a glance what the team does not own.
workspace "Ride booking" "C4 model of the ride-booking system." {
model {
rider = person "Rider" "Books rides, follows the driver and pays."
driver = person "Driver" "Accepts ride offers and drives riders."
agent = person "Support agent" "Answers riders and issues refunds."
payments = softwareSystem "Payment provider" \
"Authorises and captures card payments." "External"
maps = softwareSystem "Maps platform" \
"Routes, travel times and address search." "External"
push = softwareSystem "Push service" \
"Delivers notifications to iOS and Android phones." "External"
rides = softwareSystem "Ride Booking System" {
description "Matches riders with drivers, prices trips and takes payment."03. Step 2: open the box into containers
Now list what must be running for a ride to happen. Each block below is one container, with a description and a technology. A few choices deserve a sentence each, because a reader will ask about them:
- The rider and driver apps are separate containers, even though both are written in React Native, because they are different apps on different phones. The tag
Clientmarks containers that run on users' devices; the lab in lesson 4 uses it. - The dispatch worker is separate from the Booking API. Matching a driver can take most of a minute, so the API hands the work over through a queue and replies at once.
- The queue itself is a container, a store of waiting ride requests, rather than one box for the whole RabbitMQ broker. The diagram then shows exactly who puts requests in and who takes them out.
- Both data stores are containers: the trip database schema and the Redis store of driver positions. Each is described by what it holds, not just by its product name.
riderApp = container "Rider app" {
description "Requests rides, shows the driver on a map, pays."
technology "TypeScript, React Native"
tags "Client,Mobile"
}
driverApp = container "Driver app" {
description "Receives ride offers and streams the phone's GPS position."
technology "TypeScript, React Native"
tags "Client,Mobile"
}
console = container "Support console" {
description "Lets support agents search trips and issue refunds."
technology "TypeScript, React single-page app"
tags "Client,Browser"
}
api = container "Booking API" {
description "Quotes fares, creates rides and takes payment."
technology "Python 3.12, FastAPI"
trips = component "Trips endpoint" \
"Handles quote, ride and refund requests." "FastAPI router"
fares = component "Fare quoter" \
"Prices a trip from route distance and time." "Python module"
mapsClient = component "Maps client" \
"Calls the maps platform for routes." "httpx"
payClient = component "Payment client" \
"Authorises, captures and refunds card payments." "httpx"
repo = component "Trip repository" \
"Reads and writes trips." "SQLAlchemy"
publisher = component "Request publisher" \
"Publishes ride requests to the queue." "aio-pika"
}
dispatch = container "Dispatch worker" {
description "Offers each ride request to nearby drivers, one at a time."
technology "Python 3.12"
}
gateway = container "Location gateway" {
description "Keeps WebSocket connections to driver apps open."
technology "TypeScript, Node.js 22"
}
tripDb = container "Trip database" {
description "Trips, fares, offers and payments."
technology "PostgreSQL 18 schema"
tags "Database"
}
locStore = container "Location store" {
description "Latest position of every online driver, with a geo index."
technology "Redis"
tags "Database"
}
queue = container "Ride request queue" {
description "Ride requests waiting for the dispatch worker."
technology "RabbitMQ queue"
tags "Queue"
}
}Next, the relationships. Every arrow in this model points from the element that starts the interaction, and its label reads as a sentence: "Dispatch worker takes ride requests from Ride request queue". Choose one convention, either who calls whom or which way the data flows, and keep it; the C4 guidance allows both, as long as the label matches the arrow's direction. Arrows between containers end with the protocol, because "how do these two talk?" is a question every operations engineer asks. Arrows from people have no protocol: a rider tapping a phone screen does not need one.
rider -> riderApp "Requests rides and pays with"
driver -> driverApp "Accepts ride offers with"
agent -> console "Looks up trips and refunds with"
riderApp -> api "Requests quotes and rides" "JSON/HTTPS"
driverApp -> api "Accepts or declines offers" "JSON/HTTPS"
driverApp -> gateway "Streams GPS positions every 4 s" "WebSocket"
console -> api "Searches trips, issues refunds" "JSON/HTTPS"
api -> tripDb "Reads and writes trips" "SQL over TCP"
api -> queue "Publishes ride requests to" "AMQP"
api -> payments "Authorises and captures payments" "JSON/HTTPS"
api -> maps "Gets routes and travel times" "JSON/HTTPS"
dispatch -> queue "Takes ride requests from" "AMQP"
dispatch -> locStore "Finds drivers near the pickup" "Redis protocol"
dispatch -> tripDb "Records offers and matches" "SQL over TCP"
dispatch -> push "Sends ride offers" "JSON/HTTPS"
gateway -> locStore "Saves each driver's position" "Redis protocol"
push -> driverApp "Delivers offer notifications to" "APNs/FCM"04. Step 3: zoom into the Booking API
The Booking API is where the new engineers will work, so it is the one container worth opening. Its components are groups of code behind one interface each, not individual classes: the HTTP routes, the fare calculation, one client per external service, the repository that talks to the database and the publisher that talks to the queue. Six boxes are enough to explain where a change belongs. A component for every Python module would turn the diagram into a code listing that is out of date by the next sprint.
The relationships come in two kinds. Calls between components happen inside one process, so their technology is simply "Python call". Calls that leave the container repeat the protocol from step 2. The apps now point at the Trips endpoint, which tells a reader where requests enter the container.
api = container "Booking API" {
description "Quotes fares, creates rides and takes payment."
technology "Python 3.12, FastAPI"
trips = component "Trips endpoint" \
"Handles quote, ride and refund requests." "FastAPI router"
fares = component "Fare quoter" \
"Prices a trip from route distance and time." "Python module"
mapsClient = component "Maps client" \
"Calls the maps platform for routes." "httpx"
payClient = component "Payment client" \
"Authorises, captures and refunds card payments." "httpx"
repo = component "Trip repository" \
"Reads and writes trips." "SQLAlchemy"
publisher = component "Request publisher" \
"Publishes ride requests to the queue." "aio-pika"
} riderApp -> trips "Requests quotes and rides" "JSON/HTTPS"
driverApp -> trips "Accepts or declines offers" "JSON/HTTPS"
console -> trips "Searches trips, issues refunds" "JSON/HTTPS"
trips -> fares "Asks for a fare quote" "Python call"
fares -> mapsClient "Gets distance and time" "Python call"
mapsClient -> maps "Gets routes and travel times" "JSON/HTTPS"
trips -> payClient "Authorises, captures or refunds" "Python call"
payClient -> payments "Authorises and captures payments" "JSON/HTTPS"
trips -> repo "Saves and loads trips" "Python call"
repo -> tripDb "Reads and writes trips" "SQL over TCP"
trips -> publisher "Asks for a driver" "Python call"
publisher -> queue "Publishes ride requests to" "AMQP"
}05. Step 4: views, styles and a text check of each zoom level
The views section asks for three diagrams. Each view has an explicit key (Context, Containers, ApiComponents), because other files will link to these names, and generated keys can change. The styles give each tag a shape. They are the notation, and Structurizr builds the diagram key from them, so readers do not have to guess what a cylinder or a grey box means. The configuration block declares that this workspace describes one software system, which lets the tool warn you if it grows beyond that.
views {
systemContext rides "Context" {
include *
autolayout lr
}
container rides "Containers" {
include *
autolayout lr
}
component api "ApiComponents" {
include *
autolayout lr
}
styles {
element "Person" {
shape person
}
element "Mobile" {
shape mobileDevicePortrait
}
element "Browser" {
shape webBrowser
}
element "Database" {
shape cylinder
}
element "Queue" {
shape pipe
}
element "External" {
background #6b6b6b
color #ffffff
}
}
}
configuration {
scope softwaresystem
}
}Validate the file, then export the model as JSON and print what each view contains with the short script below. It reads the export and lists every element with its type and technology, then every arrow with its label. It is a way to review the diagrams as text, for example in a pull request, without rendering an image. The fragments for lines 1–16, 18–72, 74–90, 92–104 and 106–145, in that order with a blank line between them, make up the whole workspace.dsl.
"""Print what each static view of a Structurizr workspace shows, as plain text."""
import json
import sys
from pathlib import Path
LEVELS = ("Person", "Software System", "Container", "Component")
def index(model: dict) -> tuple[dict, dict]:
"""Map element ids to elements and relationship ids to relationships."""
elements, relationships = {}, {}
stack = list(model.get("people", [])) + list(model.get("softwareSystems", []))
while stack:
element = stack.pop()
elements[element["id"]] = element
stack += element.get("containers", []) + element.get("components", [])
for rel in element.get("relationships", []):
relationships[rel["id"]] = rel
return elements, relationships
def kind(element: dict) -> str:
tags = element["tags"].split(",")
return next(level for level in reversed(LEVELS) if level in tags)
def label(element: dict) -> str:
tech = element.get("technology")
return f"{element['name']} [{kind(element)}{': ' + tech if tech else ''}]"
def main(path: str, keys: list[str]) -> None:
workspace = json.loads(Path(path).read_text(encoding="utf-8"))
elements, relationships = index(workspace["model"])
views = workspace["views"]
static = (views.get("systemContextViews", []) + views.get("containerViews", [])
+ views.get("componentViews", []))
for view in static:
if keys and view["key"] not in keys:
continue
shown = [elements[e["id"]] for e in view["elements"]]
print(f"== {view['key']}: {len(shown)} elements")
for element in sorted(shown, key=lambda e: (LEVELS.index(kind(e)), e["name"])):
print(" " + label(element))
for r in sorted((relationships[r["id"]] for r in view["relationships"]),
key=lambda r: (elements[r["sourceId"]]["name"],
elements[r["destinationId"]]["name"])):
tech = f" [{r['technology']}]" if r.get("technology") else ""
print(f" {elements[r['sourceId']]['name']} -> "
f"{elements[r['destinationId']]['name']}: {r['description']}{tech}")
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2:])java -jar "$STRUCTURIZR_WAR" validate -workspace workspace.dsl && echo valid
java -jar "$STRUCTURIZR_WAR" export -workspace workspace.dsl -format json \
-output build > export.log && ls build
python views_summary.py build/workspace.json Contextvalid
workspace.json== Context: 7 elements
Driver [Person]
Rider [Person]
Support agent [Person]
Maps platform [Software System]
Payment provider [Software System]
Push service [Software System]
Ride Booking System [Software System]
Driver -> Ride Booking System: Accepts ride offers with
Push service -> Ride Booking System: Delivers offer notifications to [APNs/FCM]
Ride Booking System -> Maps platform: Gets routes and travel times [JSON/HTTPS]
Ride Booking System -> Payment provider: Authorises and captures payments [JSON/HTTPS]
Ride Booking System -> Push service: Sends ride offers [JSON/HTTPS]
Rider -> Ride Booking System: Requests rides and pays with
Support agent -> Ride Booking System: Looks up trips and refunds withLook at the arrows. Nobody wrote a relationship from Ride Booking System to Payment provider, yet the context view has one. Structurizr implied it from the Booking API's relationship with the payment provider: if a container talks to an outside system, then the system as a whole does too. The context view therefore stays consistent with the container view. The context view has no containers in it, because its job is to show scope to everyone, including people who will never read code.
python views_summary.py build/workspace.json Containers
python views_summary.py build/workspace.json ApiComponents== Containers: 15 elements
Driver [Person]
Rider [Person]
Support agent [Person]
Maps platform [Software System]
Payment provider [Software System]
Push service [Software System]
Booking API [Container: Python 3.12, FastAPI]
Dispatch worker [Container: Python 3.12]
Driver app [Container: TypeScript, React Native]
Location gateway [Container: TypeScript, Node.js 22]
Location store [Container: Redis]
Ride request queue [Container: RabbitMQ queue]
Rider app [Container: TypeScript, React Native]
Support console [Container: TypeScript, React single-page app]
Trip database [Container: PostgreSQL 18 schema]
Booking API -> Maps platform: Gets routes and travel times [JSON/HTTPS]
Booking API -> Payment provider: Authorises and captures payments [JSON/HTTPS]
Booking API -> Ride request queue: Publishes ride requests to [AMQP]
Booking API -> Trip database: Reads and writes trips [SQL over TCP]
Dispatch worker -> Location store: Finds drivers near the pickup [Redis protocol]
Dispatch worker -> Push service: Sends ride offers [JSON/HTTPS]
Dispatch worker -> Ride request queue: Takes ride requests from [AMQP]
Dispatch worker -> Trip database: Records offers and matches [SQL over TCP]
Driver -> Driver app: Accepts ride offers with
Driver app -> Booking API: Accepts or declines offers [JSON/HTTPS]
Driver app -> Location gateway: Streams GPS positions every 4 s [WebSocket]
Location gateway -> Location store: Saves each driver's position [Redis protocol]
Push service -> Driver app: Delivers offer notifications to [APNs/FCM]
Rider -> Rider app: Requests rides and pays with
Rider app -> Booking API: Requests quotes and rides [JSON/HTTPS]
Support agent -> Support console: Looks up trips and refunds with
Support console -> Booking API: Searches trips, issues refunds [JSON/HTTPS]== ApiComponents: 13 elements
Maps platform [Software System]
Payment provider [Software System]
Driver app [Container: TypeScript, React Native]
Ride request queue [Container: RabbitMQ queue]
Rider app [Container: TypeScript, React Native]
Support console [Container: TypeScript, React single-page app]
Trip database [Container: PostgreSQL 18 schema]
Fare quoter [Component: Python module]
Maps client [Component: httpx]
Payment client [Component: httpx]
Request publisher [Component: aio-pika]
Trip repository [Component: SQLAlchemy]
Trips endpoint [Component: FastAPI router]
Driver app -> Trips endpoint: Accepts or declines offers [JSON/HTTPS]
Fare quoter -> Maps client: Gets distance and time [Python call]
Maps client -> Maps platform: Gets routes and travel times [JSON/HTTPS]
Payment client -> Payment provider: Authorises and captures payments [JSON/HTTPS]
Request publisher -> Ride request queue: Publishes ride requests to [AMQP]
Rider app -> Trips endpoint: Requests quotes and rides [JSON/HTTPS]
Support console -> Trips endpoint: Searches trips, issues refunds [JSON/HTTPS]
Trip repository -> Trip database: Reads and writes trips [SQL over TCP]
Trips endpoint -> Fare quoter: Asks for a fare quote [Python call]
Trips endpoint -> Payment client: Authorises, captures or refunds [Python call]
Trips endpoint -> Request publisher: Asks for a driver [Python call]
Trips endpoint -> Trip repository: Saves and loads trips [Python call]Each level answers a different question. The context view answers "what is this system and what does it depend on?". The container view answers "what runs, in which technology, and how do the parts talk?". Fifteen elements already make a busy diagram; if it grew much further, you would split it by area rather than shrink the text. The component view answers "where in the Booking API does my change belong?". It keeps the apps, the database, the queue and the two providers as supporting elements, so the reader still sees where each request comes from and where it goes.
To see the pictures, paste workspace.dsl into the Structurizr playground. The lab in lesson 4 renders the same views as a static web site from a script.
06. Check your understanding
07. Apply it
Extend the model of your own system from the previous lesson:
- Add the relationships between your containers, using one arrow convention, a sentence-style label and a protocol on every inter-container arrow.
- Open the one container that people change most and give it five to eight components.
- Add views with explicit keys and styles driven by tags, then export to JSON and run
views_summary.pyon it. - Read the output as a newcomer would. Every arrow should read as a sentence, every element should say what it does, and no view should mix levels. Fix the model until all three are true.
08. Review prompt
Without looking back: name the three views of this example and the question each one answers. Explain why the queue is drawn as a container and why the dispatch worker is not part of the Booking API. Then explain where the arrows on the context view come from, and what that means for keeping diagrams consistent.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.