Skip to content

Kruchten's 4+1 View Model: Logical, Process, Development, Physical & Scenarios ​

"As a remedy, we propose to organize the description of a software architecture using several concurrent views, each one addressing one specific set of concerns." — Philippe Kruchten, Architectural Blueprints—The "4+1" View Model of Software Architecture, IEEE Software 12(6), November 1995

Summary: One diagram cannot say what runs, what is compiled, what is deployed and what the business means at the same time; the 4+1 model splits the architecture description into four views for four groups of people (logical, process, development, physical) and ties them together with a handful of scenarios that both drive the design and prove it works. Focus: The five views in depth (purpose, stakeholders, elements, connectors, notation, questions, diagrams), how scenarios connect and validate them, the correspondence rules between views, the later vocabulary (ISO/IEC/IEEE 42010 viewpoints and views, SEI Views and Beyond, C4, arc42, Rozanski and Woods), the mapping to UML diagram types, which views matter at which scale, a complete online-ordering example with Go and Laravel code, keeping views in sync, anti-patterns and a checklist. Learning goal: Given any system, produce the minimum set of views its stakeholders need, draw each with the right elements and connectors, write the three to five scenarios that walk through all of them, and wire the build so the development and physical views cannot silently drift from the code.

This page owns the documentation side of architecture: how to describe a system so that each audience finds its answer. It assumes the definitions from What Software Architecture Is and the level split from Architecture vs Design. It does not re-teach the diagram notations themselves (that is UML in Practice), nor how to record one decision (that is Architecture Decisions and ADRs), nor how to derive the drivers (that is From Requirements to Architecture). The styles the views end up showing are taught in Layered Monolith, Modular Monolith and Microservices.

Page map ​

If you are looking forGo to
The five views in a few tablesEverything in one minute
Why one diagram is never enoughWhy it exists
Perry and Wolf, Kruchten 1995, RUP, IEEE 1471, ISO 42010, V&B, C4Where it comes from
Logical, process, development, physical, scenarios, one block eachThe concept catalogue
How elements of one view map to another (inside-out, outside-in)Correspondence between views
Stakeholder, concern, viewpoint, view, model (ISO 42010)Viewpoints and views
Module, component-and-connector, allocationViews and Beyond
C4 levels, arc42 sections, Rozanski and Woods viewpointsC4, arc42, Rozanski and Woods
4+1 against UML diagram types and the other systemsMapping table
Software Architecture Document outline, choosing views, diagrams as codeMechanics
An online ordering platform documented in all five viewsWorked example
Go and Laravel code tied to the viewsGo, Laravel
Giant diagram, unread views, stale viewsSolving the classic problems
Which views for which systemChoosing
Monolith to distributed systemIn architecture
Hands-onLab
What to check before you publishDocumentation checklist
Wrong beliefs, cheat sheet, self-check, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The five views. Stakeholders and concerns in the first rows come from Kruchten's own summary table (Table 1 of the paper); the "today" rows are ours.

LogicalProcessDevelopmentPhysicalScenarios (+1)
In plain wordsWhat the system does, in domain termsWhat runs at the same time and how it talksHow the code is organized and builtWhere it runsA few stories that walk through all four
Components (Kruchten)ClassTaskModule, subsystemNodeStep, scripts
Connectors (Kruchten)Association, inheritance, containmentRendez-vous, message, broadcast, RPCCompilation dependency, "with" clause, "include"Communication medium, LAN, WAN, bus(uses the process connectors)
Containers (Kruchten)Class categoryProcessSubsystem (library)Physical subsystemWeb
Stakeholders (Kruchten)End-userSystem designer, integratorDeveloper, managerSystem designerEnd-user, developer
Concerns (Kruchten)FunctionalityPerformance, availability, S/W fault-tolerance, integrityOrganization, reuse, portability, line-of-productScalability, performance, availabilityUnderstandability
Typical UML todayClass, object, state machineSequence, activity, communicationPackage, componentDeploymentUse case, sequence
C4 todayContext, componentContainer, dynamicComponent, codeDeploymentDynamic
Question it answers"Where does the rule live?""What blocks what, and how long?""Who owns which folder, what may import what?""What dies if this node dies?""Does the design actually work for this story?"

One system, five answers (the full example is in the worked example):

ViewOnline ordering platform, in one line
LogicalOrdering (Order aggregate, lines, status), Catalog, Inventory, Payments, Shipping
Processorders-api ×3 (sync HTTP), outbox-relay ×1 (periodic), workers (async, retry)
DevelopmentOne Go module / one Laravel app; cmd/ per process, one folder per module, platform at the bottom
PhysicalLoad balancer, Kubernetes over two zones, PostgreSQL primary + standby, three broker nodes
ScenariosS1 place order, S2 out of stock, S3 payment declined, S4 relay crash, S5 zone loss

The vocabulary around it.

TermSourceOne line
ViewKruchten, ISO 42010, V&BA representation of the system from one set of concerns
ViewpointISO 42010, Rozanski and WoodsThe conventions (notation, rules, concerns) for building one kind of view
Stakeholder / concernISO 42010Who has an interest / what that interest is
Model (view component in 2022)ISO 42010One diagram or text inside a view
CorrespondenceISO 42010; V&B "mapping between views"A recorded link between elements of different views
Module / C&C / allocationSEI Views and BeyondCode units / runtime elements / mapping to non-software things
C4Simon BrownContext, Container, Component, Code diagrams plus deployment and dynamic
arc42arc42 templateTwelve sections; 5 building block, 6 runtime, 7 deployment

Why it exists ​

Open any wiki and you will find "the architecture diagram": boxes, arrows, a database cylinder, a cloud icon. Kruchten opens his paper with exactly that picture and asks what the boxes are: "Are the boxes representing running programs? Or chunks of source code? Or physical computers? Or merely logical groupings of functionality? Are the arrows representing compilation dependencies? Or control flows? Or data flows? Usually it is a bit of everything." A picture that mixes all of these answers none of them: the developer cannot see which package may import which, the operator cannot see which process runs on which node, and the product owner cannot see where the discount rule lives.

One overloaded diagramSeveral views plus scenarios
Fast to draw, slow to readEach view is small and has one audience
Arrows mean "something"Each view fixes the meaning of boxes and arrows
Nobody can check it against codeDevelopment and physical views can be generated or tested
Hides concurrency and deployment risksProcess and physical views force those questions
Gets stale silentlyEach view has an owner and a source of truth
Good for: a pitch slideGood for: building, operating and changing a real system
Logical viewWhat the system doesStakeholders: end-users, analystsConcern: functionalityUML: class, state, (package)Development viewHow the code is organizedStakeholders: programmers, managersConcerns: organization, reuse, portabilityUML: package, componentProcess viewWhat runs concurrentlyStakeholders: integrators, system designersConcerns: performance, availabilityUML: activity, sequence, (component)Physical viewWhere it runsStakeholders: system engineers, opsConcerns: topology, scalabilityUML: deploymentScenarios (+1)use cases that driveand validate all fourclass to moduleprocess to nodeobject to taskimage to node

The picture is the shape of Kruchten's Figure 1: four views around the scenarios. The dashed lines are the correspondences the paper describes (classes to modules, objects to tasks, processes to nodes); the solid spokes are the scenarios touching every view.

The analogy we reuse on this page: the drawings of a house. An architect does not hand a builder one drawing. There is a floor plan (rooms and what they are for: the logical view), the electrical and plumbing plans (what flows where while the house is in use: the process view), the construction plan with trades and phases (who builds which part in what order: the development view), and the site plan (where the house sits on the plot and how it connects to the street, water and power: the physical view). The family then walks through a typical day, "wake up, shower, cook, leave", on all the plans at once (the scenarios): if the shower is on the floor plan but has no pipe on the plumbing plan, the walk-through finds it. arc42 uses the same image: its building block view "is the floor plan".

Three common misunderstandings, up front ​

  1. "4+1 means I must draw five diagrams for every system." Kruchten himself: "Not all software architecture need the full “4+1” views." The physical view can go if there is one processor, the process view if there is one process. The scenarios are the one view he keeps "in all circumstances".
  2. "The logical view is the class diagram of the code." It is the key abstractions of the problem domain at architectural significance: a few dozen classes for a big system, grouped into categories. The code-level class diagram is design, not architecture.
  3. "4+1 is a UML thing." The 1995 paper uses Booch notation and Rational Rose; UML did not exist yet. The mapping to UML diagram types came later through the Rational Unified Process and practice. Any notation works if each view has a key.

Where it comes from ​

Perry and Wolf, 1992. Foundations for the Study of Software Architecture (ACM Software Engineering Notes) gave the formula Kruchten builds on, as he quotes it "modified by Boehm": "Software architecture = {Elements, Forms, Rationale/Constraints}". Kruchten applies it per view: for each view, choose the element types (components, containers, connectors), the forms and patterns, and the rationale.

Kruchten, 1995. Philippe Kruchten, then at Rational Software Corp., published Architectural Blueprints—The "4+1" View Model of Software Architecture in IEEE Software 12(6), November 1995, pp. 42–50. The examples come from a PABX (a telephone switch, from work at Alcatel) and air traffic control systems (Hughes Aircraft of Canada). The paper says the model "has been used with success on several large projects" and that other proposed views "could usually be folded into one of the 4": a cost and schedule view into the development view, a data view into the logical view, an execution view into process plus physical.

RUP. The Rational Unified Process adopted 4+1 as its architecture description backbone; the SEI's technical notes say "the Rational Unified Process (RUP), which is based on Kruchten's 4+1 view approach". The paper's own Software Architecture Document outline (its Figure 13) follows the views section by section; see Mechanics.

IEEE 1471-2000 → ISO/IEC/IEEE 42010. The standard generalized the idea: it does not prescribe a fixed set of views but the concept of a viewpoint, chosen from stakeholders' concerns. The 2011 edition is ISO/IEC/IEEE 42010:2011; a second edition appeared in 2022, which renamed "Architecture Model" to "View Component" and generalized "System of Interest" to "Entity of Interest" (per the standard's maintainers' site). That site lists "Kruchten's 4+1 View Model" as an example of an architecture framework.

SEI Views and Beyond, 2002 and 2010. Clements, Bachmann, Bass, Garlan, Ivers, Little, Merson, Nord and Stafford's Documenting Software Architectures: Views and Beyond (2nd edition dated October 5, 2010 on the SEI page) groups views into module, component-and-connector and allocation, and adds the documentation that goes "beyond" views. The SEI technical notes we read describe 4+1 as one of the approaches that "prescribe a fixed set of views", while V&B lets the architect pick "whatever views are useful for the system at hand".

Rozanski and Woods. Software Systems Architecture builds a catalogue of viewpoints (Context, Functional, Information, Concurrency, Development, Deployment, Operational) and adds perspectives for quality properties that cut across views. Their site says: "In his introductory paper, Kruchten defined four standard views, namely, Logical, Process, Physical, and Development."

C4, 2010s. Simon Brown's history page traces the C4 diagrams to his workshops, with a QCon London 2010 workshop and the hierarchy "systems, containers, components, and classes" appearing by 2011. The C4 FAQ says plainly that "the C4 model was inspired by UML and the 4+1 model for software architecture".

arc42. A free template with twelve sections; its sections 5, 6 and 7 (building block, runtime, deployment views) are where the 4+1 views land when a team uses arc42.

text
     Year      Idea                                          What changed in practice
1    1992      Perry & Wolf: elements, forms, rationale       Architecture as a structure plus reasons
2    1995      Kruchten: 4 views + scenarios                  One description per audience
3    2000      RUP book (cited by the SEI as Kruchten 00)     Software Architecture Document template
4    2000      IEEE 1471: viewpoint, view, concern            Views chosen from stakeholder concerns
5    2002/2010 SEI Views and Beyond                           Module / C&C / allocation + docs beyond views
6    2000s     Rozanski & Woods                               Viewpoint catalogue + quality perspectives
7    2010+     C4 model                                       Developer-friendly zoom levels, notation-free
8    2011      ISO/IEC/IEEE 42010:2011                        International standard for architecture descriptions
9    2022      42010 second edition                           Entity of interest, view components, aspects

The concept catalogue ​

Each block follows the same order: plain words, the usual wrong belief, a precise definition, a sequence, real scenarios, what provides it in today's tools, and how to produce it. The running example is the online ordering platform from the worked example.

Logical view Must-know ​

In plain words: the logical view is the map of what the system is about: the key business concepts, the responsibilities, and which part asks which other part for what. No threads, no servers, no folders.

Common misunderstanding: "The logical view is the full class diagram generated from the code." Kruchten's notation is "considerably simplified to take into account only the items that are architecturally significant"; his air traffic control example shows "8 class categories" at the top level of "a much bigger system, which contains a few dozen classes of architectural significance". A generated diagram of 400 classes is a detail you look up in the IDE, not a view.

Definition: "The logical architecture primarily supports the functional requirements—what the system should provide in terms of services to its users." The system is decomposed into "key abstractions, taken (mostly) from the problem domain", using abstraction, encapsulation and inheritance; related classes are grouped into class categories. The paper allows a non-object form: "Alternatively to an OO approach, an application that is very data-driven may use some other form of logical view, such as E-R diagrams." Kruchten's main style guideline: "keep a single, coherent object model across the whole system".

AspectLogical view
ElementsClasses, class categories (today: modules, bounded contexts, aggregates)
ConnectorsAssociation, usage, composition, inheritance, instantiation
StakeholdersEnd-users, analysts, domain experts, product owners
ConcernsFunctionality, responsibilities, the vocabulary of the business
Notation then / todayBooch class diagrams and templates in Rational Rose / UML class, object and state machine diagrams, E-R diagrams, C4 component diagrams
Typical diagramsTop-level module map, domain class sketch per module, state machine of the main entity, E-R for the core tables
Questions it answersWhere does a business rule live? Which module owns which data? What does "order" mean here?
Questions it does not answerHow many processes, which folder, which server
text
     Feature request: "gold customers get free shipping"     Logical view question at each step
