Modelling a system with C4¶
How to decide what goes in the model and at which level: what a software system, a container, a component and a code element are, with a test for each, how to draw relationships and scenarios, the usual mistakes and how to correct them, and a checklist. Read it before planning a model (SKILL.md, step 1) and when reviewing one.
This guide is about what to model. The fields are in data-model.md (types, parent, tag, sub, desc, kind, edges, scenarios, data); placement, layout and the size of groups in features.md ("How layout is decided", "Making a good architecture diagram with it"). Where they overlap, they say the same thing. check-model.mjs (which the build runs) prints modelling hints, under a HINTS line, when a model looks like one of the mistakes below; each names the section here that explains it. They are information, not warnings.
The four levels¶
C4 describes one software system at four zoom levels. Each answers one question for one kind of reader, and the explorer shows them as boxes that open in place.
| Level | Boxes (type) |
The question it answers | Who reads it |
|---|---|---|---|
| L1 · Context | person, system, ext, sibling |
Who uses the system, and what does it depend on? | Everyone, including people who do not write code |
| L2 · Containers | container, store |
What runs, what stores data, and how do they talk? | Developers, operations, architects |
| L3 · Components | component |
How is one container organised inside? | Developers working on that container |
| L4 · Code | code |
Which functions, classes, endpoints, tables matter by name? | Developers looking for a specific thing |
A state is not a C4 level: it is one step of a lifecycle, drawn inside the box that owns it (one level below it).
Two accurate levels beat four invented ones. Stop at the level where your evidence stops.
Which type is it?¶
Ask these questions in order, about the thing as it exists at run time. The first "yes" decides.
| # | Question | Yes → |
|---|---|---|
| 1 | Is it a human, or a role humans play (an admin, a reviewer, a customer)? | person |
| 2 | Is it a separate system whose behaviour your team does not decide (a payment provider, an identity provider, a partner's API)? | ext |
| 3 | Is it a separate system your organisation builds, but outside the boundary you are documenting? | sibling |
| 4 | Is it the whole thing you are documenting, owned and built by one team? | system |
| 5 | Must it run, or hold data, for the system to work, as a unit of its own: its own process, its own deployment, its own store? | store if it holds data (database, bucket, queue, cache, index), else container |
| 6 | Is it a group of related code behind one interface, inside one container, that you cannot deploy on its own? | component |
| 7 | Is it a function, class, endpoint, constant, query or file that someone will look for by name? | code |
| 8 | None of the above (a library, a folder, a layer, a server, a cluster, a config file) | Not a box: see "Not a container" under "Containers", and "What is not in the model" |
People (person)¶
Test: does a human start something in the system, or receive something from it?
- A person is a role, not an individual:
Reviewer, notAlice. Take roles from the code: the role column, the role checks on routes, the pages per role. - Model a role when it uses the system differently from the others (its own pages, its own permissions). Two roles that do exactly the same things are one person.
- Automated clients (a cron, CI, another company's server) are not people. A scheduler that is part of your system is a
container; a partner's server calling your API is anext. - A person talks to the container (or the component, such as the page) they use, not to a data store. If someone really reads the database directly (an analyst with SQL access), draw it and say so in
desc.
Software systems: yours, neighbouring, external¶
system: the boundary of what one team owns and builds. Usually one per model: the repository's product. Several only when the repository really ships several products with their own users.
ext: a system you depend on but do not own or change. You call its API, it calls yours, and someone else decides how it behaves: Stripe, an identity provider, a weather API, a partner's ERP. It is a black box: no children. Say in desc what the system uses it for, and give its documentation as url.
sibling: a system your organisation builds, outside this boundary. Another team's service, the company's data platform. Also one box here: its insides belong to its own model.
The test that separates them from containers is ownership, not hosting:
- A database, bucket or queue your system owns (its schema, its data, its configuration) is a
storeinside yoursystem, even when a cloud provider runs it (RDS, S3, a managed Redis). Your team decides what is in it. - A service you only call is an
ext, even when it runs in your own cloud account (a vendor's appliance you only reach through its API), as long as you do not decide what it does. - A shared database that several systems write to is the hardest case: model it as a
storeof the system that owns its schema, and as anextorsiblingin the others.
Containers (container)¶
Test: must it be running for the system to work, as a unit of its own? Its own process (or browser tab, or function invocation), started, deployed or scaled on its own. Start from the deployment files: every service of a compose file, every Deployment of a Kubernetes manifest, every app of a Procfile is a candidate; then confirm each has code or an image.
Containers in C4 are not Docker containers: the word means "something that contains code or data and runs". A Docker image is often one container, but not always (a sidecar that only ships logs is deployment, not architecture).
| A container | Why |
|---|---|
| A single-page app (React, Vue) running in the browser | Its own runtime: the browser |
| A server-rendered web app, an API service, a backend for frontend (BFF) | Its own process |
| A background worker, a consumer of a queue | Its own process, scaled on its own |
| A scheduled or one-shot job (a cron job, a migration job, an init container that creates buckets) | It runs, and the system needs it to have run |
| A serverless function (or a group deployed together) | Its own deployment and invocation |
| A CLI, a desktop app, a mobile app | Installed and run on its own |
| Not a container | What it is instead |
|---|---|
| A library, an SDK, a shared package | Code that runs inside the containers that import it: a component of each (or of the main one), or only a tech chip |
A folder, a layer (controllers/, domain/), a module |
A component |
| A Kubernetes cluster, a namespace, a VM, a server, a load balancer that only forwards | Deployment: where containers run, not what they are (see "Deployment: where the containers run") |
| A Docker image that only wraps a tool for the developers (a linter, a test runner) | Development tooling: leave it out, unless the documentation is about the build |
| A configuration file, an environment variable | notes on the container that reads it |
The browser and the server. Strictly, a single-page app (in the browser) and the web server that sends it (on a server) are two runtimes, so two containers. When the server only hands out the built files and forwards /api (nginx, a CDN), a common simplification is one container for both, with the server as a component inside it; say so in desc. When the server has logic of its own (server-side rendering, sessions, a BFF), split them: Web server and Single-page app.
A project that is a library. The system is the library, its users are the applications that import it (ext, or a person for the developer), and there is one container: the package as it is installed. The weight goes on components: the public API, the core, the adapters or back-ends.
Name and tag. name is what the team calls it (API service, Web app, Worker). tag says the kind and the technology (CONTAINER · FASTAPI, ONE-SHOT JOB · MC); tech lists the stack.
Data stores (store)¶
Test: does it hold data the system needs, as a unit of its own? A database, an object store or bucket, a queue or topic broker, a cache, a search index, a file share. In C4 a data store is a kind of container (the RDF graph types it as both), drawn as a cylinder.
- One
storeper store the system owns, not per server: a PostgreSQL server holding two databases owned by two services is two stores (name them by what they hold:Orders DB,Billing DB). tagsays what kind of store it is, because the product does not:QUEUE · REDIS 7andCACHE · REDIS 7are different roles of the same product.- Name a store by what it holds or by its product when there is one of each (
PostgreSQL,MinIO). Never justDatabase. - A store is passive: it answers, it does not call. Arrows go to it (
reads tasks,PUT originals). An arrow from a store is right only when the store really pushes (a database trigger calling out, a stream that invokes a function). - Tables, buckets, messages and their fields are not more boxes: they go in the Data tab (see "Data").
Components (component)¶
Test: a group of related code behind one interface, inside one container, that cannot be deployed on its own. A package, a module, a directory, a service layer, a set of routes, a page of a web app, a job a worker runs. Look for them from the entry point inward: entry point → routers or handlers → services or domain → adapters (database, storage, queue, other services).
- Size them so a container has about 4 to 9. Not every file, not every class: the modules a maintainer thinks in. Three helpers and a constants file are not three components.
- A component belongs inside a
container(or astore, for stored procedures and the like), never directly inside asystemor a person (the validator warns). - One interface, one responsibility.
Auth,Tasks routes,Object storage client,Task state machine. A component named after a single function is usually code (see "Anti-patterns"); a module with one public entry point that the container dispatches to (a job of a worker) is a fine component. - Cross-cutting parts (auth, the ORM session, logging) are components too when the code has them as modules; place them where many arrows reach them (
features.md, "Cross-cutting hubs"). Pure utilities that explain nothing (string helpers, config loading) can be left out. - Only the containers that matter get components. Usually one to three: the ones with the domain logic, the hub, the one the flows spend their steps in. Data stores, brokers and thin proxies stay single boxes.
Code elements (code)¶
Test: will someone look for it by name? The public entry points (POST /api/tasks/next as claim_next_task()), the function that orchestrates, the one place a status changes, the central types, a transition table, a tricky query.
nameis the real identifier, with()for functions;tagthe construct (POST /api/images,FUNCTION,CLASS,SQL QUERY).- Inside a
component, never directly inside a container: code belongs to a component. - Two to six per component. Most components need none: L4 is for the places a reader will search, not a mirror of the source tree.
States (state)¶
The plugin's extension for lifecycles. When a status field drives the domain (an order, a task, a payment, a job), give it a box of its own (a component or code element made for it, or the class that holds the status) and put only its state children in it, with the transitions as edges labelled by the event that causes them. One state is initial: true, end states final: true; five to nine read well. The function that performs a transition can point at the state it produces. Details in data-model.md, "State machines".
How deep to go¶
| Go one level deeper when | Stay where you are when |
|---|---|
| The reader asked about the logic inside it | It is a data store, a broker or a thin proxy |
| It is a hub: many arrows in or out | It has one responsibility a sub and a desc already explain |
| The flows you trace spend their steps inside it | You would be guessing: no code read for it |
| A scenario should show a sequence inside it (its steps must then name its components) | It would get a single child |
A box with one child says nothing its parent does not: merge them, or name the other children. It is normal for one container to have components and the others to stay leaves.
Relationships (edges)¶
An edge says that one element calls, reads, writes, sends to or depends at run time on another. Imports that say nothing about behaviour are not edges.
- Direction is who initiates: caller → callee, reader → store, producer → queue, consumer → queue (the consumer polls it). The arrow does not follow the data: a
GETthat brings data back is still caller → callee. - One arrow for a call and its answer. Do not draw the response as a second arrow back;
A → Bstands for the request and its reply. An arrow back is right only when B starts something on its own: a callback, a webhook, a push notification. - Labels are verb phrases with what is carried:
reads stock + prices,POST /orders,publishes OrderPlaced,enqueue "exports". Notuses,callsorconnects to: an edge you cannot name a verb for is probably not real. The protocol goes in the label when it is what a reader searches for (SQL (SQLAlchemy),GET presigned URLs), else in the scenario steps. Up to 16 characters fit on one line (data-model.md,edges[]). - Dashed for asynchronous, optional or indirect: enqueueing a job, consuming a queue, an event, a link the browser follows later.
- Declare it between the most specific elements you know (component to component, code to code), and only there. The map lifts every edge to the boxes that are visible, so a closed container shows the relationships of everything inside it; declaring the same relationship again between the containers would draw it twice. Give the lower edges a
summary(JSON over HTTPS) so the lifted arrow reads well at L2 (data-model.md, "Labels on merged arrows"). - No edge between two containers that never talk. A worker and an API that share a queue and a database have no arrow between them: both have arrows to what they share.
- Queues and topics: producer → queue (
enqueue "thumbnails", dashed), consumer → queue (consumes jobs, dashed). A scenario step, unlike an edge, follows the message: the job travels from the queue to the consumer (see "Scenarios"). - Entry points:
kind: 'accent'on the few edges where the outside world enters the system. - Hubs: an element most siblings use (auth, the ORM session) is drawn, placed centrally, and reached by edges with the same short label (
features.md, "Cross-cutting hubs"); declare the dependency once at a common parent of its users when one exists. - One to three outgoing edges per box at the level where it is drawn. Eight means a hub, or edges that belong to its children.
Scenarios¶
A scenario is one flow through the system, in execution order: the main user journey, the main background job, the path that explains a design decision (a rejection, a retry, a cache miss).
- Steps follow the message: caller → callee for a call, the queue → the consumer when a job is delivered, callee → caller with
reply: truefor an answer worth showing (201 · image_ids). Not every call needs its reply. - Steps name the most specific elements: a component or code element, not the container around it. A step written as
web → apishows nothing insideapi, so the sequence inside that container stays empty. - 8 to 40 steps. More is two scenarios; fewer than five usually means the steps are too coarse.
- Labels are concrete: the function and its key arguments, the HTTP method and path, the message, the status code.
- Use-case fields from evidence only:
actor(the person whose goal it serves; the role check on the route),goal,trigger,preconditions(role checks, error answers),outcome(the last writes). Leave a field out rather than guess (data-model.md, "Use cases"). - Two to four scenarios per model.
Data: the Data tab, not more boxes¶
The store is the box; what is in it is data. Tables, columns, buckets and key layouts, queue messages, API payloads and ontology classes are schemas (each living in a store, container or component), entities and fields, drawn in the Data tab, and the steps say what they reads and writes (data-model.md, "Data: schemas, entities, relations").
- Not a
codebox per table. The ORM model class is acodeelement only when someone looks for it by name; the entity points at it withcode. - A lifecycle's status column points at its
statebox withstates.
Names, tag, sub and desc¶
| Field | Write | Example |
|---|---|---|
name |
What the team calls it, or its real identifier for code. Not the parent's name again. | API service, Tasks routes, claim_next_task() |
tag |
The kind of thing, plus technology or route | CONTAINER · FASTAPI, QUEUE · REDIS 7, POST /api/tasks/next |
sub |
What it does, in about five words separated by · |
claim · submit · reopen |
desc |
One to three sentences: its responsibility and, when not obvious, why it exists. Facts from the code, not guesses. | "Owns all business rules … The only writer of task status." |
notes |
What bites: configuration flags, limits, invariants, "only runs when" | REVIEW_COMMENT_REQUIRED defaults to true |
kind |
Only to make a point: highlight on the two or three boxes a reader must not miss |
the entry point, the orchestrator |
Generic names (Backend, Database, Service, Server) hide what a box is: name it by its role or by what it holds.
Size of a group¶
| Group | Aim for | Hard to read beyond |
|---|---|---|
| Top level (people, systems, externals) | 4–8 | 10 |
| Containers in a system | 3–8 | 10 |
| Components in a container | 4–9 | 12 |
| Code in a component | 2–6 | 9 |
The same table is in features.md ("How many boxes"); the validator warns above 12 children. When a group grows past it, add a level by responsibility (five route modules become one routes/ component with five children), merge externals of the same role, or drop pure utilities. Do not shrink text.
Deployment: where the containers run¶
A deployment is a separate diagram, not more boxes on the map (deployment in model.js; data-model.md, "Deployment"). The map says what the software is; the deployment says where each part runs, per environment.
Test: is it something a container runs on or goes through, rather than something the team writes? Then it belongs in the deployment, not on the map.
- Environment: one per real target the repository deploys to, as its files say:
Productionfrom the Terraform and Kubernetes folders,Local (Docker Compose)fromdocker-compose.yml. Not one per branch, not one per developer. - Deployment node: where an instance runs: a cloud account or region, a cluster, a namespace, a VM, a Docker host, a pod spec, a database server, a phone. Nest them as the files nest them (account › region › cluster › namespace).
techsays what it is (AWS EKS 1.30,Docker Engine);instanceshow many there are (a node pool of 3). - Container instance: a container or data store of the map running on a node;
instancesis its replica count when the files give one (replicas: 3, an autoscaler's minimum), andtechhow it runs there (the image, the port). - Software system instance: a whole system you run yourself on that infrastructure (a self-hosted Keycloak drawn as
ext, a neighbouring system). - Infrastructure node: what the traffic goes through but nobody on the team writes: a load balancer, DNS, a firewall, a CDN, an ingress controller. Only when the files declare it.
- Relationships: the map's own arrows are drawn between the instances already. Add only what the deployment has on its own: the load balancer forwarding to the web instances, a replica following its primary.
Anti-patterns:
| Spot it | Correct it |
|---|---|
A Kubernetes cluster, a VM or a load balancer drawn as a container on the map |
Move it into the deployment as a node or an infrastructure node; the map keeps the software |
| An environment, a region or a replica count with no file behind it | Leave it out; a deployment is only as true as its sources (path on every node) |
| Every Kubernetes object as a node (Service, ConfigMap, Secret, Ingress, HPA…) | Nodes are where things run (cluster, namespace, a workload); an Ingress or a Service that only routes is at most one infrastructure node; configuration goes in desc |
The model's relationships copied into relationships |
Remove them: they are drawn between the instances already |
| A container in two nodes of one environment without ids | Give each instance an id (api-eu, api-us) |
| One environment per developer laptop, per feature branch | One per target the files describe |
What is not in the model¶
- Deployment is not containers. Clusters, nodes, VMs, regions, load balancers, replicas and scaling are where the containers run, not what they are: they go in the
deployment(above), never on the map. - Facts the model has no field for (ownership, data classification, cost, SLAs) go through the same
rdfhook. - Build and development tooling (linters, test runners, CI images) unless the documentation is about the build.
- Things you did not find in the code. No cache, gateway or queue "because systems like this have one".
Worked example: the Image Annotation Tool¶
examples/image-annotation-tool in the plugin: an admin uploads images, annotators draw boxes, reviewers approve or reject, approved work is exported as COCO JSON. Its model (communications/architecture-explorer/model.js) and brief (communications/project-brief.md) apply the rules above.
Level 1. Three person boxes, admin, annotator and reviewer: the three values of the users table's role column, each with its own page. One system, iat. No ext: the brief found no outbound client, SDK or webhook. PostgreSQL, Redis and MinIO are not external systems: the project's own compose file runs them and the system owns their data, so they are stores inside iat.
Level 2, from the compose file's services:
| id | type |
Why it is at this level |
|---|---|---|
web |
container |
The React single-page app, built with Vite and served by nginx: one compose service, one image. nginx only serves the files and proxies /api/, so it is a component inside (nginx), not a container of its own (see "The browser and the server") |
api |
container |
The FastAPI service: its own process, the only writer of task status |
worker |
container |
The RQ worker: its own process, scaled on its own. There is no edge between api and worker: they share Redis, PostgreSQL and MinIO, and both have arrows to those |
minio-init |
container |
A one-shot job that creates the buckets and exits; the API and the worker wait for it, so the system needs it to have run |
postgres |
store |
The system of record (DATA STORE · POSTGRES 16) |
redis |
store |
Used as a job queue, so its tag says QUEUE · REDIS 7 |
minio |
store |
Object storage for originals, thumbnails and export files (OBJECT STORE · S3 API) |
Level 3, only for the three containers with code:
api: one component per module ofapi/app/(auth,images,tasks,annotations,reviews,export,models,storage,queue), the puresm(task state machine), andlifecycle, a box made to hold the task's states. Eleven is at the upper end of the range; grouping the five route modules into oneroutes/component would bring it to seven at the cost of one more level.web: the app shell, one component per role's page, the canvas, the API client andnginx.worker: the entry point (wmain) and one component per job (thumb,coco). Each job is a module with one entry point that the worker dispatches to, a fine component. The brief's "shared clients" module was left out: a utility that explains nothing.
Level 4, only what a reader looks for: the endpoints (login(), claim_next_task(), submit_task(), review_task(), …), apply_action() (the single place a status changes), TRANSITIONS (the transition table), APPROVED_BOXES (the export's SQL query). The pages, the canvas and the jobs' internals have no code children.
States. lifecycle holds st-pending (initial), st-in-progress, st-submitted, st-approved (final) and st-rejected, with transitions labelled by action and role (claim · annotator). next-status → lifecycle says which code moves a task; the tasks.status column points at lifecycle with states.
Relationships worth a look:
client → claim-next(POST /api/tasks/next): declared between the most specific elements; at L2 the map lifts it, with its siblings, to oneweb → apiarrow.enqueue-thumbnail → redis(enqueue "thumbnails") andwmain → redis(consumes jobs), both dashed: producer → queue and consumer → queue. In theuploadscenario the same hand-off is the stepredis → wmain(job from queue "thumbnails"), because steps follow the message.canvas → minio(GET presigned URLs, dashed): the browser fetches images straight from MinIO with URLs the API signed. It is declared from the component that does it, so at L2 it shows asweb → minio.nginx → api(proxies /api/): from a component to a whole container, because the proxy forwards to the service, not to one part of it.
Scenarios. Four flows (upload, annotate, review, export), every step between components or code (no step names api or web themselves, so the sequence inside each container shows its parts), with replies only where the answer matters (201 · image_ids). annotate and export carry the use-case fields, taken from the role checks and error answers in the code.
Anti-patterns¶
| Anti-pattern | How to spot it | Correction |
|---|---|---|
| Mixing levels in one group | A component next to containers inside a system; a container at the top level | Put each box at its level: the component inside its container, the container inside the system (the validator warns about most of these) |
One giant Backend |
A container with 30 or 40 children, or named Backend |
Split it into the containers that really run separately; if it is one process, add a level of components by responsibility |
| A library or shared package as a container | type: 'container' with a name or tag like lib, SDK, shared, common |
A component inside each container that uses it, or a tech chip; a container only if it runs on its own |
| Infrastructure as containers | Boxes named Kubernetes, EKS cluster, VM, nginx ingress that host other boxes |
Leave deployment out, or record it in notes, variants or the rdf hook (see "What is not in the model") |
An unnamed Database |
A store called Database, DB, Storage |
Name it by what it holds (Orders DB) or its product, and give it a tag with its kind |
| Arrows both ways | A → B and B → A where one is the reply (returns data, 200 OK) |
One arrow from the caller; the answer is part of the call (a reply: true step in a scenario, if it matters) |
uses labels |
Labels uses, calls, connects to, talks to |
A verb phrase with what is carried: reads tasks, POST /images, enqueue "exports" |
| A component per function | Many components each named do_x(), all in one module |
One component for the module; the functions that matter are its code children |
| Code directly in a container | A code box whose parent is a container |
Add the component that groups it, or make it a component |
| Insides of an external system | An ext (or sibling) with children |
One box; say in desc what the system uses it for |
| A data store that calls | PostgreSQL → API service (returns rows) |
API service → PostgreSQL (reads tasks); a store answers |
| A person on the database | Admin → PostgreSQL |
Admin → Admin page → … → PostgreSQL, unless someone really queries it directly (then say so) |
| Containers that never talk, connected | API service → Worker when they only share a queue |
Arrows from both to the queue they share |
| A relationship declared twice | web → api and client → claim-next for the same calls |
Only the lower one; a summary on it for the lifted arrow |
| Coarse scenario steps | Steps between containers that have components | Steps between the components or code that send and receive |
| An orphan | A box with no edge and no scenario step, nor anything inside it | Connect it, or leave it out: a box nothing uses and that uses nothing explains nothing |
| One child | A box whose only child is one box | Merge them, or model the other children |
| Invented boxes | A cache or gateway with no file behind it | Only what the code, the deployment files or the docs show; every box gets a path |
Review checklist¶
Before building, and again when reviewing someone else's model:
- [ ] Every
personis a role found in the code; everyextis something the system calls or is called by, with no children. - [ ] Every
containerandstorepasses the test: it runs, or holds data, as a unit of its own. No library, folder, layer or piece of infrastructure among them; no Docker image counted just because it exists. - [ ] Stores the system owns are inside its
system, whoever hosts them; each has a name and atagsaying its kind. - [ ] Components are inside containers, about 4 to 9 per container, each one responsibility; only the containers that matter have them.
- [ ] Code elements are inside components and are things a reader will search for.
- [ ] No group with a single child; no group past the "hard to read" limits.
- [ ] Every edge goes from the initiator, has a verb-phrase label, is declared once at the most specific level, and is dashed when asynchronous. No reply arrows, no arrows between containers that never talk.
- [ ] Every scenario's steps name components or code, follow the message, and are in the order the code runs them; use-case fields are backed by code.
- [ ] Tables and messages are in the Data tab, not boxes.
- [ ] Every box has a
desc, and apathwhen it maps to code. - [ ] Every modelling hint the build prints (
HINTS) is fixed, or you can say why the model is right as it is. - [ ] The coherence rules find nothing open (
scripts/check-coherence.mjs,coherence-rules.md): every step rides an arrow, data is reached from the boxes that touch it, queues have both sides, no two containers call each other, every lifecycle starts and ends. What is right as it is carries its reason inview.coherence.ignore.
Where the details are. The fields named above are described in the data model (types, edges, scenarios, use cases, state machines, the data layer); placement, the size of groups and hubs in Features and layout. The worked example is the example explorer, built from its project brief. The terms are defined in the ontology.
Source
This page is skills/architecture-explorer/references/modelling.md, the guide the skill reads before it plans a model. Edit it there; the documentation includes it as is.