DDD in a Zombie Apocalypse. Part 1
2026-02-22 · [ leer en español ]
Picture this: we're in the middle of a zombie apocalypse. Your group of survivors has holed up in an old abandoned power plant, and things are bad. Someone has to manage shelters, coordinate supply runs, keep infections in check and make calls that can mean life or death. So you decide to build a system to help with all of it.
Months later the system works, but there's a problem. Every time the group leader (our "domain expert") asks for a change, you and your team get lost in translation. The leader talks about "quarantined survivors" and you think user.status = 3. The leader says "shelter at critical capacity" and you see shelter.count >= shelter.max. The code works, but nobody really understands what it does without opening every file and untangling the logic. And in a zombie apocalypse, wasting time trying to figure out the code can get you killed.
This is exactly the kind of problem Domain-Driven Design set out to solve. And no, DDD isn't an architecture, or a magic framework you install with npm. It's a way of building software that proposes something radical and obvious at the same time: the code should be a faithful mirror of how things work in the real world of the business (or, in our case, of the apocalypse).
Eric Evans laid out the idea in 2003 in his book Domain-Driven Design: Tackling Complexity in the Heart of Software. More than two decades later, the premise is as strong as ever: if the survivor leader and the developer both look at the system's model, they should see the same thing. Same concepts, same words, same rules.
Sounds simple? It is. Easy to pull off? Not at all. But when it works, the difference is huge: the code stops being an incomprehensible black box and becomes a living picture of the domain.
Why DDD in a zombie apocalypse?
Our survival domain has everything a good DDD model needs:
- Clear actors: Survivors, Shelters, Supplies, the Infected
- Hard rules: maximum shelter capacity, risk of infection by proximity, evacuation priority
- Events that matter:
SurvivorInfected,ShelterResupplied,QuarantineActivated - Immediate consequences: one bug in the quarantine logic can mean a massive outbreak
If the code speaks the same language as the apocalypse, decisions get faster and less dangerous. If instead we have User.status = 2 where there should be Survivor.infect(), somebody's going to get bitten because they didn't know what that "2" did.
Now that we understand the problem, let's see what tools DDD gives us to fix it.

1. Ubiquitous language
The first pillar of DDD is setting up a shared language between everyone on the project. And by shared I mean that the words the survivor leader uses to describe how the shelter is run have to be exactly the same ones that show up in the code, the tests, the docs and the team meetings.
Why does this matter so much? Let's take a concrete example from the apocalypse.
Say the group leader tells you: "When a survivor shows signs of infection, they go into quarantine immediately until a doctor checks them." If you, the developer, translate that in your head into user.status = 2 and user.quarantine = true, what happens three months later when another developer has to change that logic? They'll have to do some code archaeology just to figure out what status = 2 means.
The ubiquitous language removes that mental translation. In our shelter:
- We don't say
User, we saySurvivor. Because in a zombie apocalypse there are no "users", there are people fighting to stay alive. - We don't have a
setHealth(value)method, we havetakeInjury(),heal()orapplyBandage(). Anyone gets what they do without opening the docs. - There's no
status = 5, there's aquarantine()method that does exactly what it says.
What happens if we skip the ubiquitous language?
The direct result is lost domain knowledge. The code turns cryptic, full of abbreviations and abstractions only the original developer understands. When that person leaves (or worse, turns into a zombie), what they knew goes with them.
On top of that, every conversation with the business team becomes an exercise in simultaneous interpretation: they talk about "emergency resupply" and you think supply.priority = 1. They say "safe route" and you see route.safe = true. It's exhausting and, worst of all, an easy way to misunderstand each other.
In practice
If the group leader mentions "quarantine" in a spec, the code will have a class or concept called Quarantine, not IsolationZone or StatusType2. If they talk about "critical supplies", the code will have CriticalSupplies, not ImportantSupplies.
This shared language becomes the project's living dictionary. And it should be written down: a simple glossary defining the key domain terms can save your team hours of confusion.