1    Product owner describes the rule                        Which concept owns "free shipping"? Shipping or Ordering?
2    Architect looks at the module map                       Shipping computes cost; Ordering only asks for a quote
3    Team adds Customer.tier to the Catalog/Customer model   New attribute in an existing abstraction, no new module
4    Shipping.Quote(order, tier) changes                     Responsibility stays inside one module
5    Scenario S1 is replayed on paper                        The interaction diagram still has the same arrows

Real scenarios:

  • Checkout logic duplicated in the web controller and the mobile API: the logical view shows that "pricing" has no home; give it a module.
  • A data-heavy reporting system: use an E-R diagram as the logical view, as Kruchten allows, and keep classes for the few services.
  • Two teams both "own" the customer address: the logical view must give it one owner and show who reads it.
  • Order status changes in five places: a state machine in the logical view makes the legal transitions explicit (pending → confirmed or rejected → shipped).

What provides it today:

ContextWhere the logical view lives
GoPackage names and exported types (ordering.Order, ordering.Service), ports as small interfaces owned by the consumer
Laravelapp/Modules/<Name>/Domain (Eloquent models, enums, value objects), Application (use cases), Api (contracts)
UMLClass diagram, state machine, package diagram for categories
C4System context (scope) and component diagrams inside one container
DDDBounded contexts and aggregates (see the DDD path)
DataThe core schema as DDL or an E-R diagram

How to produce it: list the scenarios first, underline the nouns and verbs, keep the abstractions that appear in more than one scenario, group them into five to nine categories, and draw only the arrows a scenario needs. For a data-driven core, the DDL is part of the logical view:

