Chaos is death, order is life
Software dies of entropy, one feature at a time.It lives by order, one pruning at a time.
Updated
I have been working long enough into software to know that without a structure growing software end-up in as a big ball of mud where the entropy is high and the system becomes hard to understand.
The entropy in system is created one new feature at a time, it is the death by a thousand cut
As an evolving program is continually changed, its complexity, reflecting deteriorating structure, increases unless work is done to maintain or reduce it.
The solution against it is energy and structure which create order
The energy is the constant effort a software engineer do to maintain the system he growth
The structure is the mental model he uses to handle the entropy of the software
This article describe the concepts around the structure i believe helps software system to handle the entropy
Layered architecture
Source code dependencies can only point inwards.
Let's imagine you are at the new house friend, everything is fine, you are enjoying a good drink. She is going to prepare the table for everyone and ask you to put some trash into the bin. You go open the cupboard under the sink - nothing, there are plates here and some tea towels. She then say really casually "oh the bin is in the garage". You should be confused and rightly if you ask me. The garage responsability is not to handle the bin which you will use really regularly while you are cooking. The expected place is in the kitchen.
In software system the place where you put code should be layer, a layer as responsibilities it's a mental model that help you structure your code by having one point of entry where you handle one concept
The different layers are :
| Layer | Part | Side |
|---|---|---|
| Domain | Core | - |
| Ports | Core | - |
| Use-cases | Core | - |
| Storage | Adapter | Driven |
| Connector | Adapter | Driven |
| System | Adapter | Driven |
| Controller | Adapter | Driving |
| Presenter | Adapter | Driving |
We divide them in two category :
- CoreWhich is the the heart of the system, where the business logic belongs
- AdapterWhich is the implementation of the port interface they invert the dependency between the core and the adapter so that the core doesn't depend on the implementation and technologic and can stay dependency free
Important : One key aspect of this architecture is to isolate the business logic so we don't have to change it later in case of a switch or technology. We don't want to pollute the business logic with implementation details, tech choices, etc..
Core:Domain
- ResponsabilityHandling business logic we will store inside Domain rules, Invariants, Domain errors, Entity schema.
- CouplingIt decouple the business logic from what is related to it (such has technology choices)
- Reason to changeThe business changes its mind (such as a new rules get added to the system, or an old one is updated)
Core:Use-cases
- ResponsabilityFulfil one user intention. Loads through ports, applies domain rules, saves through ports, in that order. The only layer that mixes I/O and rules
- CouplingImports Domain and the Ports it declares. Receives adapters as arguments, never imports one. Knows no protocol, no database, no host
- Reason to changeThe user wants to do something new, or do an existing thing in a different order
Core:Ports
- ResponsabilityDeclare, in domain vocabulary, what the core needs from the outside world: what it must fetch, store, call or know. Types only, no behaviour
- CouplingImports Domain and nothing else. Used by Use cases, implemented by Adapters. Never names a technology, a library type or a wire format
- Reason to changeA use case needs something new from the outside world. Never because an adapter changed how it provides it
Adapters:Storage(driven)
- ResponsabilityLoad and save one aggregate, whole and atomically, behind its port. Translates between domain shape and storage shape in both directions.
- CouplingImplements one Storage port. Imports Domain, the port, and one storage library.
- Reason to changeThe port grew a method, the storage technology changed, or the aggregate's shape changed and the mapping must follow
Adapters:Connector(driven)
- ResponsabilityTalk to one external system we do not control. Handles its protocol, auth, paging and retries, and maps its shape into the port's domain vocabulary
- CouplingImplements one Connector port. Imports Domain, the port, and the vendor's SDK or HTTP client. Never a use case, another adapter, or an app
- Reason to changeThe vendor changed its API, its auth, or its limits we swapped vendors or a use case needs one more thing from it
Adapters:System(driven)
- ResponsabilityProvide one fact about the world or the process: current time, fresh identifiers, configuration, environment, randomness. One question, one answer
- CouplingImplement the SystemPort
- Reason to changeSwap in technology such has the date technology. This Adapter almost never change it handle System technology at one place which don't change often in order to keep the core free
Adapters:Controler(driving)
- ResponsabilityReceive a request in one protocol, authenticate it, parse and validate the input against a Contract, call one use case, hand the result to a Presenter
- CouplingImports Use cases, Contracts, and one protocol SDK. Imports no Domain internals, no Storage, no Connector. The only piece that knows both the protocol and the use case
- Reason to change The protocol or host changed, or a use case is newly exposed or exposed differently.
Adapters:Presenter(driving)
- ResponsabilityShape one use case result for one audience. Chooses which fields to show, how to label and format them, and what to say about an error
- CouplingImports Contracts and nothing else from the core. Called by the Controller
- Reason to change The audience wants to see something differently: a new field, a different wording, a changed layout
Composition Root
Once we have theses layers in place the application need to compose them (adapter, port, etc..), in order to that we use a container file that is responsible for knowing which adapter goes to which port
It lives in the app because it is the only place that knows which database, which vendor, which clock. It imports every adapter and every entity's controller, and nothing imports it.
Domain Modeling
Schema First
The domain is modelled as schemas, not as types. A schema is a runtime value, so one declaration gives four things that would otherwise be written by hand and drift apart: the static type, inferred from it; the validator, run at every boundary where data enters;
Schema:Entity
A shape with an identity. It stays the same thing as its fields change, so it has an id, a storage, and the invariants that make it valid. Built only by the domain, it is the canonical form of the data and never leaves the core.
Schema:ValueObject
A shape with no identity. Equal to any other value with the same fields, never modified but only replaced, validated once at construction and valid everywhere after. Branded so that two values of the same primitive type cannot be confused.
Schema:Contract
A shape that leaves the core. Derived from an entity by pick, omit and extend, with no rules of its own, it is what controllers, presenters and views depend on instead of the entity, so that the entity can change without breaking them. Lives in contracts, next to the function that builds it from the entity
Errors
There are three kinds of error :
Error:Domain
An invariant or a rule was not satisfied. They are defined in Core:Domain, next to the rule that issues them, because the refusal is part of the rule.
Error:NotFound
Something expected is absent. It returns the absence as a value and the use case decides whether that absence is an error. So NotFound is defined in the application layer, produced only by use cases, and shown to the user like a domain error.
Error:System
The system failed for reasons unrelated to the business: network down, database unreachable, a provider throttling us, a configuration value missing. These are born in an adapter, at the first line that can throw, and wrapped into a value with the original cause attached. Only the operator can fix them, so they are logged with their cause, retried when transient, and shown to the user as a plain failure with nothing from the inside.
Two concepts carry all three.
Errors as values
An error is data with a tag, returned rather than thrown. The only place an exception is allowed is the controller, when the protocol demands one.
Result monad
Every function that can fail returns Result<T, E>. The signature lists what can go wrong, the caller cannot ignore it, and a switch on the tag with no default stops compiling the day a new error is added. Ports declare the error union of each method, so a use case sees a closed set and chooses what to do with each case: retry, switch source, skip, or pass it up.
Each error is translated exactly once, at a boundary. The adapter turns an exception into a value. The controller turns the value into the protocol's vocabulary: an HTTP status, an MCP isError, an exit code. Nothing in between touches it, which is why a tag created in a repository arrives at the controller unchanged.
Because errors are typed data rather than stack traces, an external system calling ours receives a precise error it can act on.
Vertical Slicing
Minimize coupling between slices, and maximize coupling in a slice.
Code is grouped by capability first and by layer second. A slice is one thing the user does and the aggregate it touches, and it is one folder that holds every layer it needs:
entity/
domain/
application/
contracts/
storage/
connectors/Typesafe
Well-type programs cannot “go wrong”.
The goal is to learn about a mistake at compile time rather than in run time. How much a language lets you do that depends on whether its type system is sound.
A sound type system guarantees that a value of type T is really a T at runtime. Rust is sound outside unsafe: the program may still panic, but it will never hold a string where it believes there is an integer.
An unsound type system accepts programs where a value can carry a type it does not have. TypeScript is unsound by design: any, as, JSON.parse
Tooling
Monorepo
The whole system lives in one repository. A change to runs touches its domain, its storage, its contracts and the app that exposes it in a single commit: no package versions to bump between them, no release order to get right. You can also check architecture rules as everything is in the repo.
package/
entity/
domain/
application/
contracts/
storage/
connectors/
controllers/
presenters/
config/
tsconfig.json
eslint.json
apps/
web-app/
container.ts
server/
container.ts
server-mcp/
container.tsEach entity folder is one slice and one workspace package, complete from domain to controller. An app is a composition root and nothing else: it builds the adapters, then hands a server and a deps bag to each entity's controller.
Linting
Linting. A linter reads the code and refuses patterns we have agreed are mistakes. It catches the small things that are tedious to review by hand. A linter runs in seconds, on save and in CI.
Each coupling row of the cards becomes one import rule: the domain may not import a database library, the application may not import an adapter, a controller may only import its own slice. A no-cycle rule keeps slices out of each other.
Formatting
One formatter, no options, run on save and in CI
DevTools
Dev tools make life easier and application more understandable i like to use :
- Google Chrome DevTools
- Drizzle UI for Databases
- Scalar UI for APIs
Testing
Program testing can be used to show the presence of bugs, but never to show their absence!
Unit
I like to unit test function to test edge cases and make sure they are Total functions
It's also a good documentation when you discover a case that could go wrong you can create an associated unit test to bit.
Knowing every possible edge cases in advance could be hard but it's simple to test from a pure function perspective
Integration
Integration test are from the perspective of a package/slice. They are here to ensure a part of the system behave has expected. The classical case is calling the controller knowing the inputs and expecting outputs. The test shouldn't know about how the module/package works and internals or dependencies and which layer get traversed
End-to-end (E2E)
The end-to-end test are from the user interface point of view
They are slow and can break often. But they provide a good check if the system is working correctly
I used them to check happy path only - or really important edge case that that happened in production and i want a Tripwire on
Documentation
ADR
This document describes the structure; a project's ADRs record where and why it deviated. Keep them in docs/adr/, numbered, one decision per file, each with a status, a date, the decision in a few lines, and the evidence that led to it. The first three are always the same: the architecture and its enforcement, the storage choice, and the error and validation stack. Record the spike that justified each, with its date, so a later reader can tell a tested choice from a habit. An ADR is amended, never rewritten: when a decision changes, a new ADR supersedes the old one and both say so.
Infrastructure
One page and one diagram: which processes exist, where each runs, what it talks to, what configuration and secrets it needs, and how it gets deployed. It is the only place the real constraints behind the code are visible, and the first thing an on-call reader opens. It changes rarely, so it is written by hand and reviewed with every deployment change.
Database (EntityRelationship Diagram)
An entity relationship diagram generated from the schema definitions, on every build. Never drawn by hand: a drawn diagram is a snapshot, and the schema moves.
APIs
A reference of every endpoint, its inputs, outputs and errors, with examples. Schema first makes this free: the contracts produce an OpenAPI document and a renderer such as Scalar serves it. Nobody maintains it, so it is never out of date.
Further reading
The books and articles behind this article, in the order they appear.
Brian Foote and Joseph Yoder, 1997
Where the name comes from: how systems lose their shape, and why.
Alexis King, 2019
Check data once, at the boundary, and keep the proof in the type.