In the image above, the developer has to stop thinking in technical terms and start speaking the same language as the leader.
The difference between the code on the left and the code on the right looks cosmetic, but in practice it's enormous:
// ❌ Without ubiquitous language
user.status = 2;
user.quarantine = true;
// ✅ With ubiquitous language
survivor.quarantine();
In the first case, what does status = 2 mean? Is there a status = 1? A status = 3? Who knows what each number implies? In the second case the intent is crystal clear. And if later on quarantine also means locking the survivor out of the mess hall or notifying the doctor, where does that logic go? In the quarantine() method, of course. The code organizes itself when the language is right.
2. Bounded contexts
Here comes one of the most powerful ideas in DDD, and also one of the most misunderstood. A bounded context is basically a boundary inside which a specific model makes sense and holds together.
Why do we need it? Because in large systems the same word can mean completely different things depending on who's using it. That isn't a mistake, it's just how things are.
Let's take an example from the apocalypse: the word "Survivor".
- For the Logistics team, it's someone who uses up resources, has a location and can carry supplies. They care about how much the survivor can carry and which route they're on.
- For the Medical team, it's a potential patient with a medical history, a health level and an infection risk. They care about body temperature and whether the survivor has been exposed to bites.
- For the Command team, it's a unit with specific skills that can be assigned to shelters or missions. They care about combat experience or technical know-how.
See the problem? If we try to cram all of that into a single Survivor class, we'll end up with a 50-property monster where half the fields make no sense in any given context. Even worse, when Logistics wants to change how carrying capacity is calculated, they could accidentally break something in Medical.
Divide and conquer
The fix is to split our system into bounded contexts, each with its own model:
Logistics context
- Manages supply routes between shelters
- Tracks stock levels and expected consumption
- Calculates transport costs and route risks
- Its
Survivorhas: location, carrying capacity, mobility status
Medical context
- Tracks infections and possible outbreaks
- Manages vaccines and medical treatments
- Monitors general health
- Its
Survivorhas: medical history, symptoms, immunity level
Command context
- Assigns survivors to shelters
- Decides evacuations and redistributions
- Plans missions and strategy
- Its
Survivorhas: skills, experience, assigned shelter
Inside each context, the model and the language are consistent and focused. No "extra" properties, no responsibilities that don't belong there.

In the image above you can see the three bounded contexts of our apocalypse: logistics, medical and command.
Communication between contexts
Of course, these contexts don't live in isolation. When Medical detects an outbreak, Command needs to know so it can trigger an evacuation. When Logistics updates a shelter's stock, Command has to find out whether there's a critical shortage.
Contexts talk to each other through well-defined contracts:
- APIs: clear interfaces that expose only what's needed
- Domain events: "X has happened" (for example,
SurvivorInfected,ShelterResupplied) - Anti-corruption layers: layers that translate between the models of different contexts, shielding each one from changes in the other
For example, when Medical publishes the OutbreakDetected event, Command doesn't need the internal medical details. It only gets what it cares about: which shelter is affected and how many people are at risk.