sql
-- Logical view, data form (Kruchten: "E-R diagrams" for data-driven systems).
-- PostgreSQL 17. Ownership: the Ordering module owns these three tables.
CREATE TABLE orders (
    id           text PRIMARY KEY,               -- ULID from the application
    customer_id  text        NOT NULL,
    total_cents  bigint      NOT NULL CHECK (total_cents >= 0),
    status       text        NOT NULL CHECK (status IN ('pending', 'confirmed', 'rejected', 'shipped')),
    created_at   timestamptz NOT NULL DEFAULT now(),
    updated_at   timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE order_lines (
    order_id     text    NOT NULL REFERENCES orders (id),
    sku          text    NOT NULL,
    quantity     integer NOT NULL CHECK (quantity > 0),
    price_cents  bigint  NOT NULL CHECK (price_cents >= 0),
    PRIMARY KEY (order_id, sku)
);

-- The outbox belongs to the same module and the same transaction (process view, step 4).
CREATE TABLE outbox (
    id          bigserial PRIMARY KEY,
    type        text        NOT NULL,
    payload     jsonb       NOT NULL,
    created_at  timestamptz NOT NULL DEFAULT now(),
    sent_at     timestamptz
);
CREATE INDEX outbox_unsent ON outbox (id) WHERE sent_at IS NULL;

The Go and Laravel expressions of the same view are in Go (internal/ordering) and Laravel (app/Modules/Ordering/Domain).

Process view Must-know ​

In plain words: the process view shows what runs at the same time, what waits for what, and how the running pieces talk: requests, threads, workers, queues, timeouts, retries.

Common misunderstanding: "Process view means the business process (BPMN)." Kruchten's "process" is an operating-system-level unit of execution: "A process is a grouping of tasks that form an executable unit." The business workflow is a scenario; the process view is about concurrency and distribution.

Definition: "The process architecture takes into account some non-functional requirements, such as performance and availability. It addresses issues of concurrency and distribution, of system's integrity, of fault-tolerance, and how the main abstractions from the logical view fit within the process architecture—on which thread of control is an operation for an object actually executed." Processes are "the level at which the process architecture can be tactically controlled (i.e., started, recovered, reconfigured, and shut down)" and "can be replicated for increased distribution of the processing load, or for improved availability". A task is "a separate thread of control". Major tasks communicate through "synchronous and asynchronous message-based communication services, remote procedure calls, event broadcast, etc."; minor tasks are local (time-outs, buffering). One rule from 1995 that reads like a microservices rule: "Major tasks shall not make assumptions about their collocation in the same process or processing node."

AspectProcess view
ElementsProcesses, tasks/threads, (today: services, pods' main processes, workers, consumers, cron jobs)
ConnectorsMessage, RPC, bidirectional message, event broadcast; (today: HTTP, gRPC, AMQP, Kafka, shared DB as an anti-connector)
StakeholdersSystem designers, integrators, performance engineers, SREs
ConcernsPerformance, availability, software fault tolerance, integrity, throughput, latency budget
Notation then / todayBooch's Ada tasking notation extended, with a "periodic process" adornment / UML sequence, activity and communication diagrams; C4 container and dynamic diagrams
Typical diagramsProcess topology with sync/async arrows, one sequence diagram per critical scenario, a table of timeouts and retries
Questions it answersWhat blocks a request? Which call can time out? What is retried and is it idempotent? What happens if this process crashes mid-way?
text
     One POST /orders inside orders-api (Go)                    Process view property
1    LB picks a pod; net/http starts a goroutine                One thread of control per request
2    context.WithTimeout(ctx, 2s)                               Latency budget for the whole request
3    inventory.Reserve (in-process call, ~1 ms)                 Sync, same process: no network failure mode
4    payments.Authorize -> HTTPS to provider (~300 ms)          Sync, remote: timeout + retry + idempotency key
5    BEGIN; INSERT orders, lines, outbox; COMMIT                Integrity: one local transaction
6    201 returned; goroutine ends                               Nothing else waits on this request
7    outbox-relay ticker (500 ms) reads unsent rows             Separate periodic process, at-least-once
8    shipping-worker consumes OrderPlaced, acks                 Async; crash before ack = redelivery

Real scenarios:

  • A checkout calls four services in a row, each with a 5-second timeout, behind a 10-second load-balancer timeout: only the process view shows the budgets do not add up.
  • Emails sent from inside the web request make checkout slow and fail when the mail server is slow: the process view moves them to a worker.
  • A cron job and a queue worker both process "unsent invoices": the process view shows two threads of control on the same rows, so you add locking.
  • Kruchten's PABX: a 200 ms low-rate scan task and a 10 ms high-rate task inside one controller process, chosen for hard real-time constraints.
  • Kruchten suggests a "hollow" process architecture "with dummy loads for the processes" to measure performance on the target system; today that is a load test against stub services.

What provides it today:

ContextUnit of the process viewConnector
GoOne OS process per binary under cmd/; goroutines as tasks; context deadlinesnet/http, gRPC, channels inside a process, broker clients
Laravel (PHP-FPM)One FPM worker process per request, no shared memory between requestsHTTP, queues (ShouldQueue), events
Laravel Octane (FrankenPHP, Open Swoole, Swoole, RoadRunner)Long-lived workers that serve many requests; --workers, --max-requestsSame, plus in-memory state you must reset
Laravel queue workerphp artisan queue:work process(es)Redis/database/SQS queue drivers
Laravel schedulerphp artisan schedule:work (or cron calling schedule:run)Dispatches jobs or commands
KubernetesContainer main process; replicas; probesServices, DNS

How to produce it: take the logical modules and ask Kruchten's four questions per abstraction: is it active or passive, persistent or transient, subordinate to another object, distributed? Then group with the two strategies in Correspondence. Write down, per arrow: sync or async, timeout, retry policy, idempotency key. Link deep dives instead of re-teaching them: Service Communication, outbox, retries.

Development view Must-know ​

In plain words: the development view is how the code is cut into folders, packages, libraries and repositories, who owns each part, what may depend on what, and how it is built.

Common misunderstanding: "The development view is the same as the logical view, just with file names." Kruchten found the opposite: "The logical and development views are very close, but address very different concerns. We have found that the larger the project, the greater the distance between these views." His example: the "External interfaces—Gateway" category is spread over several layers, from protocol subsystems in layer 1 to specific gateways in layer 5.

Definition: "The development architecture focuses on the actual software module organization on the software development environment. The software is packaged in small chunks—program libraries, or subsystems—that can be developed by one or a small number of developers." Subsystems are organized in layers, "each layer providing a narrow and well-defined interface to the layers above it". Even before all modules are known, it is "possible to list the rules that govern the development architecture: partitioning, grouping, visibility". Its concerns are "internal requirements related to the ease of development, software management, reuse or commonality, and to the constraints imposed by the toolset, or the programming language". It "serves as the basis for requirement allocation, for allocation of work to teams (or even for team organization), for cost evaluation and planning, for monitoring the progress of the project, for reasoning about software reuse, portability and security. It is the basis for establishing a line-of-product." Style advice: "We recommend adopting a layered style for the development view, defining some 4 to 6 layers of subsystems", where a subsystem may depend only on subsystems in the same layer or below. Sizing heuristic from the paper: "typically 5K to 20K SLOC per subsystem".

AspectDevelopment view
ElementsModules, subsystems, layers, libraries; (today: Go packages and modules, Composer packages, Laravel modules, repositories, build targets, images)
ConnectorsCompilation dependency ("with", "include", import, use)
StakeholdersDevelopers, tech leads, project and configuration managers, security reviewers
ConcernsOrganization, reuse, portability, build time, team ownership, release strategy
Notation then / todayBooch module/subsystem diagrams, Rational Apex enforced the rules / UML package and component diagrams, C4 component, a generated import graph, a repo tree
Typical diagramsLayer diagram with allowed dependencies, module ownership table (CODEOWNERS), build pipeline
Questions it answersWhere do I put new code? May ordering import payments/internal? Who reviews this folder? What gets rebuilt?
text
     A pull request that breaks the development view            What catches it
1    Dev adds `import ".../payments/internal/gateway"` in ordering
2    go build                                                   Go: "use of internal package ... not allowed"
3    (Laravel) `use App\Modules\Payments\Internal\...`           PHP does not stop it at compile time
4    CI runs tests: archtest / Pest arch()                      Rule table = the development view, fails the build
5    CI runs viewgen + git diff                                 Generated diagram changed: reviewer sees a new arrow
6    Reviewer either rejects or updates the rule + ADR          The view changes on purpose, not by accident

Real scenarios:

  • Twelve teams in one repository: the development view assigns folders to teams (and CODEOWNERS enforces review), which is how Kruchten's "allocation of work to teams" looks today.
  • A Laravel app where every model is used everywhere: drawing the development view shows a ball of mud; a modular monolith with Api/ and Internal/ folders and Pest arch() rules fixes the shape.
  • A product line (white-label shop for several brands): Kruchten's line-of-product idea; shared layers 1–2, brand-specific layer at the top.
  • Build takes 40 minutes: the development view shows which modules trigger which builds and what can be cached.
  • Splitting a service later: if the development view already has a module with a narrow API, the split is "move the folder, put a network client behind the same interface".

What provides it today:

MechanismGoLaravel / PHP
Hidinginternal/ directories (compiler-enforced)Convention (Internal/ namespace) + Pest arch() or Deptrac
Module boundaryGo module (go.mod), packageComposer package, app/Modules/<Name> + service provider
Dependency rulesgo vet-clean import graph + a test like archtestPest arch()->expect(...)->not->toUse(...), Deptrac layers and rulesets
Entry pointscmd/<binary>/main.go (composition root)routes/, bootstrap/app.php, bootstrap/providers.php
Buildgo build ./cmd/..., one image per commandOne image, several commands (web, worker, scheduler)
OwnershipCODEOWNERSCODEOWNERS

How to produce it: start from the rules (partitioning, grouping, visibility), not from the full tree. Write the allowed-dependency table, put it in a test, then draw the picture from the test or generate it (Mechanics).

Physical view Must-know ​

In plain words: the physical view shows the machines, containers, networks and data stores, and which running process sits where.

Common misunderstanding: "There is one physical view." Kruchten: "We expect that several different physical configurations will be used: some for development and testing, others for the deployment of the system for various sites or for different customers." C4 says the same: deployment information is "better captured via one or more deployment diagrams, one per environment". Your laptop, staging and production are three physical views of one architecture.

Definition: "The physical architecture takes into account primarily the non-functional requirements of the system such as availability, reliability (fault-tolerance), performance (throughput), and scalability." The software runs on "a network of computers, or processing nodes"; "networks, processes, tasks, and objects—need to be mapped onto the various nodes". The key requirement: "The mapping of the software to the nodes therefore needs to be highly flexible and have a minimal impact on the source code itself." Kruchten's PABX example shows the same processes mapped onto a small and a large hardware configuration (his Figures 9 and 10).

AspectPhysical view
ElementsProcessors, devices, nodes; (today: VMs, Kubernetes nodes and pods, managed databases, load balancers, zones, regions)
ConnectorsCommunication lines, buses, LAN, WAN; (today: VPC networks, service mesh, VPN, replication links)
StakeholdersSystem engineers, operators, SREs, security, finance (cost)
ConcernsAvailability, reliability, throughput, scalability, topology, latency between nodes, cost
Notation then / todayKruchten's processor/device symbols / UML deployment diagram, C4 deployment diagram, cloud provider icons with a key
Typical diagramsOne deployment diagram per environment; zone/region layout; data replication paths
Questions it answersWhat fails together? Where is the primary? What is the blast radius of a zone outage? Which network hop is slow?
text
     Zone A goes down (production physical view)                 What the view must already show
1    2 of 3 orders-api pods disappear                            Replicas spread over zones (topologySpreadConstraints)
2    LB health checks mark them unhealthy                        Readiness probe on /healthz
3    PostgreSQL primary was in zone A                            Standby in zone B + failover procedure
4    Standby promoted; apps reconnect                            Connection strings point at a service, not an IP
5    outbox-relay pod rescheduled in zone B                      Only one relay: singleton, needs leader/lock
6    Broker node 1 lost; quorum (2 of 3) remains                 Three nodes in three zones, quorum queues

Real scenarios:

  • Everything "redundant" but both database nodes share one storage array: only a physical view that shows storage finds the single point of failure.
  • Payment provider requires a fixed egress IP: the physical view must show NAT gateways per zone.
  • A batch job saturates the network link to the database at night: the physical view shows the shared link.
  • Data residency (EU customers' data must stay in EU regions): the physical view is where you prove it.

What provides it today: infrastructure as code is the physical view as code: Dockerfiles (what an image contains), Docker Compose (one environment's topology), Kubernetes manifests or Helm charts (replicas, probes, zones), Terraform (networks, databases). The worked example shows all three for the ordering platform.

How to produce it: draw one diagram per environment; for each node, list the processes from the process view that run on it, how many replicas, and what happens on loss. Keep the mapping data-driven (Kruchten used a tool to change it "without source code modifications"; we use environment variables and manifests).

Scenarios: the "+1" view Must-know ​

In plain words: a few important stories (use cases) are walked through all four views; they are how you find the architecture in the first place and how you prove it holds.

Common misunderstanding: "Scenarios are the full list of use cases." They are "a small set of important scenarios", "instances of more general use cases", chosen for risk and criticality. Ten good scenarios beat two hundred user stories.

Definition: Kruchten: "The scenarios are in some sense an abstraction of the most important requirements." The view "is redundant with the other ones (hence the “+1”), but it serves two main purposes": "as a driver to discover the architectural elements during the architecture design" and "as a validation and illustration role after this architecture design is complete, both on paper and as the starting point for the tests of an architectural prototype". Each scenario has a script: "sequences of interactions between objects, and between processes". Critical means "the most important, the raison d’être of the system, or that have the highest frequency of use, or that present some significant technical risk that must be mitigated".

Customerorders-apiinventorypaymentspaymentproviderPostgreSQLoutbox-relaybrokershipping-worker1 POST /orders2 reserve(lines)3 authorize(total)3a HTTPS, 2 s timeoutauth id4 BEGIN; orders+lines+outbox; COMMIT5 201 Created6 poll outbox7 publish OrderPlaced8 deliver9 ackabove: synchronous, inside one request (latency budget); below: asynchronous, eventually consistentViews exercised: steps 1-5 logical (Order, ports) + process (one goroutine, sync calls) + physical (LB, pod, DB primary);steps 6-9 process (relay, worker) + physical (broker cluster) + development (three images from one module).

The scenario diagram above is S1 of the worked example as a sequence: steps 1–5 run inside one HTTP request, steps 6–9 run later in other processes. Every arrow must exist in another view: the Order and the ports in the logical view, the goroutine and the relay in the process view, the three binaries in the development view, the pods and the database primary in the physical view.

Scenario (ordering platform)Why chosenViews it stresses
S1 Place an order (happy path)Raison d'être, highest frequencyAll four
S2 Item out of stockBusiness rule, must not chargeLogical, process
S3 Payment declined or provider timeoutExternal dependency, moneyProcess, physical (egress)
S4 Outbox relay crashes after publish, before mark-sentDuplicate eventsProcess (idempotent consumer)
S5 Zone A lost during peakAvailabilityPhysical, process
S6 New developer adds a "gift card" payment methodChangeabilityDevelopment, logical

The iterative loop from the paper, as a sequence:

text
     Kruchten's scenario-driven iteration                          Ordering platform, iteration 1
1    Choose a few scenarios by risk and criticality                S1, S3 (money and an external dependency)
2    Put a strawman architecture in place                          One Go binary, PostgreSQL, a fake PSP
3    "Script" the scenarios: (object, operation) pairs             Order.place, Payments.authorize, Store.save
4    Lay the elements on the 4 blueprints                          Draw logical/process/development/physical
5    Implement, test, measure (under load, target env if possible) k6 at 200 orders/s; p99 of step 4 = 900 ms
6    Capture lessons, reassess risks                               PSP latency dominates: add timeout + async capture?
7    Next iteration: add scenarios, update all 4 views             S4, S5; outbox relay appears in process view
8    Stop when no new abstractions, processes, interfaces appear   Kruchten: "after 2 or 3 iterations"

How to produce it: write three to six scenarios as numbered scripts; for each step note the element in every view it touches; turn each into an automated test (an acceptance test for the logical/process part, a chaos or failover drill for the physical part). The Go section shows S1–S3 as tests and the Laravel section S1 and S3.

Correspondence between views Important ​

In plain words: the views are not independent drawings; every class lands in some module, runs in some process, on some node. Writing those links down is what keeps four drawings one architecture.

Common misunderstanding: "If the views are separate, they can be designed by separate people independently." The paper: "The various views are not fully orthogonal or independent. Elements of one view are connected to elements in other views, following certain design rules and heuristics."

Definition: Kruchten describes three mappings. Logical to process: classify each class by autonomy (active, passive, protected), persistence, subordination and distribution, then cluster with two strategies used together: inside-out ("Starting from the logical architecture: define agent tasks which multiplex a single thread of control") and outside-in ("Starting with the physical architecture: identify external stimuli (requests) to the system, define client processes to handle the stimuli and servers processes that only provide services and do not initiate them"). Logical to development: "A class is usually implemented as a module"; class categories become subsystems, adjusted for team organization, code size, reuse and layering, so there is usually no one-to-one correspondence. Process to physical: processes and process groups are mapped onto hardware "in various configurations for testing or deployment". ISO 42010 later formalized this as correspondences and correspondence rules; V&B calls it "mapping between views".

text
     Element (logical)    Development (module)         Process (thread of control)          Physical (node)
1    Order, OrderLine     internal/ordering            orders-api request goroutine          orders-api pods, zones A+B
2    PaymentsApi          internal/payments            same goroutine, HTTPS call to PSP     orders-api pods; egress NAT
3    OutboxEvent          internal/platform/outbox     outbox-relay (periodic, single)       1 pod, any zone
4    Shipment             internal/shipping            shipping-worker (consumer x2)         worker pods
5    (data) orders table  migrations in ordering       PostgreSQL backend processes          primary zone A, standby zone B

Real scenario: an incident review asks "which code runs on the node that ran out of memory?" Without a correspondence table, nobody can answer quickly; with it, the answer is a lookup. Microservices make this table trivial for development-to-process (one repo, one process) and critical for process-to-physical (hundreds of pods).

How to produce it: keep the table above in the architecture document; generate the development-to-process column from build files (cmd/ directories, Compose command: lines) and the process-to-physical column from manifests.

Viewpoints and views: ISO/IEC/IEEE 42010 Important ​

In plain words: 42010 is the standard that explains the words: a stakeholder has concerns; a viewpoint is the recipe for answering some concerns; a view is that recipe applied to your system; a view contains models (diagrams, tables, text).

Common misunderstanding: "View and viewpoint are synonyms." A viewpoint is reusable across systems ("the deployment viewpoint: nodes, links, these symbols, these questions"); a view is specific ("the production deployment of the ordering platform"). 4+1 is, in 42010 terms, an architecture framework that fixes five viewpoints.

Definition (quoted from the standard's maintainers' conceptual model page):

ConceptDefinition (quoted)
Architecture"fundamental concepts or properties of a system in its environment embodied in its elements, relationships, and in the principles of its design and evolution"
Architecture description"a work product used to express the Architecture of some System Of Interest"
Stakeholder"individuals, groups or organizations holding Concerns for the System of Interest"
Concern"any interest in the system"
Architecture viewpoint"a set of conventions for constructing, interpreting, using and analyzing one type of Architecture View"
Architecture view"expresses the Architecture of the System of Interest from the perspective of one or more Stakeholders to address specific Concerns, using the conventions established by its viewpoint"
Model kind"defines the conventions for one type of Architecture Model"
Correspondence"express a relation between AD Elements"
Architecture rationale"records the explanation, justification or reasoning about Architecture Decisions that have been made and architectural alternatives not chosen"
Architecture framework"establishes a common practice for creating, interpreting, analyzing and using architecture descriptions"; examples include "Kruchten’s 4+1 View Model"

The 2022 second edition (per the same site): "Architecture Model is changed to View Component", the subject is an "Entity of Interest" instead of a "System of Interest", and it adds "Stakeholder Perspectives" (to group concerns) and "Architecture Aspects".

text
     42010 chain for the ordering platform
1    Stakeholder: SRE team
2    Concern: "what is lost if one availability zone fails?"
3    Viewpoint: deployment (model kinds: node diagram, replica table; rule: one diagram per environment)
4    View: "Production deployment, eu-central, November 2026"
5    Models: the physical SVG + the Kubernetes manifests + the replica/failover table
6    Correspondence: process "orders-api" -> 3 pods, zones A, A, B
7    Rationale: ADR-0012 "standby in a second zone, not a second region"

Real scenario: a regulator asks for "the architecture documentation". A 42010-shaped answer lists stakeholders and concerns first, then which viewpoint answers each concern, then the views. That list is also the table of contents of a good 4+1 document.

Views and Beyond: module, component-and-connector, allocation Important ​

In plain words: the SEI approach groups every possible view into three families: how the code is cut (module), what runs and talks (component-and-connector, C&C), and how software maps to things that are not software (allocation). Then it adds the documents that span views.

Common misunderstanding: "V&B replaces 4+1." It generalizes it: the SEI note says some authors "prescribe a fixed set of views" (it names RUP/4+1 and the Siemens Four Views), while "architects should produce whatever views are useful for the system at hand". The 4+1 views fit into the three families.

Definition (from the SEI technical notes CMU/SEI-2005-TN-017 and CMU/SEI-2003-TN-023): "Documenting an architecture is a matter of documenting the relevant views and then adding documentation that applies to more than one view."

V&B familySEI wordingTypical styles4+1 counterpart
Module views"how the system is to be structured as a set of code units"Decomposition, uses, generalization, layered, data modelLogical (decomposition, data) and development (layers, uses)
Component-and-connector (C&C) views"how the system is to be structured as a set of interacting runtime elements"Pipe-and-filter, client-server, publish-subscribe, shared dataProcess
Allocation views"how the system relates to non-software structures in its environment"Deployment, implementation (files), work assignmentPhysical (deployment), development (work assignment, files)

Choosing views is a three-step procedure: (1) build a stakeholder/view table and mark for each cell "none, overview only, or detailed"; (2) combine views with weak constituencies or strong element correspondence ("combined view"); (3) prioritize. Each view uses a standard template: primary presentation (with a key), element catalog, context diagram, variability guide, rationale, other information. The "beyond views" part has: documentation roadmap, view template, system overview, mapping between views, directory, glossary and acronym list.

text
     Stakeholder/view table (V&B step 1) for the ordering platform
     stakeholder        decomposition  uses   C&C    deployment  work assignment
1    product owner      overview       none   none   none        none
2    new developer      detailed       detail overv  none        overview
3    SRE                none           none   detail detailed    none
4    security reviewer  overview       overv  detail detailed    none
5    engineering mgr    overview       none   none   overview    detailed
     -> combine uses + decomposition; deployment is mandatory; work assignment = CODEOWNERS table

C4 model Must-know ​

In plain words: C4 is a zoom: system context (the system and who uses it), containers (apps and data stores), components (inside one container), code; plus deployment and dynamic diagrams. It is the most common way teams draw the 4+1 content today.

Common misunderstanding: "A C4 container is a Docker container." The C4 site says "Not Docker!": "a container represents an application or a data store", for example a server-side web application, a single-page app, a database schema or an S3 bucket.

Definition: "A set of hierarchical abstractions - software systems, containers, components, and code", "a set of hierarchical diagrams - system context, containers, components, and code" and "an additional set of supporting diagrams - system landscape, dynamic, and deployment"; "Notation independent" and "Tooling independent". The site recommends only what adds value: "the system context and container diagrams are sufficient for most software development teams". The dynamic diagram "is based upon a UML communication diagram"; the deployment diagram is "based upon a UML deployment diagram". The C4 FAQ: "the C4 model was inspired by UML and the 4+1 model for software architecture".

C4 diagramRecommended? (c4model.com)Closest 4+1 view
System contextYesScope for all views; logical at the widest zoom
ContainerYesProcess (runtime units and how they talk) with some physical hints
Component"No, only create component diagrams if you feel they add value"Logical inside one container; development
Code"No, particularly for long-lived documentation"Logical/development at design level
DeploymentYesPhysical
Dynamic"No, dynamic diagrams should be used sparingly"Scenarios

The deeper comparison of C4 and UML notations is in UML and the C4 model.

arc42 Good to know ​

In plain words: arc42 is a fill-in template with twelve numbered sections; three of them are the 4+1 views under other names.

Common misunderstanding: "arc42 and 4+1 compete." arc42 is a document structure; 4+1 is a set of views; you can put 4+1 views into arc42 sections.

arc42 sectionWhat it holds (from docs.arc42.org)4+1 counterpart
1 Introduction and GoalsRequirements, stakeholders, top quality goalsScenario selection input
3 Context and ScopeBusiness and technical context, external interfacesC4 context; physical (technical context)
4 Solution StrategyFundamental decisions and ideasRationale across views
5 Building Block View"static decomposition of the system into building blocks"; "mandatory"; "the floor plan"Logical + development
6 Runtime ViewScenarios: use cases, critical interfaces, start-up, errorsProcess + scenarios
7 Deployment ViewInfrastructure and "the mapping of (software) building blocks to that infrastructure"Physical
8 Crosscutting ConceptsRecurring patterns and practicesRozanski and Woods perspectives
9 Architecture DecisionsADRsRationale
10 Quality RequirementsQuality scenariosScenarios
11 Risks and Technical DebtKnown problemsInput to the next iteration
12 GlossaryTermsLogical view vocabulary

Rozanski and Woods: viewpoints and perspectives Good to know ​

In plain words: a catalogue of ready viewpoints for information systems, plus perspectives: checklists for qualities (security, availability, performance) that you apply across all views instead of drawing a "security view".

Common misunderstanding: "Security needs its own view." Their site: "trying to address these aspects of an architecture by using viewpoints doesn’t work well"; a perspective is "a collection of activities, tactics, and guidelines that are used to ensure that a system exhibits a particular set of related quality properties that require consideration across a number of the system’s architectural views".

Rozanski and Woods viewpointDescribes (their site)4+1 counterpart
ContextRelationships with the environmentC4 context
Functional"functional elements, their responsibilities, interfaces, and primary interactions"Logical
Information"the way that the architecture stores, manipulates, manages, and distributes information"Logical (data form)
ConcurrencyMaps "functional elements to concurrency units"Process
DevelopmentSupports "the software development process"Development
Deployment"the environment into which the system will be deployed"Physical
Operational"how the system will be operated, administered, and supported"Physical + runbooks (missing in 4+1)

Their warning matches Kruchten's opening: "It is not possible to capture the functional features and quality properties of a complex system in a single comprehensible model that is understandable by and of value to all stakeholders."

Mapping 4+1 to UML, C4, Views and Beyond, arc42 ​

4+1 viewUML diagramsC4 modelViews and Beyondarc42 sectionR&W viewpointLogicalclass, object, statecontext, component,codemoduledecomposition, uses5 building block(whitebox)Functional,InformationProcesssequence, activity,communicationcontainer, dynamicC&C (client-server,pub-sub)6 runtimeConcurrencyDevelopmentpackage, componentcomponent, codemodule (layered),allocation: work5 building block, 8conceptsDevelopmentPhysicaldeploymentdeploymentallocation:deployment7 deploymentDeployment,OperationalScenariosuse case, sequencedynamicbehaviour docs,quality scenarios6 runtime, 10quality(perspectives,Context)Synthesis by this page: Kruchten (1995) used Booch notation, not UML; C4, V&B, arc42 and R&W do not define a 1:1 mapping.

The table is our synthesis. Kruchten (1995) predates UML and used Booch notation; RUP and later practice attached UML diagram types to the views; C4, V&B, arc42 and Rozanski and Woods each define their own sets, and none publishes an official one-to-one mapping to 4+1. Use it as a translation aid, not as a rule.

4+1 viewUML diagram types (see UML in Practice)Why that diagram
LogicalClass, object, state machineAbstractions, relationships, life cycle of the main entity
ProcessSequence, activity, communicationWho calls whom, in which order, in parallel or not
DevelopmentPackage, componentCode units and their dependencies
PhysicalDeploymentNodes, artifacts, communication paths
ScenariosUse case, sequenceThe story and its script

Mechanics ​

The Software Architecture Document outline Important ​

Kruchten's paper ends with the document that carries the views (his Figure 13) and a second document, the Software Design Guidelines, which "captures (among other things) the most important design decisions that must be respected to maintain the architectural integrity of the system".

Section (Kruchten, Fig. 13)What to write todayWhere it usually lives
1 Scope, 2 ReferencesSystem in one paragraph, linksdocs/architecture/README.md
3 Software ArchitectureStyle in two sentences + C4 context diagramSame
4 Architectural Goals and ConstraintsTop 3–5 quality goals, hard constraintsarc42 sections 1–2
5 Logical ArchitectureModule map, core schema, state machinedocs/architecture/logical.md
6 Process ArchitectureProcess topology, timeouts and retries tableprocess.md
7 Development ArchitectureLayer and dependency rules, ownership, pipelinedevelopment.md + archtest + CODEOWNERS
8 Physical ArchitectureOne deployment diagram per environmentphysical.md + deploy/
9 Scenarios3–6 scripted scenarios, each linked to a testscenarios.md + tests
10 Size and PerformanceLoad assumptions, measured numbersLoad test reports
11 QualityQuality scenarios and how they are verifiedarc42 section 10
Appendices: acronyms, definitions, design principlesGlossary; principles; ADR indexdocs/adr/

Choosing the views: a three-step procedure ​

text
     Step                                     Output for the ordering platform
1    List stakeholders and their concerns     PO: functionality; devs: where code goes; SRE: zone loss; security: data flows
2    Match each concern to a view             logical, development, process, physical (prod + staging), scenarios
3    Apply Kruchten's tailoring rules         1 process + 1 server? drop process and physical (not our case)
4    Combine weak views (V&B step 2)          logical + development as one module map with folder names
5    Prioritize (V&B step 3)                  process + physical first (risk), then development rules
6    Decide the source of truth per view      code, manifests, tests, or a hand-drawn diagram with an owner

Diagrams as code, and views generated from code Must-know ​

A view that lives in a drawing tool goes stale the day after the review. Three techniques keep it honest:

TechniqueTool examplesWhich viewsStaleness check
Text diagrams in the repositoryMermaid (C4Context, C4Container, C4Deployment, C4Dynamic), C4-PlantUML, Structurizr DSLAllReviewed in the same pull request as the code
Generated from sourceImport graph (our viewgen), IDE class diagrams, Deptrac's dependency graphDevelopment, logical (code level)Regenerate in CI, git diff --exit-code
Generated from infrastructure as codeCompose files, Kubernetes manifests, Terraform statePhysicalDiagram built from the same files that deploy
Executable rulesarchtest (Go), Pest arch(), DeptracDevelopmentTest fails on a forbidden import
Executable scenariosAcceptance tests, contract tests, chaos drillsScenarios, processTest fails when the story breaks

Mermaid's C4 support states that its "C4 diagram syntax is compatible with plantUML" and supports C4Context, C4Container, C4Component, C4Dynamic and C4Deployment. Structurizr DSL "provides a way to define a software architecture model (based upon the C4 model) using a text-based domain specific language". The container view of the ordering platform as Mermaid source, stored next to the code:

mermaid
C4Container
title Online ordering platform - containers (modular monolith, step 2 of 3)
Person(customer, "Customer", "Buys products in a browser or the app")
System_Ext(psp, "Payment provider", "Authorizes cards")
Container_Boundary(shop, "Ordering platform") {
  Container(api, "orders-api", "Go, net/http", "Catalog, cart, ordering, payments modules")
  Container(relay, "outbox-relay", "Go", "Publishes committed events")
  ContainerDb(db, "shop", "PostgreSQL 17", "orders, order_lines, outbox")
  ContainerQueue(mq, "events", "RabbitMQ 4", "OrderPlaced, PaymentAuthorized")
}
Rel(customer, api, "Places orders", "HTTPS/JSON")
Rel(api, psp, "Authorizes payment", "HTTPS")
Rel(api, db, "Reads and writes", "SQL")
Rel(relay, db, "Polls outbox", "SQL")
Rel(relay, mq, "Publishes", "AMQP 0-9-1")

Keeping the five views in sync Must-know ​

ViewSource of truthGenerated or checked byWho updates by hand
LogicalModule APIs and core schema (DDL, migrations)Schema dump; package listArchitect + module owners, on new module or ownership change
ProcessEntry points (cmd/), queue and topic configuration, timeouts in codeGrep of cmd/, Compose command: linesTeam that adds a process or a connector
DevelopmentDirectory tree, go.mod, composer.json, dependency rulesviewgen + archtest, Pest arch(), DeptracNobody: generated; rule changes need an ADR
PhysicalDockerfiles, Compose, Kubernetes, TerraformRendered from manifestsPlatform team per environment
ScenariosAcceptance tests and drillsCI, game daysProduct + architect, per iteration

Failure messages you will actually see ​

WhereMessageWhich view was violated
Go compileruse of internal package m/a/internal/x not allowedDevelopment (visibility rule)
Go test (this page)../../internal/ordering/zz_violation.go imports internal/payments: not allowed by the development viewDevelopment (dependency rule)
Pesta failed arch() expectation naming the class and the forbidden namespace (wording varies by Pest version)Development
CI (git diff --exit-code after viewgen)non-zero exit and a diff of the .mmd fileDevelopment diagram stale
Kubernetes eventsprobe failures such as Liveness probe failed: ... (readiness failures are reported the same way)Physical (health contract between process and node)
Go contextcontext deadline exceededProcess (latency budget)
Laravel containerTarget [App\Modules\Payments\Api\PaymentsApi] is not instantiableDevelopment (module provider not registered in bootstrap/providers.php)

Worked example: an online ordering platform in all five views ​

The system. A web shop: customers browse a catalog, place orders, pay by card through an external payment provider, and get their parcel shipped. Quality goals: an order must never be charged without being recorded (integrity), checkout p99 under 1.5 s at 200 orders/s (performance), survive the loss of one availability zone (availability), and let three teams work without stepping on each other (changeability). Today it is a modular monolith in Go (the Laravel variant is the same shape); the views are written so that a later split into services changes the process and physical views, not the logical one.

Logical view of the example ​

CatalogProductPrice (cents, currency)Categoryread-mostly, cacheableOrdering (core)Order (aggregate root) id, customerId, totalCentsOrderLine 1..*OrderStatus (state)PlaceOrder (use case)ports: Inventory, Payments, Store (with outbox)PaymentsPaymentAuthorizationPaymentsApi (interface)InventoryStockItemReservation (TTL)WarehouseShippingShipmentCarrierreacts to OrderPlacedpricesauthorizereserveeventpendingconfirmedrejectedshippedOrder status (state machine)

Five class categories. Ordering is the core: Order is the aggregate root with OrderLines and an OrderStatus state machine; PlaceOrder is the use case; it depends on three ports it owns (Inventory, Payments, Store). Catalog provides prices, Inventory reserves stock, Payments authorizes money behind a PaymentsApi interface, Shipping reacts to the OrderPlaced event. The data form is the DDL in the logical view block.

Process view of the example ​

clientsorders-api x31 goroutine per requestdeadline 2 s per requestpayment provider(external)outbox-relay x1periodic: every 500 msbrokerRabbitMQ / Kafkashipping-workerx2, retry+DLQnotify-workerx1, idempotentPostgreSQLorders + outboxHTTPSsync, timeoutSQL tx: order + outboxpoll (SELECT ... FOR UPDATE)publishsync request (RPC, HTTP)async message / eventreplicated processConcerns answered: latency budget, throughput, failure isolation, what blocks what, what is retried.
ProcessReplicasTriggerTalks toTimeout / retryOn crash
orders-api3HTTP requestPSP (sync), PostgreSQL2 s per request; PSP call retried twice with idempotency keyRequest fails; nothing half-written (one transaction)
outbox-relay1Timer, 500 msPostgreSQL, brokerRetries next tickRestarted; resends unsent rows (at-least-once)
shipping-worker2MessageBroker, carrier APIBackoff, then DLQRedelivery; consumer is idempotent on order_id
notify-worker1MessageBroker, email providerBackoffRedelivery; duplicate email suppressed by key

The same view in Laravel has three processes from one image: web (Octane on FrankenPHP or PHP-FPM), queue:work, and schedule:work:

yaml
# PROCESS view made concrete: three processes from the same code base.
services:
  web:
    build:
      context: ..
      dockerfile: deploy/app.dockerfile
    ports:
      - "8000:8000"
    env_file: ../.env
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_started
  worker:
    build:
      context: ..
      dockerfile: deploy/app.dockerfile
    command: ["php", "artisan", "queue:work", "--tries=3"]
    env_file: ../.env
    depends_on:
      - postgres
      - redis
  scheduler:
    build:
      context: ..
      dockerfile: deploy/app.dockerfile
    command: ["php", "artisan", "schedule:work"]
    env_file: ../.env
    depends_on:
      - redis
  postgres:
    image: postgres:17
    environment:
      POSTGRES_USER: shop
      POSTGRES_PASSWORD: shop
      POSTGRES_DB: shop
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U shop"]
      interval: 5s
      retries: 10
  redis:
    image: redis:7-alpine

Development view of the example ​

Layer 3: entry points (one per process)cmd/orders-apicmd/outbox-relayLaravel: routes/, app/Http, bootstrap/Layer 2: modules, one team eachinternal/orderingteam Checkoutinternal/paymentsteam Paymentsinternal/catalogteam CatalogLaravel: app/Modules/Ordering, app/Modules/Paymentsrule: only Api/ is public; never import another module's Internal/Layer 1: platform (shared, no business rules)platform/outboxplatform/httpxplatform/dbLaravel: framework + app/Support; Go: stdlib + a few librariesBuild pipeline (CI)1. go vet ./...2. go test ./...scenario tests (the +1)dependency rules (this view)3. viewgen, git diffstale diagram = red build4. docker build per cmd/orders-api, outbox-relay5. push image taghands over to physical view
text
go/                                  Laravel equivalent
1    go.mod                          composer.json
2    cmd/orders-api/main.go          public/index.php + routes/ (web process)
3    cmd/outbox-relay/main.go        app/Modules/Ordering/Jobs/RelayOutbox.php + routes/console.php
4    internal/ordering/              app/Modules/Ordering/{Domain,Application}
5    internal/payments/              app/Modules/Payments/{Api,Internal}
6    internal/platform/outbox/       app/Support/ (shared, no business rules)
7    internal/archtest/              tests/Architecture/DevelopmentViewTest.php
8    tools/viewgen/                  (Deptrac can render its graph)
9    deploy/                         deploy/

The pipeline that enforces this view is part of it:

yaml
# Development view: the build pipeline is part of "how the software is
# organized in its development environment". Rules from the view run here.
name: ci
on: [push, pull_request]
jobs:
  build:
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: go
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-go@v7
        with:
          go-version-file: go/go.mod
      - run: go vet ./...
      - run: go test ./...            # scenarios + development-view rules
      - run: go run ./tools/viewgen . > ../docs/development-view.mmd
      - run: git diff --exit-code ../docs/development-view.mmd   # stale view = red build
      - run: docker build -f ../deploy/orders.dockerfile --build-arg CMD=orders-api -t shop/orders-api .

Physical view of the example ​

load balancer (L7, TLS)payment provider (external)zone Azone Borders-api podorders-api podoutbox-relay podorders-api podshipping-workernotify-workerPostgreSQL primaryvolume: SSD, PITR backupsPostgreSQL standbyhot standby, failoverbroker node 1broker node 2node 3zone Cstreaming replicationquorum queuesEnvironments are separate physical views: production (this picture), staging (one zone, one replica of each),laptop (Docker Compose: every box above is one container). Same images, different topology.Concerns answered: availability per zone, failover, capacity per node, network paths, where data lives.

The physical view as code. The image (what runs on a node):

dockerfile
# Physical view as code: one image per process from the same Go module.
# Build: docker build -f deploy/orders.dockerfile --build-arg CMD=orders-api -t shop/orders-api .
FROM golang:1.24-alpine AS build
WORKDIR /src
COPY go.mod ./
RUN go mod download
COPY . .
ARG CMD=orders-api
RUN CGO_ENABLED=0 go build -trimpath -o /out/app ./cmd/${CMD}

FROM gcr.io/distroless/static-debian13:nonroot
COPY --from=build /out/app /app
EXPOSE 8080
ENTRYPOINT ["/app"]

The laptop environment (every node is a container):

yaml
# Physical view for ONE environment (a developer laptop): every node of the
# deployment diagram is a service here. Production differs; document both.
services:
  orders-api:
    build:
      context: ../go
      dockerfile: ../deploy/orders.dockerfile
      args:
        CMD: orders-api
    ports:
      - "8080:8080"
    environment:
      DATABASE_URL: postgres://shop:shop@postgres:5432/shop?sslmode=disable
    depends_on:
      postgres:
        condition: service_healthy
  outbox-relay:
    build:
      context: ../go
      dockerfile: ../deploy/orders.dockerfile
      args:
        CMD: outbox-relay
    environment:
      DATABASE_URL: postgres://shop:shop@postgres:5432/shop?sslmode=disable
      AMQP_URL: amqp://guest:guest@rabbitmq:5672/
    depends_on:
      postgres:
        condition: service_healthy
      rabbitmq:
        condition: service_started
  postgres:
    image: postgres:17
    environment:
      POSTGRES_USER: shop
      POSTGRES_PASSWORD: shop
      POSTGRES_DB: shop
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U shop"]
      interval: 5s
      retries: 10
  rabbitmq:
    image: rabbitmq:4-management
    ports:
      - "15672:15672"

The production placement rule (replicas spread across zones, health contract):

yaml
# Physical view for PRODUCTION: replicas, zones and health are architecture
# decisions, and this file is where they are actually enforced.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: orders-api
  labels:
    app: orders-api
spec:
  replicas: 3
  selector:
    matchLabels:
      app: orders-api
  template:
    metadata:
      labels:
        app: orders-api
    spec:
      topologySpreadConstraints:
        - maxSkew: 1
          topologyKey: topology.kubernetes.io/zone
          whenUnsatisfiable: DoNotSchedule
          labelSelector:
            matchLabels:
              app: orders-api
      containers:
        - name: orders-api
          image: registry.example.com/shop/orders-api:1.4.2
          ports:
            - containerPort: 8080
          readinessProbe:
            httpGet:
              path: /healthz
              port: 8080
            periodSeconds: 10
          resources:
            requests:
              cpu: 250m
              memory: 128Mi

topologySpreadConstraints with topologyKey: topology.kubernetes.io/zone and whenUnsatisfiable: DoNotSchedule is the manifest form of the sentence "orders-api survives the loss of one zone"; readinessProbe on /healthz is the contract between the process view (the server answers) and the physical view (the load balancer only sends traffic to ready pods).

Scenarios of the example ​

The S1 sequence is drawn above. S1–S3 are automated below as tests in Go, and S1 and S3 in Laravel; S4 (relay crash) is covered by the idempotent consumer and an integration test that kills the relay between publish and mark-sent; S5 (zone loss) is a quarterly game day that cordons one zone's nodes in staging.

text
     S3 Payment declined (Laravel variant), script across the views
1    Logical: PlaceOrder.handle(customer, lines); total computed in cents
2    Process: web worker calls PaymentsApi::authorize -> Http::timeout(2)->retry(2, 100)
3    Physical: egress from the pod through the zone's NAT to the provider
4    Provider answers 402 -> PaymentDeclined thrown before DB::transaction starts
5    Logical: no Order row, no outbox row; the customer sees "payment declined"
6    Development: the test tests/Feature/PlaceOrderScenarioTest.php (S3) proves it on every build

Go ​

The Go code is one runnable module (docs/snippets/architecture/kruchten-4plus1-views/go); gofmt -l . is empty and go vet ./... and go test ./... pass. Each file says in its header which view it belongs to.

Example: logical view in code ​

go
// Package ordering is the core of the LOGICAL view: the key abstractions
// (Order, Line, Status) and the PlaceOrder use case. It depends only on
// small ports it defines itself; payments, stock and messaging are
// adapters that live elsewhere in the DEVELOPMENT view.
package ordering

import (
	"context"
	"errors"
	"fmt"
	"time"
)

// Status is the life cycle of an order (a state machine in the logical view).
type Status string

const (
	StatusPending   Status = "pending"
	StatusConfirmed Status = "confirmed"
	StatusRejected  Status = "rejected"
	StatusShipped   Status = "shipped"
)

// Line is one product in an order. Money is integer cents.
type Line struct {
	SKU        string
	Quantity   int
	PriceCents int64
}

// Order is the aggregate root of the ordering context.
type Order struct {
	ID         string
	CustomerID string
	Lines      []Line
	TotalCents int64
	Status     Status
	PlacedAt   time.Time
}

// ErrEmptyOrder and ErrOutOfStock are business errors the scenario expects.
var (
	ErrEmptyOrder = errors.New("ordering: order has no lines")
	ErrOutOfStock = errors.New("ordering: out of stock")
)

// Inventory reserves stock (a port; the adapter may be in-process or remote).
type Inventory interface {
	Reserve(ctx context.Context, orderID string, lines []Line) error
}

// Payments authorizes money (a port; owned by ordering, implemented by payments).
type Payments interface {
	Authorize(ctx context.Context, orderID string, cents int64) (authID string, err error)
}

// Store persists the order and its outgoing event in ONE local transaction
// (the transactional outbox), so the process view can relay it later.
type Store interface {
	SaveWithEvent(ctx context.Context, o Order, eventType string, payload []byte) error
}

// Service is the application service that scenario "place order" walks through.
type Service struct {
	Inventory Inventory
	Payments  Payments
	Store     Store
	Now       func() time.Time
	NewID     func() string
}

// PlaceOrder is scenario S1. Each numbered step maps to one arrow in the
// scenario diagram and to one element in the other four views.
func (s Service) PlaceOrder(ctx context.Context, customerID string, lines []Line) (Order, error) {
	if len(lines) == 0 {
		return Order{}, ErrEmptyOrder
	}
	o := Order{ID: s.NewID(), CustomerID: customerID, Lines: lines, Status: StatusPending, PlacedAt: s.Now()}
	for _, l := range lines {
		o.TotalCents += int64(l.Quantity) * l.PriceCents
	}
	// Step 2: reserve stock (logical: Inventory port; process: sync call).
	if err := s.Inventory.Reserve(ctx, o.ID, lines); err != nil {
		return Order{}, fmt.Errorf("reserve stock for %s: %w", o.ID, err)
	}
	// Step 3: authorize payment (process: sync call with a timeout budget).
	if _, err := s.Payments.Authorize(ctx, o.ID, o.TotalCents); err != nil {
		o.Status = StatusRejected
		return o, fmt.Errorf("authorize payment for %s: %w", o.ID, err)
	}
	o.Status = StatusConfirmed
	// Step 4: commit order + OrderPlaced event atomically (physical: one PostgreSQL primary).
	payload := fmt.Appendf(nil, `{"order_id":%q,"total_cents":%d}`, o.ID, o.TotalCents)
	if err := s.Store.SaveWithEvent(ctx, o, "OrderPlaced", payload); err != nil {
		return Order{}, fmt.Errorf("save order %s: %w", o.ID, err)
	}
	return o, nil
}
go
// Package payments is a separate module in the DEVELOPMENT view. In the
// monolith it runs in the same process; after a split it becomes its own
// deployable and only the adapter in cmd/ changes.
package payments

import (
	"context"
	"errors"
	"fmt"
)

// ErrDeclined is returned when the payment provider declines the charge.
var ErrDeclined = errors.New("payments: declined")

// Authorizer talks to the external payment provider (a box outside the
// system boundary in the C4 context diagram).
type Authorizer struct {
	LimitCents int64
}

// Authorize satisfies ordering.Payments without importing ordering:
// the dependency points from ordering's port to this implementation
// only in the composition root (cmd/orders-api).
func (a Authorizer) Authorize(_ context.Context, orderID string, cents int64) (string, error) {
	if cents > a.LimitCents {
		return "", fmt.Errorf("order %s for %d cents: %w", orderID, cents, ErrDeclined)
	}
	return "auth-" + orderID, nil
}

Example: process view in code ​

Two binaries from one module are two processes. orders-api is the request-driven process with a deadline per request and graceful shutdown on SIGTERM:

go
// Command orders-api is one PROCESS (and one container image in the
// PHYSICAL view). main is the composition root: the only place where the
// logical modules are wired to concrete adapters.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"strconv"
	"sync"
	"syscall"
	"time"

	"academy/kruchten-4plus1-views/internal/ordering"
	"academy/kruchten-4plus1-views/internal/payments"
)

// alwaysInStock stands in for the inventory module in this snippet.
type alwaysInStock struct{}

func (alwaysInStock) Reserve(context.Context, string, []ordering.Line) error { return nil }

// memStore stands in for PostgreSQL (orders + outbox tables in one transaction).
type memStore struct {
	mu     sync.Mutex
	orders map[string]ordering.Order
	outbox [][]byte
}

func (m *memStore) SaveWithEvent(_ context.Context, o ordering.Order, _ string, payload []byte) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.orders[o.ID] = o
	m.outbox = append(m.outbox, payload)
	return nil
}

func main() {
	log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
	var seq int64
	var seqMu sync.Mutex
	svc := ordering.Service{
		Inventory: alwaysInStock{},
		Payments:  payments.Authorizer{LimitCents: 500_000},
		Store:     &memStore{orders: map[string]ordering.Order{}},
		Now:       time.Now,
		NewID: func() string {
			seqMu.Lock()
			defer seqMu.Unlock()
			seq++
			return "ord-" + strconv.FormatInt(seq, 10)
		},
	}

	mux := http.NewServeMux()
	// Readiness endpoint used by the PHYSICAL view (load balancer, Kubernetes probe).
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK)
	})
	mux.HandleFunc("POST /orders", func(w http.ResponseWriter, r *http.Request) {
		var req struct {
			CustomerID string          `json:"customer_id"`
			Lines      []ordering.Line `json:"lines"`
		}
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			http.Error(w, "bad json", http.StatusBadRequest)
			return
		}
		// Process view: every request has a deadline that covers the sync calls.
		ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
		defer cancel()
		o, err := svc.PlaceOrder(ctx, req.CustomerID, req.Lines)
		switch {
		case errors.Is(err, ordering.ErrEmptyOrder):
			http.Error(w, err.Error(), http.StatusUnprocessableEntity)
			return
		case errors.Is(err, payments.ErrDeclined):
			http.Error(w, err.Error(), http.StatusPaymentRequired)
			return
		case err != nil:
			log.Error("place order", "err", err)
			http.Error(w, "internal error", http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusCreated)
		_ = json.NewEncoder(w).Encode(o)
	})

	addr := ":" + envOr("PORT", "8080")
	srv := &http.Server{Addr: addr, Handler: mux, ReadHeaderTimeout: 5 * time.Second}
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	go func() {
		log.Info("orders-api listening", "addr", addr)
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Error("listen", "err", err)
			stop()
		}
	}()
	<-ctx.Done()
	// Graceful shutdown: Kubernetes sends SIGTERM before removing the pod.
	shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	_ = srv.Shutdown(shutdown)
}

