Domain-Driven Design: what it is, how it works, and how it helps you program with AI
Learn to translate business rules into software with Domain-Driven Design. Explore its fundamental concepts through TypeScript examples and discover how to use them to guide and review AI-generated code, beyond whether it compiles or responds correctly to a request.
The indicator keeps the furthest percentage explored; marking the article complete is your choice.
An academy opens twenty places for a workshop. You ask an artificial intelligence tool to implement enrollment: it generates an endpoint, validates JSON, and saves records. The demo works. Yet when one place remains, two students enroll almost simultaneously and both receive confirmation.
The code may be well written and still fail the academy's needs. Validating that studentId is a string does not answer who controls capacity or what should happen when two requests compete for it.
Domain-Driven Design, or DDD, helps turn those questions into an explicit model: concepts, rules, and boundaries guiding implementation. To understand it, we will start with the business problem and finish with a verifiable TypeScript example.
What DDD is and what problem it solves
DDD is a development approach centering design on Domain knowledge and collaboration with those who know it. The Domain is the area of activity the software helps address: education, commerce, or reservation management, for example. A Domain Model is a representation selecting concepts and rules relevant to that purpose; it does not try to copy all reality. This is the orientation Eric Evans presents in his DDD reference.
In an academy, speaking with coordination may reveal that “course” means content, while “edition” identifies a group with dates and places. If you store capacity directly in Course, you may prevent offering two simultaneous editions with different capacities.
The modeling decision changes the result: CourseEdition controls enrollment for a particular edition. Now you can open one edition with twenty places and another with thirty without mixing participants.
DDD seeks to reduce the gap between what people want to express and what the program allows. It does not guarantee absence of errors. It makes certain decisions visible, discussable, and verifiable.
Distinguish two scales. Strategic Design organizes responsibilities, models, and relationships between areas. Tactical Design expresses rules within a model through tools such as Entities and Aggregates. Starting with classes without clarifying boundaries leaves part of the problem unresolved.
First understand words and responsibilities
Domain and Subdomains: where investment is worthwhile
A Subdomain is a part of the overall problem. In our academy, we could distinguish edition planning, learning, billing, and communication.
Not all require equal effort. If the academy competes on how it adapts exercises to each student, that capability may be its differentiating core. Sending emails could use an existing service. Classification depends on the business: for an email company, delivering messages would be central.
As a practical criterion, identify which behavior differentiates the product, which custom capabilities support it, and which needs are common to many organizations. This avoids spending weeks on a sophisticated model for a secondary function while important rules remain scattered.
Ubiquitous Language: names also useful in conversation
The Ubiquitous Language is the shared vocabulary connecting conversations, documentation, and code within a model. Evans includes it as a fundamental DDD element in his reference.
For the workshop, we agree:
An edition is a particular offering of a course.
Enrolling consumes a place immediately.
A person cannot enroll twice in the same edition.
This example has no temporary reservations or waiting list.
The last clarification matters. If coordination calls a place held for fifteen minutes a “reservation,” implementing enroll() with permanent occupancy would be incorrect. Before asking AI for code, resolve that difference.
Vocabulary is reviewed when new cases arise. If the team discovers reserving and enrolling are different actions, the model must reflect it; a glossary nobody checks against behavior adds little.
Bounded Contexts: one word may have different meanings
A Bounded Context marks where a model and its language are valid. It does not require deploying a microservice per Bounded Context: it is primarily a boundary of meaning and responsibility. Martin Fowler explains separating related models through Bounded Contexts.
In learning, a “student” may have progress and submissions. In billing, a “customer” may have tax details and payment obligations. Although both refer to the same person, you do not need a universal class with all those attributes.
The Subdomain describes part of the problem; the Bounded Context delimits a solution model. They are related concepts but not equivalent by definition. You can revisit their correspondence as your understanding improves.
Entities, Value Objects, and Aggregates
An Entity is distinguished by its identity over time. An edition retains its identifier even if its schedule changes. Two editions with identical dates are not necessarily the same.
A Value Object represents something defined by its attributes. Two ten-euro amounts are equivalent if amount and currency match. Usually, you make it immutable to preserve that meaning.
An Aggregate groups elements that must maintain consistent rules; its Aggregate Root controls external modifications. An Invariant is a condition that must hold after every valid operation. These distinctions form part of Evans's Tactical Design patterns.
In the workshop, we choose CourseEdition as Aggregate Root. Its Invariant will be “the number enrolled never exceeds capacity.” Exposing a public array so anyone can add participants would bypass that rule. Offering enroll(studentId) concentrates the decision.
An Aggregate can contain just one Entity. Nor should you include all related data: we will not load each enrollee's academic history or invoices. The boundary is chosen by rules needing joint consistency, not relationships you can draw between tables.
Main example: enroll without exceeding capacity
From an isolated check to a protected rule
This problematic solution seems reasonable. It is partial pseudocode; database represents a fictional persistence API:
if (await database.countEnrollments(editionId) < capacity) {
await database.insertEnrollment(editionId, studentId);
}
Two requests can count nineteen enrollees before either saves. Each check is individually correct; the combination admits twenty-one.
We need two complementary decisions: the model rejects invalid enrollments, and persistence prevents saving changes based on stale state. A class alone does not coordinate concurrent processes.
Example contract and simplifications
We will represent this request:
POST /editions/typescript-octubre/enrollments
Content-Type: application/json
{}
Identity comes from an already authenticated session, not JSON. The successful response will be 201 with the edition and student. Duplicate enrollment, a full edition, or a version conflict return 409; a nonexistent edition returns 404.
The next block is a self-contained program. Save it as inscripciones.ts. It uses only modules included in Node.js. You can run it with node inscripciones.ts on Node.js 24.21.0, the version used to check it. Node can execute this syntax by removing types, but does not type-check during that execution.
To focus on DDD, the postEnrollment adapter receives an already decoded body and a trusted session; it does not open an HTTP server. The Repository saves in-memory copies and loses data when execution ends. It simulates concurrency control in one process, without offering durable persistence or coordination between servers.
First, the adapter validates the body's shape. It rejects unexpected fields: the client cannot choose another identity. In a real server, you would also check authentication, permissions, route parameters, and request limits.
Then enrollStudent executes the Use Case, the operation offered by the application. It retrieves the edition and coordinates saving. It does not calculate remaining places itself: it delegates that rule to CourseEdition.
The Entity encapsulates state and permits modification through enroll. Changing permitted capacity or adding enrollment closure would have a specific place in the model. Transport validation and Domain rules fulfill different responsibilities.
The Repository offers retrieval and saving of Aggregates without the Use Case knowing a particular database. Here, its contract includes an important condition: save only if the version read matches.
In the concurrent test, both operations may work with version zero. The first saves version one; the second finds a different version and fails. The observable result is one confirmation and one conflict, with only one place occupied.
In a database, comparison and writing must also be atomic: for example, through a version-conditioned update, checking affected rows and saving every Aggregate change in a local transaction. Separating those checks would reintroduce the race. If you decide to retry a conflict, load current state and execute the rules again.
The assertions protect business behavior as well as the response: they reject duplicates, prevent capacity being exceeded, and verify finally saved state. The program was run with Node.js 24.21.0 and completed those assertions; compilation with TypeScript's type checker was not performed. This demonstration does not replace a concurrent test against the actual persistence engine.
Our choice has a cost: loading every enrollee may be reasonable for a small workshop and unsuitable for a massive event. In that case, how place allocation is represented and its consistency protected must be reconsidered. DDD requires reviewing the model, not preserving this implementation at every scale.
Second example: money in commerce
Now the decision changes. A store receives prices from an integration. The problematic solution represents everything as number and ends up adding ten euros and ten dollars as if they were twenty units of one currency.
Here we need a Value Object making units explicit. This instructional snippet is independent of the preceding program and deliberately limits the example to euros and dollars with two decimal places:
Representing minor units avoids certain problems with binary decimal operations, but does not solve conversion, taxes, or rounding. Those rules need additional decisions. Furthermore, TypeScript types do not validate data received through HTTP: the adapter must check currency at runtime.
This example teaches recognizing when data deserve their own meaning. We do not need an identifier for every amount; we need value equality and operations compatible with its units.
Third example: translate a logistics integration
A store receives the carrier state DELIVERED. Initially, someone transforms it directly into order.completed = true. The problem appears when the business distinguishes physical delivery, customer acceptance, and commercial closure.
The decision is to introduce an Anticorruption Layer, or ACL: an adapter translating the external model into the language the consumer needs. Evans describes this pattern to protect the internal model from other models.
In our scenario, the ACL validates the carrier response and translates DELIVERED into “physical delivery confirmed.” The Use Case records that fact; a separate business rule decides whether the order should close. The result changes: receiving the package no longer automatically skips pending acceptance.
The consumer contract could be this partial snippet, without an HTTP implementation:
The consumer defines what it needs to know. Its adapter implements the contract, validates external JSON, and distinguishes “not delivered” from “could not query.” A network failure must not silently become a business fact.
This also clarifies a boundary: querying through HTTP and saving in your database does not constitute a shared transaction. If you must coordinate actions between systems, agree on what happens upon partial failures, repetitions, and data changing between queries. The ACL translates; it does not eliminate those problems.
Example code based on a real case
In a real comment-publication case, the example code distinguishes two responsibilities: validating content and checking conditions necessary to publish it. A Value Object can normalize text and reject an empty comment; the Use Case coordinates checks and saving.
If a check depends on another Bounded Context, an ACL can query its HTTP API and validate the response against a consumer-defined contract. Each Bounded Context thus retains its model without importing the other's implementations. This is an integration decision for the example, not a universal DDD requirement. The HTTP query and local save do not constitute a shared transaction.
This article's examples are instructional: they simplify cases to explain design decisions.
What changes when programming with artificial intelligence
The relationship with AI is a practical application of these ideas: an explicit model gives you criteria for requesting and reviewing changes. It does not imply DDD makes a tool automatically understand your business.
“Implement enrollment” leaves questions AI may resolve through assumptions: allowing duplicates, turning reservations into enrollments, or sharing an Entity between Bounded Contexts. A more precise contract reduces ambiguity:
Describe vocabulary and rules with examples and counterexamples.
Identify which Bounded Context decides each matter and what data it needs from others.
Request a bounded implementation and observable checks.
Review behavior with someone who knows the Domain.
A test generated by the same tool can confirm an incorrect assumption. If both implementation and test consider a second enrollment valid, they will agree while still misrepresenting the business.
These prompts serve as a starting point. Complete the context with real information and share only authorized material.
To analyze before implementing
We work in an academy. Course is content; edition is an offering with its own capacity. Enrolling occupies a place and does not permit duplicates. There are no temporary reservations. Analyze “last place,” “two simultaneous requests,” and “same person twice.” Return rules, ambiguous terms, and a proposed Aggregate boundary, without writing code. Separate facts from assumptions. A coordination person will specifically validate the meaning of enrollment and exceptions.
To implement with clear boundaries
Implement the InscribirEstudiante Use Case in TypeScript for Node.js. Identity comes from a trusted session; the body does not accept studentId. CourseEdition protects capacity and duplicates. The Repository must detect writes based on an old version. Do not add frameworks, dependencies, or imports between Bounded Contexts. Deliver code and tests for duplicates, a full edition, and two requests for one place. Explain which guarantee depends on the database. A person will review real-adapter atomicity and authorization rules.
To review without confusing compilation and correctness
Review this change against the attached rules and contracts. Look for ways to modify the Aggregate without its methods, confusion between reservation and enrollment, unvalidated external contracts, and shared-transaction assumptions over HTTP. Do not change files. Return findings with evidence and a reproducible scenario; mark doubts as doubts. A person will check scenarios with the business and execute tests in the corresponding environment.
When a simpler solution is enough
An internal classroom catalog may only need to create, read, update, and delete records: operations usually called CRUD. If its rules are limited to a required name and unique code, a small service with validation and a database uniqueness constraint may suffice.
You can retain clear names and separate responsibilities without creating an Aggregate, Factory, and several services for every table. DDD does not require microservices, a particular folder, CQRS, or storing every change as an event. Fowler's overview emphasizes Strategic Design's importance and applicability beyond a single programming approach.
The real cost includes conversations, concept review, boundary maintenance, and team learning. It is worthwhile when it prevents important errors or facilitates frequent changes to complex rules. If abstractions add steps without representing decisions, simplify them.
Three exercises for applying judgment
1. A place reserved for fifteen minutes
The academy wants to hold a place while payment completes. Decide what you would change before programming.
Reasoned solution: distinguish temporary reservation from confirmed enrollment. Clarify when it expires, whether it consumes capacity, and what happens if payment arrives late. If both occupy places, the Invariant must consider active reservations and enrollments. Injecting a controllable clock allows testing expiration without waiting fifteen minutes. A repeated payment confirmation should not consume another place either. Adding only a paid field leaves those decisions pending.
2. A new address after shipment
A customer changes their profile address after an order is dispatched. Should the shipment address change too?
Reasoned solution: if logistics needs to preserve where it was dispatched, save a copy of the value agreed when preparing shipment. The profile address can change without rewriting that fact. A later correction requires an explicit operation with its own rules, not an automatic update of every reference.
3. The carrier does not respond
The delivery query times out. AI proposes returning physicallyDelivered: false. Would you accept it?
Reasoned solution: not for the described contract. “Unknown because the query failed” is not equivalent to “not delivered.” Retain the distinction through an error or explicit unavailable result, and agree whether the Use Case should wait, retry, or leave a pending review. Check that an integration failure does not accidentally close or reverse an order.
How to recognize where to apply DDD
DDD is particularly useful when the same words cause disagreements, several operations must protect a common rule, or an integration begins imposing its vocabulary on the rest of the system. Also when every change requires searching for duplicated conditions in controllers and services.
Start with a concrete operation: write its rules with someone who knows the business, identify terms, and check cases that could break it. Introduce Entities, Value Objects, and Aggregates where they make necessary decisions explicit. Then check the model against persistence and integrations: a rule expressed in code still needs mechanisms sustaining it at runtime.
When working with AI, that model guides implementation and discussion of results. Code compiling is a technical check; allowing exactly the agreed operations requires understanding the Domain and supplying behavioral evidence.
Further references
In addition to linked sources, the introduction to a local copy of Domain Driven Design Quickly, published by InfoQ, written mainly by Abel Avram with Floyd Marinescu as editor, was consulted. It provides an entry point to Evans's ideas. This article's scenarios and implementation decisions are instructional and must be adapted to each project's rules.
Integrate the collection by building an order API with TypeScript, Express, Zod, and SQLite. Includes project files, domain rules, events, version control, Vitest tests, and commands to run and verify it locally.
Learn to guide AI agents with business rules, context boundaries, and verifiable criteria. A TypeScript case shows how to prepare instructions, protect Order, design tests, and review changes without delegating architectural judgment.
Compare a modular monolith with separating Sales, Payments, and Inventory. Design contracts in TypeScript and Express and understand partial failures, eventual consistency, idempotency, Outbox, and Sagas without introducing complex infrastructure.