Communication diagram between Medical, Logistics and Command
3. Entities and value objects
One of the most important distinctions in DDD is the difference between something that "is" and something that "has". Sounds philosophical, but it has very practical consequences for how we design our code.
Entity: what matters is WHO it is
An entity is something with a unique identity that carries on over time, no matter how its attributes change.
Take a survivor named Gema. When Gema arrives at the shelter, she has 100 health points and isn't infected. Over the following days Gema gets wounded (now she's at 80), then she's patched up (back to 95), then she catches a mild infection... her state keeps changing. But the whole time we're still talking about Gema, the same survivor. Her identity stays put even though her attributes don't.
That's an entity. What matters is who it is, not what shape it's in.
What entities look like:
- They have a unique identifier (ID) that tells them apart
- Their identity persists over time
- They can change state and still be themselves
- Two entities with the same attributes but different IDs are different
- Gema with 100 health ≠ Pedro with 100 health (they're different people)
// Entity - Has its own identity through the ID
class Survivor {
constructor(
public readonly id: string, // The ID never changes
public name: string,
public health: number
) {}
takeInjury(points: number): void {
this.health = Math.max(0, this.health - points);
}
heal(points: number): void {
this.health = Math.min(100, this.health + points);
}
// Equality is decided by ID, not by attributes
equals(other: Survivor): boolean {
return this.id === other.id;
}
}
const gema = new Survivor("survivor-1", "Gema", 100);
gema.takeInjury(20); // health: 80 → still Gema
gema.heal(15); // health: 95 → still Gema
const anotherPerson = new Survivor("survivor-2", "Gema", 95);
// Same name and same health, but NOT the same person
console.log(gema.equals(anotherPerson)); // false → different ID
Value object: what matters is WHAT it is
A value object is something defined entirely by its attributes. It has no identity of its own, it just represents a value.
Think about the coordinates of a supply point: { lat: 40.4168, lon: -3.7038 }. Those coordinates aren't anybody or anything. They're just a value that describes a location. If tomorrow you have another position with exactly the same latitude and longitude, it's the same coordinate, no matter who uses it or when it was created.
What value objects look like:
- They have no identity of their own
- They're defined entirely by their attributes
- They're immutable: if you need to change one, you create a new one
- Two value objects with the same attributes are identical
- Coordinates(40.4168, -3.7038) === Coordinates(40.4168, -3.7038)
Other examples in our apocalypse:
Supply: one pack of bandages is identical to any other pack of bandages of the same kindEvacuationDate: December 25, 2026 is the same day for everyoneAmmoCount: 50 rounds are 50 rounds, no matter who counts them
// Value Object - Immutable
class Coordinates {
constructor(
public readonly lat: number,
public readonly lon: number
) {}
// Compared by value, not by reference
equals(other: Coordinates): boolean {
return this.lat === other.lat && this.lon === other.lon;
}
}
// If you need different coordinates, you create new ones
const point1 = new Coordinates(40.4168, -3.7038);
const point2 = new Coordinates(41.3851, 2.1734); // New object
// Comparison
console.log(point1.equals(point2)); // false
console.log(point1.equals(new Coordinates(40.4168, -3.7038))); // true
Why does the distinction matter?
Mix up entities and value objects and you can make some serious mistakes:
- Treating an entity like a value object: if you compare two survivors only by their current health, you could decide they're the same person. Disaster.
- Treating a value object like an entity: if you give every set of coordinates a unique ID, you'll end up with thousands of "different" objects that actually point to the same spot. Wasted memory and logic that's more complicated than it needs to be.
The simple rule: if "is it the same one?" gets answered with an ID, it's an entity. If it gets answered by comparing values, it's a value object.

4. Aggregates: the keeper of the rules
Now we get to one of the most powerful concepts in DDD: aggregates. If you've made it this far thinking "fine, I've got entities and value objects, what else do I need?", brace yourself, because aggregates are what really keep your domain in one piece.
What's an aggregate?
An aggregate is a group of entities and value objects treated as a single unit when changes are made. Inside that group there's an aggregate root, which is the only door you're allowed to use to change anything inside the aggregate.
Think of it as a shelter with a single guarded entrance. Nobody gets in or out without going through that door. Nobody changes anything inside without the guard's say-so. That guard is the aggregate root.
Why do we need this?
In our zombie apocalypse, say we have a shelter with these critical rules:
- Maximum capacity: a shelter can only hold a limited number of survivors (otherwise the air or the food runs out, or people simply don't fit).
- Mandatory quarantine: if there are infected people who aren't in quarantine, nobody else gets in (risk of mass infection).
- Supply management: the shelter's supplies have to be controlled and accounted for.
If we let any part of the code change the survivor list or the supplies directly, who makes sure these rules hold? Nobody. And as soon as someone adds a survivor without checking capacity, or hands out supplies with no control, chaos is guaranteed.
The shelter as an aggregate
We're going to model Shelter as the aggregate root. Everything that happens to that shelter's survivors and supplies has to go through it:
- ✅ The root (
Shelter) exposes methods that check the invariants before making changes - ✅ Survivors and supplies are private, nobody can touch them directly from outside
- ✅ Every operation (
admit(),addSupply()) protects the business rules - ❌ No public setters and no direct access to the internal state
// Value Object - Represents a generic supply
// Since it's a Value Object, it's immutable (readonly)
class Supply {
constructor(
public readonly name: string,
public readonly amount: number
) {}
}
// Entity - Represents an individual survivor
// It has a unique identity (id) and can change state
class Survivor {
constructor(
public readonly id: string,
public name: string,
public health: number
) {}
}
// Aggregate Root - The "front door" to our aggregate
// It's the ONLY way to change survivors and supplies
export class Shelter {
// CRITICAL: These arrays are PRIVATE
// Nobody outside this class can change them directly
private survivors: Survivor[] = [];
private supplies: Supply[] = [];
private currentCount = 0;
constructor(
public readonly id: string,
public readonly capacity: number // Invariant: we can't go over it
) {}
// Public method to admit survivors
// This is where we protect our business rules
public admit(s: Survivor): void {
// INVARIANT 1: Check capacity BEFORE admitting
// This is the rule that must NEVER be broken
if (this.currentCount + 1 > this.capacity) {
throw new Error("Shelter full: we can't admit any more survivors");
}
// Only if the check passes do we change the state
this.survivors.push(s);
this.currentCount++;
// We could publish an event here: SurvivorAdmitted
}
// Method to add supplies
// Business logic: if the supply already exists, add up the amounts
public addSupply(supply: Supply): void {
const existing = this.supplies.find(x => x.name === supply.name);
if (existing) {
// Value Objects are immutable, so we create a new one
const merged = new Supply(existing.name, existing.amount + supply.amount);
// Replace the old one with the new one
this.supplies = this.supplies.map(x => x === existing ? merged : x);
} else {
// If it doesn't exist, just add it
this.supplies.push(supply);
}
}
// Query methods: we return COPIES, not the original references
// That way nobody can change the state from outside
public getSurvivors(): Survivor[] {
return [...this.survivors];
}
public getSupplies(): Supply[] {
return [...this.supplies];
}
}
Let's see how it works in practice:
// Create a shelter with room for 3 survivors
const electricShelter = new Shelter("Abandoned Power Plant", 3);
// Admit three survivors, no problem
electricShelter.admit(new Survivor("1", "Pepe", 10));
electricShelter.admit(new Survivor("2", "Juana", 8));
electricShelter.admit(new Survivor("3", "Atolón", 9));
console.log(electricShelter.getSurvivors());
// [
// Survivor: { "id": "1", "name": "Pepe", "health": 10 },
// Survivor: { "id": "2", "name": "Juana", "health": 8},
// Survivor: { "id": "3", "name": "Atolón", "health": 9 }
// ]
// If we try to admit a fourth survivor...
// electricShelter.admit(new Survivor("4", "Ariel", 7));
// ❌ Error: "Shelter full: we can't admit any more survivors"
// The invariant keeps us from breaking the rule
// Add supplies
electricShelter.addSupply(new Supply("bandages", 10));
console.log(electricShelter.getSupplies());
// [Supply: { "name": "bandages", "amount": 10 }]
// If we add more bandages, they're added up automatically
electricShelter.addSupply(new Supply("bandages", 7));
console.log(electricShelter.getSupplies());
// [Supply: { "name": "bandages", "amount": 17 }]
// Notice there aren't two "bandages" entries, they've been merged
Key points of the aggregate
Look at what makes this code a good aggregate:
Private state: the
survivorsandsuppliesarrays are private. There's no way to change them from outside without going through the root's methods.Protected invariants: before changing any state, we check that we aren't breaking the rules (
capacity). If a rule would be broken, we throw an error and the state stays untouched.Methods that mean something to the business: there's no
setSurvivors()oraddSurvivorToArray(). There'sadmit(), which means something in the language of the domain.Defensive copies: the getters return copies (
[...this.survivors]), not the original references. That stops anyone from doingshelter.getSurvivors().push(...)and changing the state without going through the checks.Transactional consistency: when you change an aggregate, all the changes happen together. Either the survivor is fully admitted (with every check), or they aren't admitted at all. No invalid in-between states.
The next image sums up the aggregate's structure: Shelter is the root, the survivors and supplies live inside it, and access always goes through the root's public methods:

Class diagram of the aggregate: Shelter as the root, Survivor as an entity and Supply as a value object.
And if we bring it into the physical world of the apocalypse, the analogy fits perfectly:

The fighter at the door is the aggregate root. It doesn't matter who's trying to get in or how urgent things are: if the shelter is full, nobody gets in. The invariants always hold. And when the truck shows up with supplies, it goes through him too before the boxes make it inside.
To be continued
In this first part we've laid the foundations of DDD: the ubiquitous language that gets rid of mental translation, bounded contexts that split the system along sensible lines, entities and value objects that model identity and value, and aggregates that protect the domain's invariants.
In part two we'll see how to connect all this to the outside world: domain services, events, repositories and the application layer. We'll also look at the most common antipatterns and when DDD makes sense (and when it doesn't).
More articles in the series
- Part 2: Domain services, repositories, the application layer and domain events.
- Part 3: Sagas, antipatterns and tests.
- Part 4: The Outbox pattern, eventual consistency between aggregates and 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 3, “Context map”: who's upstream and who's downstream, the ways contexts relate and the full map of the shelter.
- Chapter 5, “Aggregates”: factories for complex construction, where the logic lives and when an entity with a list is enough.