func envOr(key, def string) string {
	if v := os.Getenv(key); v != "" {
		return v
	}
	return def
}

outbox-relay is the periodic process; the relay loop itself lives in the platform layer:

go
// Package outbox is infrastructure shared by modules (bottom layer of the
// DEVELOPMENT view). The Relay type is what the PROCESS view calls the
// "outbox relay" task: a separate thread of control (its own process in
// production) that moves committed events to the broker.
package outbox

import (
	"context"
	"log/slog"
	"time"
)

// Event is a row of the outbox table.
type Event struct {
	ID      int64
	Type    string
	Payload []byte
}

// Source reads unpublished events and marks them as sent.
type Source interface {
	Pending(ctx context.Context, limit int) ([]Event, error)
	MarkSent(ctx context.Context, id int64) error
}

// Publisher sends one event to the broker (RabbitMQ, Kafka, ...).
type Publisher interface {
	Publish(ctx context.Context, e Event) error
}

// Relay polls Source and publishes to Publisher (at-least-once delivery).
type Relay struct {
	Source    Source
	Publisher Publisher
	Interval  time.Duration
	Batch     int
	Log       *slog.Logger
}

// Run blocks until ctx is cancelled. One Relay per database primary is enough;
// more replicas of this process need a lock (e.g. FOR UPDATE SKIP LOCKED).
func (r Relay) Run(ctx context.Context) error {
	t := time.NewTicker(r.Interval)
	defer t.Stop()
	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-t.C:
			r.tick(ctx)
		}
	}
}

