DDD in a Zombie Apocalypse. Part 2
2026-02-28 · [ leer en español ]
In the first installment of this series we laid the groundwork for bringing DDD into our camp. We set up a ubiquitous language to close the gap between what the group leader says and what the developer writes. We split the system into bounded contexts so Medical, Logistics and Command stop stepping on each other's toes. We learned to tell entities from value objects, and finally we saw how aggregates act as the guard at the shelter door: nobody changes anything without going through them. I'd read that one first, because we'll reuse several of the classes we defined there.
All of that was the inside. The core. The logic that keeps order within the walls.
But a shelter needs more than that to survive. It needs operations that involve several people at once, ways to communicate without creating direct dependencies between contexts, and a way to persist state without the domain knowing whether you're on PostgreSQL or a pile of beat-up notebooks. Someone has to coordinate all of it without becoming the one person who knows everything and controls everything. You know how zombie apocalypses go: whoever knows where the generator keys are, has access to the critical supplies and understands how the ventilation works is, without fail, the first one to turn at the worst possible moment. And when that happens, the whole system goes down because nobody else knows how it works.
That's what this second part is about: domain services, repositories, the application layer and domain events.

1. Domain Services
Sometimes you run into business logic that doesn't fit naturally in any entity or value object. It isn't the job of a single aggregate. It touches concepts from several of them, or it's just a domain operation that doesn't "belong" to anyone in particular.
When do you need a domain service?
Ask yourself: is this logic the responsibility of a Survivor? Of a Shelter? If the answer is "not really, it's something that happens between them" or "it's a calculation that pulls information from several places", you probably need a domain service.
A domain service holds pure business logic. It doesn't do I/O (no databases, no external services), it keeps no internal state, and it works on the parameters it receives to return a result. It shouldn't turn into a junk drawer of assorted utilities either: it exists to express domain rules under a clear name.
A real example: calculating infection risk
Picture this. Luis, one of our scouts, just got back with a torn suit and a scared look on his face. He was surrounded by infected, but he says he kept his distance... more or less. The shelter's doctor needs to work out his real chance of infection based on how close he got to the zombies and how long he was exposed. This logic:
- Isn't Luis's responsibility (the
Survivor). He doesn't decide whether he gets infected, he just suffers the consequences. - Isn't the
Shelter's responsibility either. It's a calculation that can happen outside too. - Is a domain rule that depends on the physics of the zombie apocalypse.
Given all that, this is where a domain service comes in:
export class InfectionSpreadService {
/**
* Calculates the chance of infection from distance and exposure time
*
* @param distanceMeters - Distance to the infected person in meters
* @param exposureMinutes - Minutes of exposure
* @returns Probability between 0 (no risk) and 1 (certain infection)
*/
public chanceOfInfection(
distanceMeters: number,
exposureMinutes: number
): number {
// Domain rule: the closer you are, the higher the risk
// At 0 meters = maximum risk (1.0)
// At 20+ meters = no risk (0.0)
const base = Math.max(0, 1 - distanceMeters / 20);
// Domain rule: exposure time increases the risk
// Under 60 minutes = risk proportional to time
// 60+ minutes = maximum factor (1.0)
const timeFactor = Math.min(1, exposureMinutes / 60);
// Infection formula: combine distance and time
// Starts at 50% of the base and grows to 100% with time
return Math.min(1, base * (0.5 + 0.5 * timeFactor));
}
}
const infectionSpreadService = new InfectionSpreadService();
// Using the service
const risk1 = infectionSpreadService.chanceOfInfection(5, 30);
console.log(risk1);
// ~0.59 (59% chance: Luis goes into isolation)
const risk2 = infectionSpreadService.chanceOfInfection(15, 90);
console.log(risk2);
// ~0.25 (25% chance: farther away, but he was out there a long time)
const risk3 = infectionSpreadService.chanceOfInfection(1, 120);
console.log(risk3);
// ~0.95 (95% chance: Luis is pretty much gone)
Who uses this service?
This service is pure domain logic, so it can be used by:
- The
Shelteraggregate, when it decides whether to trigger an automatic quarantine. - A process that simulates interactions between survivors.
- The application layer, when it has to decide whether an
ExposedSurvivorshould be marked asInfected(we'll get to that layer in section 3).
What matters is that the business logic (how infection is calculated) lives in one place, under a clear name that says what it does. If tomorrow the zombie experts announce that "actually, it spreads faster through the air", you only change this service.
When the service coordinates several aggregates
The previous example is a "pure" service: it just does math on primitive values. There's another situation that's just as valid, though: business logic that involves several aggregates at once.
Say we need to move a survivor from one shelter to another. The operation has specific business rules:
- An infected survivor can't be transferred.
- The destination shelter must have room.
- If the survivor is a specialist (doctor, engineer), the source shelter can't drop below its required minimum of specialists.
Where does this logic live? Not in the shelter (Shelter), which knows nothing about the other shelter. Not in the survivor (Survivor), who doesn't decide where they go. It's a rule that spans two aggregates, and that's where the domain service steps in.
export class SurvivorTransferService {
/**
* Validates and carries out the transfer of a survivor between two shelters,
* applying every business rule in the domain.
*
* ⚠️ The aggregates must arrive already loaded: this service
* doesn't touch repositories or the database.
*/
public transfer(
survivor: Survivor,
fromShelter: Shelter,
toShelter: Shelter
): void {
// Domain rule: infected survivors don't get moved
if (survivor.isInfected()) {
throw new DomainError("An infected survivor can't be transferred");
}
// Domain rule: the destination must have room
if (!toShelter.hasCapacity()) {
throw new DomainError(`Shelter ${toShelter.id} is at capacity`);
}
// Domain rule: a specialist can't leave if that drops the source
// shelter below the safety minimum
if (survivor.isSpecialist() && fromShelter.wouldBeUnsafeWithout(survivor)) {
throw new DomainError(
`${survivor.name} is a specialist and leaving would put the shelter in a critical situation`
);
}
// Apply the transfer to both aggregates
fromShelter.removeSurvivor(survivor.id);
toShelter.admit(survivor);
}
}
The key is in the comment: the aggregates arrive already loaded. This service doesn't know or care whether the data came from PostgreSQL, a cache or a grimy filing cabinet. It just applies domain rules to domain objects.
Even though SurvivorTransferService coordinates the move between two shelters, the aggregates still have the final say. The service doesn't do shelter.count++ by hand (that would break encapsulation). It calls toShelter.admit(), and the aggregate makes sure its invariant ("never go over maximum capacity", for example) holds. If the service tried to force something illegal, the aggregate would throw and protect the shelter's integrity.

2. Repositories
We have aggregates with well-guarded business rules and domain services that calculate important things. One piece is still missing, and it's a big one: how do we save these aggregates to the database and get them back?
The persistence problem
Think of it this way. The shelter's doctor knows how to treat wounds, stitch up bites and spot the first symptoms of a zombie infection. But there's no reason for them to know where the cabinet with the medical records is, or how the medical supply room is organized. Those are two completely different jobs. The day we change the filing system, the doctor doesn't have to learn anything new. They just keep doing their job.
Same with the domain and persistence.
If we let our aggregates know how they get stored in the database, we'd be mixing two completely different responsibilities:
// ❌ AWFUL: The aggregate knows about SQL
class Shelter {
public async save(): Promise<void> {
await db.query(
"UPDATE shelters SET capacity = ?, current_count = ? WHERE id = ?",
[this.capacity, this.currentCount, this.id]
);
// And now what do we do with the survivors? Another table? JSON?
}
}
That throws separation of concerns out the window. The domain shouldn't know whether you persist data with PostgreSQL, MongoDB, JSON files or carrier pigeons.
The fix: repositories as abstractions
A repository is an abstraction that behaves like an in-memory collection, while underneath it can store the data wherever it needs to. It's the go-between for the pure domain and the dirty infrastructure. In DDD it's always an interface (or an abstract class). The domain uses that interface without knowing how it's implemented:
// This goes in the DOMAIN layer
// It defines WHAT operations we need, not HOW they're done
export interface ShelterRepository {
// Find a shelter by its ID
findById(id: string): Promise<Shelter | null>;
// Save a shelter (create or update)
save(shelter: Shelter): Promise<void>;
// Find shelters near some coordinates
findAllNear(coords: Coordinates, radiusKm: number): Promise<Shelter[]>;
// Find every shelter with room available
findWithCapacity(): Promise<Shelter[]>;
}
Look at what's NOT in this interface:
- ❌ No SQL, MongoDB or any other specific technology
- ❌ Nothing about tables, collections or data structure
- ❌ Nothing about connections, transactions or pooling
Only domain operations, in the language of the business: "find shelter", "save shelter", "find nearby".
Implementations go in infrastructure
The concrete implementation (SQL, Mongo, in-memory) lives in the infrastructure layer, fully separated from the domain:
// This goes in the INFRASTRUCTURE layer
export class PostgreSQLShelterRepository implements ShelterRepository {
async findById(id: string): Promise<Shelter | null> {
const row = await db.query("SELECT * FROM shelters WHERE id = ?", [id]);
if (!row) return null;
// Map from the database row to the aggregate
return this.mapToAggregate(row);
}
async save(shelter: Shelter): Promise<void> {
// Here we decide how to persist the aggregate
await db.query(
"INSERT INTO shelters ... ON CONFLICT UPDATE ...",
[shelter.id, shelter.capacity, /* etc */]
);
}
// ... other methods
}
// We could also have an in-memory implementation for tests
export class InMemoryShelterRepository implements ShelterRepository {
private shelters: Map<string, Shelter> = new Map();
async findById(id: string): Promise<Shelter | null> {
return this.shelters.get(id) || null;
}
async save(shelter: Shelter): Promise<void> {
this.shelters.set(shelter.id, shelter);
}
// ... other methods
}
What you get out of it
- A pure domain: Aggregates know nothing about persistence. They only hold business logic.
- Testability: You can test your domain with an
InMemoryRepository, no real database to spin up. - Flexibility: You can switch from PostgreSQL to MongoDB without touching a single line of the domain. You only swap the repository implementation.
- Dependency inversion: The domain defines the interface it needs, and infrastructure implements it. The domain doesn't depend on infrastructure, it's the other way around (that's the D in SOLID, an older article of mine in Spanish).
In short, repositories are the border between the clean world of business rules and the messy world of databases, APIs and files. And that border is drawn very precisely by an interface.
3. The application layer: the conductor
We now have aggregates with business rules and repositories that persist data. Something's still missing, though: who coordinates all this? Who takes requests from the outside and turns them into domain operations?
That's the job of the application layer. It orchestrates, and it holds no business logic. It's the orchestra conductor saying "you do this, then you do that, and finally you do the other thing".
What does the application layer do?
The application layer is in charge of:
- Receiving commands or requests from the outside (REST API, GraphQL, CLI, etc.)
- Checking permissions and authorization (is this user allowed to do this?)
- Loading aggregates from the repositories
- Calling domain methods (where the real business logic lives)
- Saving the changes through the repositories
- Publishing domain events so others find out (we'll cover them in the next section)
Just as important is what the application layer does NOT do:
- ❌ Hold business rules (that's the domain)
- ❌ Know about persistence details (that's infrastructure)
- ❌ Format responses for HTTP, GraphQL, etc. (that's the presentation layer)
Use cases and the Command + Handler pattern
Every operation the system exposes to the outside world is a use case. For example:
- Admit a survivor
- Transfer supplies
- Trigger a quarantine
The application layer is organized around them: one use case per operation, with all the orchestration it needs and nothing else.
A very common DDD pattern for implementing those use cases is Commands and Handlers. The Command describes the intent; the Handler is the implemented use case:
// A Command represents an INTENT
// "I want to admit this survivor into this shelter"
export class AdmitSurvivorCommand {
constructor(
public readonly shelterId: string,
public readonly survivor: Survivor
) {}
}
// The Handler is what CARRIES OUT the intent
export class AdmitSurvivorHandler {
constructor(
private shelterRepo: ShelterRepository,
private eventBus: EventBus
) {}
async handle(cmd: AdmitSurvivorCommand): Promise<void> {
// 1. Load the aggregate from the repository
const shelter = await this.shelterRepo.findById(cmd.shelterId);
if (!shelter) {
throw new Error("Shelter not found");
}
// 2. Call the domain method
// THIS is where the business rules get checked (capacity, etc.)
shelter.admit(cmd.survivor);
// 3. Persist the changes
await this.shelterRepo.save(shelter);
// 4. Publish a domain event (we'll explain this in the next section)
// ...
}
}
The whole flow
One big win of organizing the application layer into use cases is that the same use case can be called from any entry point into the system: a REST API, a command-line tool, an event coming from another service or an automated batch job. The business logic and the orchestration stay the same every time. The only thing that changes is who builds the Command and hands it to the Handler.
Here's an example, with a REST API calling the use case we just defined:
// The API receives an HTTP request (presentation layer)
app.post("/shelters/:id/admit", async (req, res) => {
const command = new AdmitSurvivorCommand(
req.params.id,
new Survivor(req.body.survivorId, req.body.name, req.body.health)
);
// Build the Command and delegate to the use case
await admitSurvivorHandler.handle(command);
res.status(200).json({ message: "Survivor admitted" });
});
Notice how the responsibilities are split:
- API (presentation): Takes HTTP in, builds the command, sends HTTP back
- Handler (application): Orchestrates the use case, with no business logic
- Shelter (domain): Checks capacity, applies the rules, protects the invariants
- Repository (infrastructure): Persists to the database
If tomorrow you wanted to admit survivors from a CLI, from a message sent by another system or from a nightly job, the only thing that would change is how the AdmitSurvivorCommand gets built. The use case (the AdmitSurvivorHandler) stays untouched. And the domain doesn't even notice.
Domain service vs. application layer
This is where a lot of people get confused, because an application use case also "coordinates" things. The difference matters a lot:
// DOMAIN SERVICE
// Receives objects already loaded, applies business rules, no I/O
transferService.transfer(survivor, shelterA, shelterB);
// APPLICATION HANDLER
// Loads objects, calls the domain, saves changes, dispatches events
class TransferSurvivorHandler {
public constructor(
private survivorRepo: SurvivorRepository,
private shelterRepo: ShelterRepository,
private transferService: SurvivorTransferService
) { }
async handle(cmd: TransferSurvivorCommand): Promise<void> {
// 1. LOAD (I/O: repository access)
const survivor = await this.survivorRepo.findById(cmd.survivorId);
const fromShelter = await this.shelterRepo.findById(cmd.fromShelterId);
const toShelter = await this.shelterRepo.findById(cmd.toShelterId);
// 2. DOMAIN (no I/O: business logic only)
this.transferService.transfer(survivor, fromShelter, toShelter);
// 3. SAVE (I/O: repository access)
await this.shelterRepo.save(fromShelter);
await this.shelterRepo.save(toShelter);
await this.survivorRepo.save(survivor);
}
}
This table sums up the differences between the two kinds of service so you don't mix them up:
| Domain service | Application service | |
|---|---|---|
| What does it do? | Applies business rules | Orchestrates a whole use case |
| What does it work with? | Domain objects, already loaded | Repositories, events, external services |
| Does it do I/O? | ❌ Never | ✅ Always |
| Does it hold business logic? | ✅ Yes | ❌ No (it delegates to the domain) |
| Does it know about external connections? | ❌ Never | Indirectly, through repositories |
Put another way: the domain service knows which rules govern a business operation. The application service knows how to run that use case from start to finish. One is logic; the other is coordination, or orchestration.
If you ever catch yourself asking "should this be a domain service or a use case?", look at the I/O. If the code needs to hit repositories or any other external infrastructure, it's application. If it only works on domain objects you already have in memory, it's domain.
4. Domain Events
Domain events represent facts that already happened and that matter to the business. They aren't orders or requests. They're notifications of something that happened and that other parts of the system might want to know about.
Why do they matter?
Events are the key to decoupling parts of the system that shouldn't know about each other directly. Back to our apocalypse.
Say a zombie squeezes through a gap in the perimeter fence. The lookout who spots it can't run off to warn the doctor, then the Logistics lead, then the commander, one at a time. By the time he finished the rounds, half the shelter would be infected. So he rings the alarm instead, and everyone who needs to react does. The lookout doesn't know or care who hears it. His job is to spot and warn, not to coordinate. That's exactly what domain events are.
As usual, a code example makes this easier. Think about what has to happen when someone gets admitted into the shelter's group of survivors:
- The Logistics team needs to know there's one more mouth to feed
- The Medical team has to register the survivor for a checkup
- The Command team updates the staff deployment map
If you did all this directly in the shelter's admit() method, you'd end up with something like this:
// ❌ BAD: The shelter knows way too much
public admit(survivor: Survivor): void {
this.survivors.push(survivor);
this.logisticService.updateFoodConsumption(this.id);
this.medicalService.scheduleCheckup(survivor.id);
this.commandService.updateMap(this.id, this.currentCount);
}
This is terrible because:
- The
Shelternow depends on 3 services that aren't its business - If tomorrow you want something else to react to an admission, you have to change the
Shelter - You're coupling contexts that should stay apart
The fix: domain events
Instead of calling all those services directly, the Handler (the one we met in the previous section) publishes an event after saving the aggregate. Whoever cares about that event can react to it.
First we define the events as types named in the past tense (they already happened, they're done deals):
type DomainEvent =
| {
type: "SurvivorAdmitted";
shelterId: string;
survivorId: string;
timestamp: string;
}
| {
type: "SurvivorInfected";
survivorId: string;
infectedBy?: string; // Optional: who infected them
timestamp: string;
}
| {
type: "ShelterRestocked";
shelterId: string;
supplies: Array<{ name: string; amount: number }>;
timestamp: string;
}
| {
type: "QuarantineActivated";
shelterId: string;
reason: string;
affectedCount: number;
timestamp: string;
};
The shelter's admit() method stays clean. It applies rules and changes state, and knows nothing about what happens next:
public admit(s: Survivor): void {
if (this.currentCount + 1 > this.capacity) {
throw new Error("Shelter is full");
}
this.survivors.push(s);
this.currentCount++;
// That's it: the domain applies rules and changes state
}
And the Handler is the one that publishes the event, always after saving. It knows which operation it just ran, so it can publish the right event:
class AdmitSurvivorHandler {
async handle(cmd: AdmitSurvivorCommand): Promise<void> {
const shelter = await this.shelterRepo.findById(cmd.shelterId);
shelter.admit(cmd.survivor);
await this.shelterRepo.save(shelter);
// If everything went well, announce the event.
await this.eventBus.publish({
type: "SurvivorAdmitted",
shelterId: shelter.id,
survivorId: cmd.survivor.id,
timestamp: new Date().toISOString()
});
}
}
In production systems, people usually reach for the Outbox pattern to guarantee the event really gets published once all the transactions have gone through. That's out of scope for this article, but you can read about it in part four of this series.
Who listens to the events?
Different parts of the system can subscribe to the events they care about:
// The Logistics service listens for admissions
eventBus.on("SurvivorAdmitted", (event) => {
logisticService.updateFoodConsumption(event.shelterId);
});
// So does the Medical service
eventBus.on("SurvivorAdmitted", (event) => {
medicalService.scheduleCheckup(event.survivorId);
});
// Command reacts to infections to assess evacuations
eventBus.on("SurvivorInfected", (event) => {
commandService.evaluateEvacuation(event.shelterId);
});
// Medical sends out alerts when there's an outbreak
eventBus.on("QuarantineActivated", (event) => {
alertService.sendUrgentNotification(
`Quarantine activated in ${event.shelterId}! Reason: ${event.reason}`
);
});
Why use events
- Decoupling: The
Shelterdoesn't know who reacts to its events, and doesn't care. It just publishes what happened. - Extensibility: If tomorrow another service needs to react to
SurvivorAdmitted, you add a listener. You don't touch theSheltercode. - Auditing: Events are a record of everything that happened. Since anyone can receive them, you can store them and keep a full history of the apocalypse.
- Async processes: Events let you kick off processes that don't need to finish right away (sending alerts, updating dashboards, generating reports, etc.).
- Event Sourcing: If you also store every event in chronological order, you're one step away from Event Sourcing, which, as Doc Brown would say, is the domain's real time machine: it lets you rebuild everything that happened, step by step, from day 0 of the apocalypse.
Events are the backbone of well-designed complex systems. In DDD, they're the glue that holds bounded contexts together without creating direct dependencies between them.

Wrapping up
Building these layers can look like a lot of extra work when there are zombies pounding on the door, but it's what separates an organized group of survivors from an all-you-can-eat buffet for the undead. Because the medical team (domain) and the supply crew (infrastructure) speak the same language and respect each other's borders, Luis is now in a safe isolation area instead of shambling around the mess hall looking for brains.
We've gone from "code that works" to a system that reflects the reality of our survival.
In the next article we take the final step: how to keep everything from blowing up when several things happen at once (transactions), which mistakes you should never make (antipatterns) and how to prove our shelter really is impenetrable (testing). Keep the doors locked and the code clean!
More articles in the series
- Part 1: Ubiquitous language, bounded contexts, entities, value objects and aggregates.
- Part 3: Sagas, antipatterns and tests.
- Part 4: The Outbox pattern, eventual consistency between aggregates, the Snapshot pattern.
- FAQ: Frequently asked questions.
If this left you wanting more architecture, Domain-Driven Design in a Zombie Apocalypse tells the whole story: entities, aggregates, bounded contexts, and a shelter that holds up as the project grows. In paperback and on Kindle, with a free sample if you want to look inside first.
To pick up where this article leaves off, the book has:
- Chapter 9, “Domain events”: where an event is born, domain events vs. integration events, projections and Event Sourcing.
- Chapter 10, “Hexagonal architecture”: the domain at the center, adapters and folder structure.