func (r Relay) tick(ctx context.Context) {
	events, err := r.Source.Pending(ctx, r.Batch)
	if err != nil {
		r.Log.Error("outbox read failed", "err", err)
		return
	}
	for _, e := range events {
		if err := r.Publisher.Publish(ctx, e); err != nil {
			r.Log.Warn("publish failed, will retry", "id", e.ID, "err", err)
			return
		}
		if err := r.Source.MarkSent(ctx, e.ID); err != nil {
			r.Log.Error("mark sent failed", "id", e.ID, "err", err)
			return
		}
	}
}
go
// Command outbox-relay is a second PROCESS built from the same module.
// Same code base (development view), different thread of control (process
// view), different container and replica count (physical view).
package main

import (
	"context"
	"log/slog"
	"os"
	"os/signal"
	"syscall"
	"time"

	"academy/kruchten-4plus1-views/internal/platform/outbox"
)

// emptySource stands in for "SELECT ... FROM outbox WHERE sent_at IS NULL".
type emptySource struct{}

func (emptySource) Pending(context.Context, int) ([]outbox.Event, error) { return nil, nil }
func (emptySource) MarkSent(context.Context, int64) error                { return nil }

// logPublisher stands in for a RabbitMQ or Kafka producer.
type logPublisher struct{ log *slog.Logger }

func (p logPublisher) Publish(_ context.Context, e outbox.Event) error {
	p.log.Info("published", "id", e.ID, "type", e.Type)
	return nil
}

func main() {
	log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	r := outbox.Relay{
		Source:    emptySource{},
		Publisher: logPublisher{log: log},
		Interval:  500 * time.Millisecond,
		Batch:     100,
		Log:       log,
	}
	log.Info("outbox-relay started")
	if err := r.Run(ctx); err != nil && ctx.Err() == nil {
		log.Error("relay stopped", "err", err)
		os.Exit(1)
	}
}

Example: development view in code ​

The dependency rules as a test (the table is the diagram), and a generator that draws the import graph from source:

go
// Package archtest turns the DEVELOPMENT view's dependency rules into a
// test. The table below IS the development view diagram, in code: if a
// pull request adds an arrow the diagram does not allow, CI fails.
package archtest

import (
	"go/parser"
	"go/token"
	"io/fs"
	"path/filepath"
	"strconv"
	"strings"
	"testing"
)

const module = "academy/kruchten-4plus1-views/"

// allowed lists, for each package, the module packages it may import.
var allowed = map[string][]string{
	"internal/ordering":        {},
	"internal/payments":        {},
	"internal/platform/outbox": {},
	"cmd/orders-api":           {"internal/ordering", "internal/payments"},
	"cmd/outbox-relay":         {"internal/platform/outbox"},
	"tools/viewgen":            {},
	"internal/archtest":        {},
}

func TestDevelopmentViewRules(t *testing.T) {
	root := filepath.Join("..", "..")
	err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
		if err != nil || d.IsDir() || !strings.HasSuffix(path, ".go") {
			return err
		}
		rel, _ := filepath.Rel(root, filepath.Dir(path))
		pkg := filepath.ToSlash(rel)
		f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly)
		if err != nil {
			return err
		}
		for _, imp := range f.Imports {
			p, _ := strconv.Unquote(imp.Path.Value)
			target, ok := strings.CutPrefix(p, module)
			if !ok || target == pkg {
				continue
			}
			if !contains(allowed[pkg], target) {
				t.Errorf("%s imports %s: not allowed by the development view", path, target)
			}
		}
		return nil
	})
	if err != nil {
		t.Fatal(err)
	}
}

func contains(list []string, s string) bool {
	for _, x := range list {
		if x == s {
			return true
		}
	}
	return false
}
go
// Command viewgen GENERATES the development view from the source tree:
// it parses every .go file, collects imports between packages of this
// module and prints a Mermaid flowchart. Run it in CI and commit the
// output next to the hand-drawn views, so this one can never go stale.
//
//	go run ./tools/viewgen . > docs/architecture/development-view.mmd
package main

import (
	"fmt"
	"go/parser"
	"go/token"
	"io/fs"
	"os"
	"path/filepath"
	"sort"
	"strconv"
	"strings"
)

func main() {
	root := "."
	if len(os.Args) > 1 {
		root = os.Args[1]
	}
	module, err := modulePath(filepath.Join(root, "go.mod"))
	if err != nil {
		fmt.Fprintln(os.Stderr, "viewgen:", err)
		os.Exit(1)
	}
	edges := map[string]bool{}
	err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
		if err != nil || d.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
			return err
		}
		f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly)
		if err != nil {
			return err
		}
		rel, _ := filepath.Rel(root, filepath.Dir(path))
		from := filepath.ToSlash(rel)
		for _, imp := range f.Imports {
			p, _ := strconv.Unquote(imp.Path.Value)
			if to, ok := strings.CutPrefix(p, module+"/"); ok {
				edges[fmt.Sprintf("  %s --> %s", id(from), id(to))] = true
			}
		}
		return nil
	})
	if err != nil {
		fmt.Fprintln(os.Stderr, "viewgen:", err)
		os.Exit(1)
	}
	lines := make([]string, 0, len(edges))
	for e := range edges {
		lines = append(lines, e)
	}
	sort.Strings(lines)
	fmt.Println("flowchart TD")
	fmt.Println(strings.Join(lines, "\n"))
}

func modulePath(gomod string) (string, error) {
	b, err := os.ReadFile(gomod)
	if err != nil {
		return "", err
	}
	for _, line := range strings.Split(string(b), "\n") {
		if m, ok := strings.CutPrefix(strings.TrimSpace(line), "module "); ok {
			return strings.TrimSpace(m), nil
		}
	}
	return "", fmt.Errorf("no module line in %s", gomod)
}

// id makes a Mermaid-safe node id that still reads like the path.
func id(pkg string) string {
	return strings.NewReplacer("/", "_", "-", "_").Replace(pkg) + "[" + pkg + "]"
}

Running it on this module prints:

text
flowchart TD
  cmd_orders_api[cmd/orders-api] --> internal_ordering[internal/ordering]
  cmd_orders_api[cmd/orders-api] --> internal_payments[internal/payments]
  cmd_outbox_relay[cmd/outbox-relay] --> internal_platform_outbox[internal/platform/outbox]

Example: scenarios as tests ​

go
package ordering_test

import (
	"context"
	"errors"
	"testing"
	"time"

	"academy/kruchten-4plus1-views/internal/ordering"
)

// The "+1" view as an executable artifact: each scenario from the
// architecture document is a test that walks the same steps.

type fakeInventory struct{ fail bool }

func (f fakeInventory) Reserve(context.Context, string, []ordering.Line) error {
	if f.fail {
		return ordering.ErrOutOfStock
	}
	return nil
}

var errDeclined = errors.New("declined")

type fakePayments struct {
	calls   int
	decline bool
}

func (f *fakePayments) Authorize(context.Context, string, int64) (string, error) {
	f.calls++
	if f.decline {
		return "", errDeclined
	}
	return "auth-1", nil
}

type memStore struct{ events []string }

func (m *memStore) SaveWithEvent(_ context.Context, _ ordering.Order, eventType string, _ []byte) error {
	m.events = append(m.events, eventType)
	return nil
}

func newService(inv ordering.Inventory, pay ordering.Payments, st ordering.Store) ordering.Service {
	return ordering.Service{
		Inventory: inv, Payments: pay, Store: st,
		Now:   func() time.Time { return time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC) },
		NewID: func() string { return "ord-1" },
	}
}

func TestScenarioS1PlaceOrderHappyPath(t *testing.T) {
	pay, st := &fakePayments{}, &memStore{}
	svc := newService(fakeInventory{}, pay, st)
	o, err := svc.PlaceOrder(context.Background(), "cus-7", []ordering.Line{{SKU: "BOOK-1", Quantity: 2, PriceCents: 1500}})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if o.Status != ordering.StatusConfirmed || o.TotalCents != 3000 {
		t.Fatalf("got status %s total %d", o.Status, o.TotalCents)
	}
	if len(st.events) != 1 || st.events[0] != "OrderPlaced" {
		t.Fatalf("outbox events = %v, want [OrderPlaced]", st.events)
	}
}

func TestScenarioS2OutOfStockNeverCharges(t *testing.T) {
	pay, st := &fakePayments{}, &memStore{}
	svc := newService(fakeInventory{fail: true}, pay, st)
	_, err := svc.PlaceOrder(context.Background(), "cus-7", []ordering.Line{{SKU: "BOOK-1", Quantity: 1, PriceCents: 1500}})
	if !errors.Is(err, ordering.ErrOutOfStock) {
		t.Fatalf("err = %v, want ErrOutOfStock", err)
	}
	if pay.calls != 0 || len(st.events) != 0 {
		t.Fatalf("payment calls %d, events %v: a rejected order must not charge or publish", pay.calls, st.events)
	}
}

func TestScenarioS3PaymentDeclinedWritesNothing(t *testing.T) {
	pay, st := &fakePayments{decline: true}, &memStore{}
	svc := newService(fakeInventory{}, pay, st)
	o, err := svc.PlaceOrder(context.Background(), "cus-7", []ordering.Line{{SKU: "BOOK-1", Quantity: 1, PriceCents: 1500}})
	if !errors.Is(err, errDeclined) {
		t.Fatalf("err = %v, want the payment error", err)
	}
	if o.Status != ordering.StatusRejected || len(st.events) != 0 {
		t.Fatalf("status %s, events %v: a declined order is rejected and publishes nothing", o.Status, st.events)
	}
}

The Go angle ​

ViewGo mechanismNote
LogicalPackage = module of the logical view; small interfaces declared by the consumerKeeps ports next to the use case
ProcessOne binary per cmd/ directory; goroutines are Kruchten's minor tasks; context.Context carries deadlinessignal.NotifyContext + Server.Shutdown for clean stops
Developmentinternal/ visibility enforced by the compiler; go list/go/parser to generate graphsThe Go modules layout guide recommends internal for packages you do not want others to depend on
PhysicalStatic binaries (CGO_ENABLED=0) in small images (distroless)Same image across environments; topology from manifests
Scenariosgo test with fakes for ports; httptest for the HTTP layerName tests after scenario IDs

Laravel ​

Laravel 13 on PHP 8.4. The code below was reviewed, not executed (no PHP on the build machine). Same views, same scenarios.

Example: logical view in code ​

php
<?php

declare(strict_types=1);

namespace App\Modules\Ordering\Domain;

use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * LOGICAL view: the Order aggregate. Status is a small state machine;
 * money is integer cents.
 *
 * @property string $id
 * @property string $customer_id
 * @property int $total_cents
 * @property OrderStatus $status
 */
#[Table('orders', keyType: 'string', incrementing: false)]
#[Fillable(['id', 'customer_id', 'total_cents', 'status'])]
final class Order extends Model
{
    protected function casts(): array
    {
        return ['status' => OrderStatus::class, 'total_cents' => 'integer'];
    }

    public function lines(): HasMany
    {
        return $this->hasMany(OrderLine::class, 'order_id');
    }

    public function confirm(): void
    {
        if ($this->status !== OrderStatus::Pending) {
            throw new \DomainException("Order {$this->id} is {$this->status->value}, cannot confirm");
        }
        $this->status = OrderStatus::Confirmed;
    }
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Ordering\Domain;

enum OrderStatus: string
{
    case Pending = 'pending';
    case Confirmed = 'confirmed';
    case Rejected = 'rejected';
    case Shipped = 'shipped';
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Ordering\Domain;

use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;

/**
 * @property string $order_id
 * @property string $sku
 * @property int $quantity
 * @property int $price_cents
 *
 * Composite primary key (order_id, sku) in the DDL, so no auto-increment id.
 */
#[Table('order_lines', incrementing: false, timestamps: false)]
#[Fillable(['order_id', 'sku', 'quantity', 'price_cents'])]
final class OrderLine extends Model
{
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Ordering\Application;

use App\Modules\Ordering\Domain\Order;
use App\Modules\Ordering\Domain\OrderStatus;
use App\Modules\Payments\Api\PaymentsApi;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

/**
 * Scenario S1 "place order" as an application service. The numbered
 * comments are the steps of the scenario diagram.
 */
final class PlaceOrder
{
    public function __construct(private readonly PaymentsApi $payments)
    {
    }

    /** @param list<array{sku: string, quantity: int, price_cents: int}> $lines */
    public function handle(string $customerId, array $lines): Order
    {
        if ($lines === []) {
            throw new \InvalidArgumentException('Order has no lines');
        }
        $orderId = (string) Str::ulid();
        $total = array_sum(array_map(fn (array $l): int => $l['quantity'] * $l['price_cents'], $lines));

        // Step 3: synchronous payment authorization (outside the DB transaction).
        $this->payments->authorize($orderId, $total);

        // Step 4: order, lines and the OrderPlaced event in ONE transaction (outbox).
        return DB::transaction(function () use ($orderId, $customerId, $lines, $total): Order {
            $order = Order::create([
                'id' => $orderId,
                'customer_id' => $customerId,
                'total_cents' => $total,
                'status' => OrderStatus::Pending,
            ]);
            $order->lines()->createMany($lines);
            $order->confirm();
            $order->save();

            DB::table('outbox')->insert([
                'type' => 'OrderPlaced',
                'payload' => json_encode(['order_id' => $orderId, 'total_cents' => $total]),
                'created_at' => now(),
            ]);

            return $order;
        });
    }
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Payments\Api;

/**
 * The ONLY door into the payments module (development view rule:
 * other modules may use Payments\Api, never Payments\Internal).
 */
interface PaymentsApi
{
    /** @throws PaymentDeclined */
    public function authorize(string $orderId, int $amountCents): string;
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Payments\Api;

final class PaymentDeclined extends \RuntimeException
{
}

Example: process view in code ​

The payment call is synchronous inside the web process, so it carries a timeout, a bounded retry and an idempotency key:

php
<?php

declare(strict_types=1);

namespace App\Modules\Payments\Internal;

use App\Modules\Payments\Api\PaymentDeclined;
use App\Modules\Payments\Api\PaymentsApi;
use Illuminate\Support\Facades\Http;

/**
 * Talks to the external payment provider. In the PROCESS view this is a
 * synchronous call inside the web request, so it gets a hard timeout.
 */
final class HttpPaymentsGateway implements PaymentsApi
{
    public function __construct(private readonly string $baseUrl, private readonly string $token)
    {
    }

    public function authorize(string $orderId, int $amountCents): string
    {
        $response = Http::baseUrl($this->baseUrl)
            ->withToken($this->token)
            ->timeout(2)
            ->retry(2, 100, throw: false)
            ->withHeaders(['Idempotency-Key' => "order-{$orderId}"])
            ->post('/authorizations', ['reference' => $orderId, 'amount' => $amountCents]);

        if ($response->status() === 402) {
            throw new PaymentDeclined("Payment for order {$orderId} declined");
        }
        $response->throw();

        return (string) $response->json('id');
    }
}

The relay runs in a queue worker process and is scheduled by the scheduler process:

php
<?php

declare(strict_types=1);

namespace App\Modules\Ordering\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

/**
 * PROCESS view: runs in a queue worker process (php artisan queue:work),
 * not in the web process. Scheduled every few seconds by the scheduler
 * process (php artisan schedule:work).
 */
final class RelayOutbox implements ShouldQueue
{
    use Queueable;

    public int $tries = 3;

    public function handle(): void
    {
        DB::transaction(function (): void {
            $rows = DB::table('outbox')
                ->whereNull('sent_at')
                ->orderBy('id')
                ->limit(100)
                ->lockForUpdate() // a second worker waits instead of double-publishing
                ->get();

            foreach ($rows as $row) {
                // At-least-once: consumers must be idempotent on order_id.
                Redis::xadd('events:orders', '*', ['type' => $row->type, 'payload' => $row->payload]);
                DB::table('outbox')->where('id', $row->id)->update(['sent_at' => now()]);
            }
        });
    }
}
php
<?php

use App\Modules\Ordering\Jobs\RelayOutbox;
use Illuminate\Support\Facades\Schedule;

// PROCESS view: the scheduler process enqueues the relay; a worker runs it.
Schedule::job(new RelayOutbox)->everyFiveSeconds();

Example: development view in code ​

Each module registers itself; the provider list is the module list of the development view:

php
<?php

// DEVELOPMENT view: each module registers itself through one provider.
return [
    App\Providers\AppServiceProvider::class,
    App\Modules\Ordering\OrderingServiceProvider::class,
    App\Modules\Payments\PaymentsServiceProvider::class,
];
php
<?php

declare(strict_types=1);

namespace App\Modules\Payments;

use App\Modules\Payments\Api\PaymentsApi;
use App\Modules\Payments\Internal\HttpPaymentsGateway;
use Illuminate\Support\ServiceProvider;

final class PaymentsServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(PaymentsApi::class, fn (): PaymentsApi => new HttpPaymentsGateway(
            (string) config('services.payments.url'),
            (string) config('services.payments.token'),
        ));
    }
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Ordering;

use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;

final class OrderingServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        $this->loadMigrationsFrom(__DIR__.'/database/migrations');
        Route::middleware('api')->prefix('api')->group(__DIR__.'/routes.php');
    }
}

The rules as Pest architecture tests:

php
<?php

// DEVELOPMENT view rules as Pest architecture tests
// (https://pestphp.com/docs/arch-testing). The diagram says "ordering
// uses payments only through Payments\Api"; this file makes it true.

arch('ordering uses payments only through its API')
    ->expect('App\Modules\Ordering')
    ->not->toUse('App\Modules\Payments\Internal');

arch('payments does not know ordering')
    ->expect('App\Modules\Payments')
    ->not->toUse('App\Modules\Ordering');

arch('payments internals stay inside payments')
    ->expect('App\Modules\Payments\Internal')
    ->toOnlyBeUsedIn('App\Modules\Payments');

arch('domain code does not touch HTTP')
    ->expect('App\Modules\Ordering\Domain')
    ->not->toUse(['Illuminate\Http', 'Illuminate\Support\Facades\Http']);

Example: physical view in code ​

One image (FrankenPHP's official image with install-php-extensions), several processes chosen by the command:

dockerfile
# PHYSICAL view as code: ONE image, three processes (web, worker, scheduler)
# chosen by the command in compose.yaml or the Kubernetes manifest.
FROM composer:2 AS vendor
WORKDIR /app
COPY composer.json composer.lock ./
RUN composer install --no-dev --no-scripts --prefer-dist --no-interaction

FROM dunglas/frankenphp:php8.4
RUN install-php-extensions pdo_pgsql redis pcntl opcache
WORKDIR /app
COPY . /app
COPY --from=vendor /app/vendor /app/vendor
RUN php artisan route:cache && php artisan view:cache
EXPOSE 8000
# config:cache needs the runtime environment (.env / env vars), so it runs at start.
CMD ["sh", "-c", "php artisan config:cache && exec php artisan octane:frankenphp --host=0.0.0.0 --port=8000"]

Example: scenarios as tests ​

php
<?php

// SCENARIO view as tests: S1 (happy path) and S3 (payment declined).

use App\Modules\Ordering\Application\PlaceOrder;
use App\Modules\Payments\Api\PaymentDeclined;
use App\Modules\Payments\Api\PaymentsApi;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;

uses(Tests\TestCase::class, RefreshDatabase::class);

it('S1: places an order and writes OrderPlaced to the outbox', function () {
    $this->app->instance(PaymentsApi::class, new class implements PaymentsApi {
        public function authorize(string $orderId, int $amountCents): string
        {
            return 'auth-1';
        }
    });

    $order = app(PlaceOrder::class)->handle('cus-7', [
        ['sku' => 'BOOK-1', 'quantity' => 2, 'price_cents' => 1500],
    ]);

    expect($order->total_cents)->toBe(3000)
        ->and($order->status->value)->toBe('confirmed')
        ->and(DB::table('outbox')->where('type', 'OrderPlaced')->count())->toBe(1);
});

it('S3: a declined payment leaves no order and no event', function () {
    $this->app->instance(PaymentsApi::class, new class implements PaymentsApi {
        public function authorize(string $orderId, int $amountCents): string
        {
            throw new PaymentDeclined('declined');
        }
    });

    expect(fn () => app(PlaceOrder::class)->handle('cus-7', [
        ['sku' => 'BOOK-1', 'quantity' => 1, 'price_cents' => 1500],
    ]))->toThrow(PaymentDeclined::class);

    expect(DB::table('orders')->count())->toBe(0)
        ->and(DB::table('outbox')->count())->toBe(0);
});

The Laravel angle ​

ViewLaravel mechanismNote
LogicalEloquent models with enum casts as the state machine; Actions/use-case classes; contracts in Api/Keep HTTP out of Domain/ (Pest rule)
ProcessWeb (PHP-FPM or Octane workers), queue:work, schedule:work; ShouldQueue jobs; Http::timeout()->retry()Octane keeps the app in memory: no request state in singletons
Developmentapp/Modules/<Name> + one service provider each, listed in bootstrap/providers.php; Pest arch(); Deptrac layersPHP does not enforce Internal/; the tests do
PhysicalOne image, three commands; /up health route (Laravel's default health check) for probesLaravel docs: the health route can be used by "an uptime monitor, load balancer, or orchestration system such as Kubernetes"
ScenariosPest feature tests with RefreshDatabase, container fakes via $this->app->instance()One test per scenario ID

Solving the classic problems ​

Three documentation anti-patterns come up again and again (one giant diagram, views that nobody reads, stale views), plus two design ones that the views expose.

One giant diagram ​

The anti-pattern Kruchten and Rozanski and Woods both open with: one sheet that mixes code, processes, servers and business concepts. Rozanski and Woods: "a monolithic AD is often incomplete, incorrect, or out-of-date".

SolutionHowAdvantageCost / limitation
Split by viewOne diagram per concern, each with a keyEach audience reads one small pictureNeed correspondence tables
C4 zoom levelsContext → container → component, never mixedDevelopers already know itProcess and physical detail need extra diagrams
Diagram review checklistTitle, type, scope, key, labelled arrows (C4 checklist)Cheap, catches most ambiguityDiscipline in reviews

Views that nobody reads ​

SolutionHowAdvantageCost / limitation
Start from stakeholdersV&B stakeholder/view table; drop cells marked "none"Every view has a readerA workshop per system
Answer questions, not templatesEach view opens with the 3–5 questions it answersReaders find the view by their questionQuestions must be maintained
Put views where people workMarkdown in the repo, linked from README and runbooksRead during code review and incidentsLess pretty than a wiki tool
Delete views with no ownerEach file names an owner teamSmaller, trusted setHarder to "document everything"

Stale views ​

SolutionHowAdvantageCost / limitation
Generate from codeviewgen, Deptrac graph, schema dumpsCannot driftGenerated pictures are less curated
Generate from infrastructure as codeDiagram from Compose/Kubernetes/TerraformPhysical view equals realityTooling per platform
Make rules executablearchtest, Pest arch()Drift fails the buildOnly for rules you can express
Diagrams as code, reviewed with codeMermaid/PlantUML/Structurizr in the PRReview catches mismatchHumans must still notice
Date and version each view"Production deployment, as of 2026-11"Readers know how much to trustManual

Missing process view ​

Teams draw boxes for services and skip what happens at runtime, then discover a chain of six synchronous calls in production.

SolutionHowAdvantageCost / limitation
A sequence per critical scenarioDraw S1 with timeouts on every arrowShows latency budgets and failure modesOne diagram per scenario
Connector tableSync/async, timeout, retry, idempotency per arrowReviewable listMust be kept with the code
Hollow prototypeKruchten's "dummy loads"; today: stubs + load testMeasures before buildingEffort up front

Logical view coupled to deployment ​

SolutionHowAdvantageCost / limitation
Ports owned by the use caseordering.Payments interface; adapters in cmd/Split a module into a service without touching the logicOne more indirection
Kruchten's collocation ruleMajor tasks "shall not make assumptions about their collocation"Same code runs in one process or manyMust handle remote failures everywhere
Data-driven mappingTopology in manifests and env vars, not in codeMany physical views, one code baseMore configuration

Choosing: which views, how much ​

SituationViews to writeDepthReason
Prototype, one developer, one processScenarios + a sketch of logicalWhiteboard photoKruchten: small systems can merge logical and development; scenarios always useful
Laravel or Go monolith, one teamLogical + development + 2–3 scenarios; one-line physicalModule map, dependency rulesCode organization is the main risk
Modular monolith, several teamsLogical + development (detailed) + process (web/workers) + scenariosRules as tests, CODEOWNERSTeam boundaries live in the development view
MicroservicesProcess + physical (detailed), logical per service, scenarios across servicesSequence per scenario, deployment per environmentFailures live between processes and nodes
Multi-region / distributed dataPhysical per region + replication paths, process with consistency notes, scenarios as failure drillsFailover runbooks linkedPartitions and lag decide correctness
Regulated or safety-criticalFull 42010-style description, all views, rationale per decisionFormal reviewsAuditors need traceability
Product line / white-labelDevelopment view first (shared layers vs product layer)Layer rulesKruchten: "the basis for establishing a line-of-product"
Onboarding documentationC4 context + container + development viewOverviewNew people need "where is what"

In architecture: from a single process to a distributed system ​

MonolithModular monolithMicroservicesMulti-regionLogicaldominantthe main viewdominantmodule = contextneededper serviceneededdata ownershipDevelopmentneededone repo, layersdominantmodule rulesneededrepo per team?neededpipelines, IaCProcesslightweb + queuelightweb + workersdominantcalls, retriesdominantreplication, lagPhysicallightone serverlightone server/HAdominantpods, meshdominantregions, failoverScenariosneededfew, as testsneededper moduledominantcross-servicedominantfailure drillsKruchten (1995): omit the physical view with one processor, the process view with one process; scenarios are always useful.

The grid is our judgement, anchored on Kruchten's tailoring rule: "Views that are useless can be omitted from the architecture description, such as the physical view, if there is only one processor, and the process view if there is only process or program. For very small system, it is even possible that the logical view and the development view are so similar that they do not require separate descriptions. The scenarios are useful in all circumstances."

Monolith: one process, one database ​

Simple example: a Laravel shop on one VM with PHP-FPM, MySQL and a Redis queue. Logical view: five modules on one page. Development view: folders and the rule "controllers call actions, actions call models". Process view: one line ("web + one queue worker + cron"). Physical view: one box. Scenarios: S1 and S3 as feature tests.

Production example: a layered monolith with 300k lines and 25 developers. The logical view and development view start to diverge (shared kernel, utilities), so the development view becomes the main tool for keeping the build and review load sane. The process view grows the moment you add Octane workers (shared memory across requests) or a second queue.

Modular monolith and multiple databases ​

Simple example: the Go module on this page: one binary for the API, one for the relay, modules under internal/ with rules in archtest. Logical module = development module = owner team.

Production example: a modular monolith where each module owns its schema (separate PostgreSQL schemas or databases). Now the logical view must show data ownership, the development view must forbid cross-module table access (a Pest rule that Ordering never uses Payments\Internal, and a database role per module), and the process view gains in-process events and an outbox per module. The correspondence table becomes the plan for any future split.

Microservices: process and physical views dominate ​

Simple example: Payments is extracted into its own service. The logical view barely changes (the PaymentsApi port stays); the development view gains a repository and a client package; the process view gains a network arrow with timeout, retry and idempotency key; the physical view gains pods, a service and a network policy.

Production example: forty services. The process view is now the critical one: synchronous chains, fan-out, sagas for multi-step workflows, outbox for events, idempotent consumers, API gateway and service mesh. The physical view is generated from manifests and shows zones, meshes and egress. The development view is mostly team boundaries and Conway's law. Scenarios cross services and become contract tests plus distributed traces.

text
     S1 after the split (microservices)                         View that changed
1    gateway -> orders (HTTP)                                   Process: new hop, auth at the edge
2    orders -> inventory (gRPC, 300 ms timeout)                 Process: remote call replaces in-process call
3    orders -> payments (HTTP, idempotency key, 2 retries)      Process + physical (egress)
4    orders commits order + outbox                              Same (logical unchanged)
5    relay -> Kafka topic orders.events (key = order_id)        Process: ordering per key
6    shipping consumes, saga step "create shipment"             Process: compensation if carrier rejects

Distributed data: replicas, caches and multi-region ​

The physical view now carries correctness, not just capacity. Draw replication paths and lag; mark which reads may go to a replica (see replication and failover), where caches sit and how they are invalidated, which data must stay in which region. The process view adds the consistency model per arrow ("read-your-writes after checkout: read from primary for 5 s"). Scenarios become failure drills: region evacuation, replica lag of 30 s, cache stampede.

ConcernView that must show itExample note
Replica lagPhysical + process"Order history reads from replica; checkout confirmation from primary"
Cache placementPhysical + process"Catalog cached in Redis, TTL 60 s, invalidated on price change event"
Data residencyPhysical"EU customers' orders only in eu-central-1 and eu-west-1"
FailoverPhysical + scenarios"Standby promotion under 60 s, drilled quarterly"
Consistency across servicesProcess + scenarios"Inventory eventually consistent; oversell handled by compensation"

Scaling path: 1×, 10×, 100× ​

LoadWhat changesWhich views change
1× (20 orders/s)One VM or one small cluster; scenarios as testsPhysical = one box; process = web + worker
10× (200 orders/s)Replicas, read replica, broker, relayProcess (new processes), physical (replicas, zones)
100× (2,000 orders/s)Extract hot modules into services, partition topics by order_id, shard or move to distributed SQLProcess and physical dominate; development splits repos; logical stays stable if ports were right

Lab: document a system in 4+1 and keep it honest ​

Prerequisites: Go 1.24+, Docker with Compose v2. Copy docs/snippets/architecture/kruchten-4plus1-views/ to a working directory.

  1. Run the scenarios and the development-view rules.
bash
cd go
go vet ./... && go test ./...
# ok  academy/kruchten-4plus1-views/internal/archtest
# ok  academy/kruchten-4plus1-views/internal/ordering
  1. Break the development view on purpose and watch the build fail.
bash
printf 'package ordering\n\nimport _ "academy/kruchten-4plus1-views/internal/payments"\n' > internal/ordering/zz_violation.go
go test ./internal/archtest/
# --- FAIL: TestDevelopmentViewRules
#     ../../internal/ordering/zz_violation.go imports internal/payments: not allowed by the development view
rm internal/ordering/zz_violation.go
  1. Generate the development view and paste it into any Mermaid renderer.
bash
go run ./tools/viewgen .
# flowchart TD
#   cmd_orders_api[cmd/orders-api] --> internal_ordering[internal/ordering]
#   ...
  1. Bring up the laptop physical view and walk scenario S1 by hand.
bash
cd ../deploy && docker compose up -d --build
curl -s -X POST localhost:8080/orders -d '{"customer_id":"cus-7","lines":[{"SKU":"BOOK-1","Quantity":2,"PriceCents":1500}]}'
# {"ID":"ord-1","CustomerID":"cus-7",...,"TotalCents":3000,"Status":"confirmed",...}
curl -s -o /dev/null -w '%{http_code}\n' localhost:8080/healthz   # 200
docker compose down -v
  1. Write your own system's 4+1 on one page each. For a system you know: list stakeholders and concerns; draw the four views (each with a key); write three scenarios as numbered scripts; fill the correspondence table; mark for each view its source of truth. Time-box to two hours.

  2. Measure staleness. For each existing diagram in your team's wiki, record the last edit date and compare with the last change to the code or manifests it describes. Anything older than the last structural change is a finding.

Documentation checklist ​

CheckPass when
Stakeholders and concerns listedEach view names who reads it and the questions it answers
Each diagram has a title, type, scope and keyC4's checklist: legend for shapes, colours, line styles, arrows
Every arrow is labelledIntent and, where applicable, protocol or technology
Logical viewFive to nine modules; each with one owner and its data
Process viewEvery inter-process arrow has sync/async, timeout, retry, idempotency
Development viewDependency rules written down and enforced by a test
Physical viewOne diagram per environment; replicas, zones, data stores, failover
ScenariosThree to six, chosen by risk; each linked to a test or drill
CorrespondenceA table maps modules → processes → nodes
RationaleEach significant choice links to an ADR
FreshnessEach view shows a date or is generated in CI
LocationViews live in the repository and are linked from the README

Common misconceptions ​

BeliefReality
"4+1 requires five diagrams for every system"Kruchten: views "that are useless can be omitted"; only scenarios are always kept
"The logical view is the generated class diagram"It shows architecturally significant abstractions only; a few dozen classes for a big system
"The process view is the business process"It is about threads of control, concurrency and distribution
"Logical and development views are the same thing"Close, but "the larger the project, the greater the distance between these views"
"There is one physical view"One per environment: laptop, staging, production, per customer site
"Scenarios are the complete use-case catalogue"A small set chosen by importance, frequency and technical risk
"4+1 is UML"The 1995 paper used Booch notation; UML mapping came later
"C4 replaced 4+1"C4 says it was "inspired by UML and the 4+1 model"; it covers static structure, with deployment and dynamic as supporting diagrams
"A C4 container is a Docker container""Not Docker!": an application or a data store
"ISO 42010 prescribes which views to draw"It prescribes how to choose and describe views (viewpoints from concerns); 4+1 is one framework
"Security needs its own view"Rozanski and Woods: qualities are perspectives applied across views
"Documentation is written after the architecture"Kruchten and V&B: views are produced while designing; scenarios drive the design
"Generated diagrams make hand-drawn views unnecessary"Generators show what is; the logical view and rationale still need a human

Cheat sheet ​

TopicRemember
LogicalFunctionality; key abstractions; end-users; class/state/E-R
ProcessPerformance, availability, integrity; tasks and processes; sync vs async; timeouts
DevelopmentOrganization, reuse, portability; modules, layers (4–6), visibility rules; teams
PhysicalAvailability, scalability; nodes; one diagram per environment
ScenariosRedundant "+1"; drive discovery, then validate; scripts; tests
TailoringDrop physical with one processor, process with one process; keep scenarios
CorrespondenceInside-out from logical, outside-in from physical; class → module → process → node
ISO 42010Stakeholder → concern → viewpoint → view → model (view component in 2022)
Views and BeyondModule, C&C, allocation; document views + beyond-views info
C4Context + container for everyone; component only if useful; deployment; dynamic sparingly
arc425 building block, 6 runtime, 7 deployment
Keep in syncDiagrams as code, generate from code/IaC, rules as tests, scenarios as tests
ScaleMonolith: logical + development; microservices: process + physical; distributed: physical + failure scenarios

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Name the four views and the "+1", and for each give one stakeholder and one concern from Kruchten's table. Important ​

Answer

Answer: Logical: end-user, functionality. Process: system designer and integrator, performance, availability, fault tolerance, integrity. Development: developer and manager, organization, reuse, portability, line-of-product. Physical: system designer, scalability, performance, availability. Scenarios: end-user and developer, understandability.

2 — Why does Kruchten call the scenarios view "redundant", and why keep it anyway? Good to know ​

Answer

Answer: Every element in a scenario already appears in one of the four views, so it adds no new elements. It is kept because it drives the discovery of architectural elements during design and validates the design afterwards, on paper and as the starting point for testing an architectural prototype.

3 — Your system is a single Laravel app on one server with no queue. Which views do you write? Important ​

Answer

Answer: By the tailoring rule: drop the process view (one process) and the physical view (one processor, or a one-line note). Logical and development may even merge for a very small system. Keep a few scenarios.

4 — A teammate says "the development view is just the logical view with folder names". What is the counter-argument? Important ​

Answer

Answer: They address different concerns: functionality versus organization, build, reuse, ownership and toolset constraints. Kruchten observed that the larger the project, the greater the distance between them; one logical category may be spread over several development layers.

5 — What are inside-out and outside-in in the mapping from logical to process view? Good to know ​

Answer

Answer: Inside-out starts from the logical classes and clusters active objects onto agent tasks until the number of processes is small. Outside-in starts from the physical architecture and external stimuli, defines client processes for stimuli and server processes for services, then allocates objects. Kruchten uses both together and iterates.

6 — In ISO 42010 terms, what is the difference between a viewpoint and a view? Important ​

Answer

Answer: A viewpoint is a reusable set of conventions (model kinds, notations, methods) framing certain concerns; a view applies a viewpoint to one specific system and consists of models (view components in the 2022 edition).

7 — Which V&B family does each 4+1 view mostly fall into? Good to know ​

Answer

Answer: Logical and development: module views (decomposition, uses, layered). Process: component-and-connector views. Physical: allocation (deployment); work assignment from the development view is also allocation.

8 — What is a C4 container, and which 4+1 view does a C4 container diagram mostly serve? Must-know ​

Answer

Answer: An application or a data store that must be running for the system to work (not a Docker container). The container diagram mostly serves the process view (runtime units and their communication) with some physical hints; deployment belongs in deployment diagrams.

9 — Name three techniques that keep the development view from going stale. Important ​

Answer

Answer: Enforce dependency rules as tests (Go archtest, Pest arch(), Deptrac); generate the import graph from source in CI and fail on diff; use Go's internal directories so the compiler rejects forbidden imports.

10 — Moving from a modular monolith to microservices, which views change most and which should barely change? Important ​

Answer

Answer: The process view (network calls, timeouts, retries, async messaging) and the physical view (pods, services, zones) change most. The logical view should barely change if modules were cut along the same boundaries and depended on ports.

11 — Where do quality attributes such as security go if not in a separate view? Important ​

Answer

Answer: Rozanski and Woods apply them as perspectives across all views; arc42 puts quality scenarios in section 10 and recurring solutions in section 8; in 4+1 they become scenarios plus notes in each affected view.

12 — What did Kruchten's Software Architecture Document contain besides the four views and scenarios? Good to know ​

Answer

Answer: Scope, references, an overview of the architecture, architectural goals and constraints, size and performance, quality, and appendices for acronyms, definitions and design principles. A separate Software Design Guidelines document held the important design decisions.

Glossary ​

TermMeaning
4+1 view modelKruchten's 1995 model: logical, process, development and physical views plus scenarios
ViewA representation of the whole system from one set of concerns
ViewpointConventions for constructing and using one kind of view (ISO 42010)
StakeholderA person, group or organization with an interest (concern) in the system
ConcernAny interest in the system: functionality, cost, safety, performance
Architecture description (AD)The work product that expresses an architecture (document, models, repository)
Model / model kindA diagram or text inside a view / the conventions for one type of model
View componentThe 2022 42010 name for what the 2011 edition called an architecture model
CorrespondenceA recorded relation between elements of different views or descriptions
Architecture frameworkConventions for descriptions in a domain; 4+1, TOGAF, RM-ODP are examples
Logical viewKey abstractions and their relationships; supports functional requirements
Process viewProcesses, tasks, and their communication; concurrency, distribution, availability
Development viewModules, subsystems, layers and their compile dependencies; organization and reuse
Physical viewNodes and networks and the mapping of processes onto them
ScenarioAn instance of a use case scripted across the views; drives and validates the design
ScriptThe sequence of (object, operation) interactions of a scenario
Class categoryA group of related classes in the logical view
SubsystemA unit of the development view, owned by one or a few developers
Major / minor taskArchitecturally visible thread of control / local thread for timeouts, buffering
Active / passive / protected objectInitiates operations / never initiates / never initiates but arbitrates calls
Inside-out / outside-inMapping strategies from logical classes outward / from external stimuli inward
Hollow process architectureProcesses with dummy loads to measure performance before the real code exists
Software Architecture Document (SAD)Kruchten's document organized around the 4+1 views
Architectural prototypeAn evolutionary prototype that grows into the system, used to test scenarios
Views and Beyond (V&B)SEI approach: document relevant views plus information that spans views
Module viewV&B family: code units and their relations
Component-and-connector (C&C) viewV&B family: runtime elements and their interactions
Allocation viewV&B family: mapping of software to non-software structures (hardware, files, teams)
Combined (hybrid) viewOne view that merges two with strong element correspondence
C4 modelSimon Brown's context, container, component, code diagrams plus deployment and dynamic
Container (C4)An application or data store that must run for the system to work
arc42A twelve-section documentation template; sections 5–7 hold building block, runtime and deployment views
PerspectiveRozanski and Woods: activities and tactics for a quality property across views
Diagrams as codeDiagram sources in text (Mermaid, PlantUML, Structurizr DSL) versioned with the code
Fitness functionAn automated check that an architectural property still holds (for example archtest)
DeptracA PHP static analysis tool that enforces layer dependency rules
Pest arch()Pest's architecture testing API (expect(...)->not->toUse(...))
Composition rootThe one place (cmd/.../main.go, service providers) where modules are wired to adapters

References ​

Built by Morteza Negahi