DDD in a Zombie Apocalypse. Part 3
2026-03-06 · [ leer en español ]
In part one we laid the foundations: the ubiquitous language that gets the group leader and the developer speaking the same language, bounded contexts so Medical, Logistics and Command don't step on each other's toes, and aggregates standing guard at the shelter door. In part two we connected that core to the outside world: domain services for logic that involves several players, repositories that keep the domain unaware of the database, the application layer as the conductor, and domain events that let the whole system react without direct dependencies.
But three questions are still up in the air. What happens when a single transaction isn't enough to coordinate a full evacuation? What are the worst mistakes you can make implementing DDD, and how do you avoid them? And how do you prove all those pieces actually work before the horde shows up?
In this third installment we'll cover consistency and Sagas, the antipatterns that do the most damage in production, and testing the domain.

1. Consistency, transactions and Sagas
So far we've seen operations that touch a single aggregate: admit a survivor, add supplies, calculate infection risk. Clean, well-scoped operations. But in the middle of a zombie apocalypse we rarely get the luxury of keeping things simple. What happens when a horde surrounds Shelter A and everyone has to move to Shelter B while supplies get redistributed across several sites? What happens when one transaction can't cover all of that?
The golden rule: one aggregate = one transaction
Aggregates define transactional boundaries. When you modify an aggregate, every change inside it happens atomically (all or nothing). But that guarantee only applies within one aggregate.
Take the simplest case: moving a survivor from Shelter A to Shelter B. The operation involves two aggregates:
- Shelter A has to "check out" the survivor
- Shelter B has to "admit" them
Technically you could wrap both in the same database transaction if they share infrastructure (and we'll see when that can make sense). But doing it couples aggregates together, which DDD tells you to avoid. And if the shelters live in separate distributed services, there's simply no transaction that covers both. That said, remember that sometimes you can bend the rules, as long as you're careful. Otherwise you'll set off a series of unfortunate events that ends with a horde all around you.
Remember that each aggregate owns its own state and shouldn't need the other one to confirm its changes. Put them in the same transaction and you're tying them together: if one fails, it drags the other down with it. That's exactly what we wanted to avoid when we drew a boundary between them.
Solution 1: Simple local transactions
When the operation is simple and the aggregates share a database, you can use a local transaction, carefully:
async transferSurvivor(
fromShelterId: string,
toShelterId: string,
survivorId: string
): Promise<void> {
await db.transaction(async (trx) => {
// Load both aggregates inside the same transaction
const fromShelter = await repo.findById(fromShelterId, trx);
const toShelter = await repo.findById(toShelterId, trx);
// Domain operations: the rules still apply
const survivor = fromShelter.removeSurvivor(survivorId);
toShelter.admit(survivor);
// If anything fails, the transaction rolls back both changes
await repo.save(fromShelter, trx);
await repo.save(toShelter, trx);
});
}
This brings in coupling we may not want. Still, it works fine when the operation is quick and both shelters sit in the same database. If not, you need something sturdier.
Solution 2: Sagas / Process Managers
Sagas are the tool for long-running or distributed operations. The idea is simple: instead of one big transaction wrapping everything, we use a sequence of small transactions coordinated through events. And if something fails along the way, compensating actions try to fix the state so the system stays consistent.
As for where it lives in the code: the Saga is a class in the application layer, just like the command handlers we saw in part two. The difference is that a handler deals with a one-off operation, while the Saga orchestrates a process that can take minutes or hours and span several aggregates. It holds no business rules (those are still the domain's job). It decides which command to send next based on the events it receives.
Picture the evacuation of Shelter A: the zombies have broken through the outer perimeter and everyone has to get to Shelter B before it's too late. The process has several steps:
- Check capacity at Shelter B (a query, it doesn't change anything)
- Mark Shelter A as "evacuating" → emits
EvacuationStarted - For each survivor:
- Reserve a slot at Shelter B → emits
SlotReserved - Remove the survivor from A → emits
SurvivorRemoved - Admit them at B → emits
SurvivorAdmitted - If B has no room → compensation: cancel the evacuation (
SlotUnavailable)
- Reserve a slot at Shelter B → emits
- Transfer critical supplies
- Mark Shelter A as "evacuated" → emits
ShelterEvacuated
sequenceDiagram
participant A as Shelter A
participant Saga as Saga / Process Manager
participant B as Shelter B
A->>Saga: EvacuationStarted
Note over A,B: Survivor 1, transfer succeeds
Saga->>B: ReserveSlot
B->>Saga: SlotReserved ✅
Saga->>A: RemoveSurvivor
A->>Saga: SurvivorRemoved
Saga->>B: AdmitSurvivor
B->>Saga: SurvivorAdmitted ✅
Note over A,B: Survivor 2, transfer succeeds
Saga->>B: ReserveSlot
B->>Saga: SlotReserved ✅
Saga->>A: RemoveSurvivor
A->>Saga: SurvivorRemoved
Saga->>B: AdmitSurvivor
B->>Saga: SurvivorAdmitted ✅
Note over A,B: Survivor 3, Shelter B is full
Saga->>B: ReserveSlot
B->>Saga: SlotUnavailable ❌
Saga->>A: Compensation: CancelEvacuation
Note over A,B: Evacuation canceled. Survivors 1 and 2 are already in B.
Each step is a local transaction on a single aggregate. The Saga usually keeps its own state (which survivors have been moved, what phase the evacuation is in) so it can decide the next step. It listens for events and reacts with the matching command. When Shelter B can't reserve any more slots, the evacuation is canceled: the survivors already moved stay in B and the rest stay in A. There's no going back for the ones who already crossed the wasteland, but the system ends up in a consistent, known state.

When to use which?
- Simple local transaction: two aggregates in the same database, quick operation.
- Sagas: long-running operation, multiple aggregates, distributed systems, or you need compensations for partial failures.
One more important thing: DDD doesn't always guarantee immediate global consistency. Sometimes the system takes a moment to reach a consistent state, and that's fine. It's called eventual consistency. Imagine the system waited for every shelter to confirm before starting the evacuation. Meanwhile, the zombies are crossing the perimeter. In real systems (and real apocalypses), eventual consistency is a fair price for keeping the system running.
2. Antipatterns and common mistakes
Like everything in software engineering, DDD can be done badly. Very badly. And the worst part is that these mistakes don't blow up right away. They pile up until the system is so hard to change that any small tweak sets off a chain of surprises. Exactly what you don't want with a horde at the gates.

Antipatterns are the equivalent of survivors walking straight into the storeroom without going past the guard, the access door ignored and supplies scattered all over the floor.
A. Anemic model: the zombie of code
The name says it all. An anemic model looks like a class with business logic, but it's empty inside: just getters, setters and no rules to protect.
// ❌ BAD: Anemic model
class Shelter {
public id: string;
public capacity: number;
public currentCount: number;
public survivors: Survivor[] = [];
public getSurvivors() { return this.survivors; }
public setSurvivors(s: Survivor[]) { this.survivors = s; }
public getCurrentCount() { return this.currentCount; }
public setCurrentCount(n: number) { this.currentCount = n; }
}
// All the logic lives in a separate service
class ShelterService {
admitSurvivor(shelter: Shelter, survivor: Survivor) {
// What if someone calls setSurvivors() directly and skips this?
if (shelter.getCurrentCount() + 1 > shelter.capacity) {
throw new Error("Shelter full");
}
shelter.getSurvivors().push(survivor);
shelter.setCurrentCount(shelter.getCurrentCount() + 1);
}
}
The problem isn't just cosmetic. With a public setSurvivors(), any part of the code can skip the capacity check. Someone adds survivors straight to the array, the shelter gets overcrowded, and in the apocalypse that can mean an outbreak.
The usual confusion goes like this: "if I need a domain service to transfer supplies between two shelters, don't I end up anemic anyway?" No, because the difference is in what the service does. If it calls methods that hold business logic, the domain is healthy. If it changes state directly and skips those rules, the domain is anemic, however nice the method names are.
// ✅ GOOD: The aggregate protects its invariants
class Shelter {
// There's no setSurvivors(). Instead:
public admit(survivor: Survivor): void {
if (this.currentCount + 1 > this.capacity) {
throw new DomainError("Shelter full: we can't admit any more survivors");
}
this.survivors.push(survivor);
this.currentCount++;
}
// There's no setSupplies(). Instead:
public receiveSupplies(supply: Supply): void {
if (this.isStorageFull()) {
throw new DomainError("Storage full");
}
// Value objects are immutable: if the supply exists, we create a new one with the sum
const idx = this.supplies.findIndex(s => s.name === supply.name);
if (idx >= 0) {
this.supplies[idx] = new Supply(supply.name, this.supplies[idx].amount + supply.amount);
} else {
this.supplies.push(supply);
}
}
public sendSupplies(supply: Supply): void {
const idx = this.supplies.findIndex(s => s.name === supply.name);
if (idx < 0 || this.supplies[idx].amount < supply.amount) {
throw new DomainError(`Not enough supplies: ${supply.name}`);
}
// Immutable value object: we replace it with the reduced amount
this.supplies[idx] = new Supply(supply.name, this.supplies[idx].amount - supply.amount);
}
}
// The domain service coordinates aggregates by CALLING their methods, never through setters:
class SupplyTransferService {
public static transfer(supply: Supply, from: Shelter, to: Shelter): void {
from.sendSupplies(supply); // ← The source applies its rules
to.receiveSupplies(supply); // ← The destination applies its own
}
}
A quick test to tell whether your domain is anemic: could you replace receiveSupplies() with setSupplies(newList) without losing a single business rule? If the answer is yes, the aggregate is empty inside.
B. Giant aggregates: the shelter that holds the whole world
The opposite extreme: a single aggregate that hoards the entire domain. The bigger it grows, the slower it is to load and the more likely a change in one area breaks something in a completely different one.
// ❌ BAD: One aggregate to rule them all
class Shelter {
private survivors: Survivor[];
private supplies: Supply[];
private medicalRecords: MedicalRecord[];
private securityLogs: SecurityLog[];
private weatherConditions: WeatherData[];
private nearbyThreats: Zombie[];
private alliances: Alliance[];
private historicalEvents: Event[];
// ... and 20 more collections
}
Every time someone modifies the Shelter, all that data gets loaded from the database, even if they only need to change the supply level. Concurrency conflicts multiply because every operation locks more data than it needs. And when the doctor wants to add a field to the medical history, the logistics module's tests break, because they share the same class.
Solution: split it into aggregates with clear responsibilities: Shelter (capacity, occupancy), MedicalHistory (patients, treatments), SecuritySystem (alerts, logs). Each one with its own invariants.
C. Bounded contexts as a folder structure
A subtle and very common mistake: creating folders named after contexts but sharing the same data model across all of them.
/contexts
/logistics
LogisticsService.ts // Uses the global Survivor class
/medical
MedicalService.ts // Uses the SAME global Survivor class
/command
CommandService.ts // Uses the SAME global Survivor class
If Logistics, Medical and Command share a Survivor class with 50 properties, any change one of them needs affects the other two. There's no real isolation. It's coupling dressed up as organization.
Solution: each context has its own Survivor model with only the properties it cares about, and they talk to each other through well-defined contracts (events, DTOs, APIs).
D. Persisting the aggregate as is
Sprinkling ORM decorators straight onto domain classes is the fastest way to make the domain depend on infrastructure, which is the exact opposite of what we want.
// ❌ BAD: The domain smells like a database
class Shelter {
@Column()
public id: string;
@OneToMany(() => Survivor)
public survivors: Survivor[];
}
If tomorrow you switch ORMs, or decide to store survivors in a MongoDB collection instead of a SQL table, you have to touch the domain. And testing the domain means spinning up the database.
Solution: the aggregate stays pure. The repository (in infrastructure) knows how to map between the aggregate's state and what the database needs. In the next installment we'll see exactly how to do that mapping without giving up that purity, with the Snapshot pattern.
E. DDD in simple CRUD apps
Throwing the whole arsenal (aggregates, bounded contexts, events, sagas) at an app that basically creates, reads, updates and deletes records is a mistake with immediate and lasting consequences. The team takes twice as long to ship anything, the code is ten times more complex than it needs to be, and people learn to hate DDD forever.
If your system is a form hooked up to a database with no complex business rules, a well-built CRUD is the right answer. DDD shines when there's domain complexity, not technical complexity.
3. Tests: test behavior, not implementation
Here's one of the quiet payoffs of getting everything above right: a pure domain is remarkably easy to test.
Think of it as the drill the shelter doctor runs before the next horde arrives. He doesn't wait for the zombies to get in to find out whether the quarantine system works. He tests it under controlled conditions, with no pressure, and if something fails he fixes it before it's too late. That's what domain unit tests are: controlled conditions, no database, no external services, no excuses.

Test invariants, not persistence details
Invariants (the rules that can never be broken) are the heart of your tests. It doesn't matter whether you use SQL or a mud-caked notebook. That's for the integration tests to worry about. In the domain, test that the business rules hold.
import { describe, test, expect } from "vitest"; // or jest, or whatever you use
describe("Shelter - Capacity management", () => {
test("should admit survivors if there's room", () => {
// Arrange
const shelter = new Shelter("shelter-1", 3);
const survivor = new Survivor("1", "Ana", 100);
// Act
shelter.admit(survivor);
// Assert
expect(shelter.getSurvivors()).toHaveLength(1);
expect(shelter.getSurvivors()[0].name).toBe("Ana");
});
test("should reject admission if the shelter is full", () => {
// Arrange
const shelter = new Shelter("shelter-1", 2);
shelter.admit(new Survivor("1", "Ana", 100));
shelter.admit(new Survivor("2", "Borja", 100));
// Act & Assert: the invariant has to protect us
expect(() => {
shelter.admit(new Survivor("3", "Carmen", 100));
}).toThrow("Shelter full: we can't admit any more survivors");
});
test("should consolidate supplies of the same type", () => {
// Arrange
const shelter = new Shelter("shelter-1", 5);
// Act
shelter.receiveSupplies(new Supply("bandages", 10));
shelter.receiveSupplies(new Supply("antibiotics", 5));
shelter.receiveSupplies(new Supply("bandages", 7)); // Same type as the first one
// Assert
const supplies = shelter.getSupplies();
expect(supplies).toHaveLength(2); // Not 3: the bandages were consolidated
const bandages = supplies.find(s => s.name === "bandages");
expect(bandages?.amount).toBe(17); // 10 + 7
});
});
describe("InfectionSpreadService - Risk calculation", () => {
const service = new InfectionSpreadService();
test("should calculate high risk at short distance and long exposure", () => {
const risk = service.chanceOfInfection(2, 120);
expect(risk).toBeGreaterThan(0.8); // Over 80% risk: Luis is a goner
});
test("should calculate zero risk outside the infection range", () => {
const risk = service.chanceOfInfection(25, 30);
expect(risk).toBe(0); // No danger at 25 meters
});
});
Why test the pure domain
- Fast tests: no database, no external APIs. Pure unit tests that run in milliseconds.
- Clear tests: each test checks one specific business rule. If it fails, you know exactly which invariant broke.
- Safe refactoring: you can change the aggregate's internals without touching the tests, as long as the invariants hold.
- Living documentation: anyone reading the tests can see what the domain allows and what it doesn't.
Repository tests (integration)
For repositories you do need integration tests, because they talk to real infrastructure:
describe("PostgreSQLShelterRepository - Integration", () => {
test("should persist and retrieve a shelter with its survivors", async () => {
const repo = new PostgreSQLShelterRepository(db);
const shelter = new Shelter("shelter-test", 10);
shelter.admit(new Survivor("1", "Ana", 100));
await repo.save(shelter);
const retrieved = await repo.findById("shelter-test");
expect(retrieved).not.toBeNull();
expect(retrieved?.getSurvivors()).toHaveLength(1);
});
});
These tests are slower and need database setup and teardown, so you write fewer of them. The usual strategy is lots of pure domain tests (fast, no dependencies) and a handful of integration tests (slow, real infrastructure).
You don't always need to spin up the production database for these tests. You can use an in-memory version (SQLite in-memory, embedded databases like H2 in Java) or a stub repository that keeps aggregates in a plain Map. It's like rehearsing the evacuation plan on a scale model of the shelter instead of the real thing: faster, safer, and if something goes wrong nobody gets left behind.
What else is worth testing
The pure domain and the repositories aren't the only things that deserve attention:
Application layer handlers: they don't check business rules (the domain tests already do that). They check that the orchestration is right: the handler loads the aggregate, calls the right method and persists the result. The repository gets replaced with a mock.
Domain services: you test them just like aggregates, with no external dependencies. The InfectionSpreadService from the example above is a typical case: known inputs, expected output, no database or network involved.
Sagas: these are the hardest to test because they involve sequences of events and compensations. What you want to check is that the Saga reacts to each event with the right command, and that it emits the right compensation when something fails. You test them by sending events straight to the Saga and checking which commands come out.
End-to-end tests: the full flow. In a web app, for example, that goes from the HTTP request all the way to the database. They're the slowest and the fewest, but they give you the final confidence that the whole system fits together. The equivalent of a full-scale drill with every shelter and every route active.
We could add examples and go deeper here, but it would practically take a whole article. If you're interested, though, leave a comment on LinkedIn and we'll get to it.
To be continued
In this third part we saw how to keep things consistent when one transaction isn't enough, with Sagas coordinating distributed operations through events and compensations. We went over the most dangerous antipatterns: the anemic model that drains the logic out of the domain, giant aggregates that cram everything in, and bounded contexts that are just folders with fancy names. And we saw how to test the pure domain without spinning up any database.
In the next installment we'll tackle the three problems that show up when you try to take this design to production: how to make sure domain events get delivered even if the system fails halfway through, why modifying two aggregates in the same transaction will cause you trouble at scale, and what happens when the domain data is truly private and the repository needs to store it without breaking that privacy. After that, we'll see the whole system running end to end, with a checklist to tell whether you're really doing DDD or just organizing folders.
Other articles in the series
- Part 1: Ubiquitous language, bounded contexts, entities, value objects and aggregates.
- Part 2: Domain services, repositories, the application layer and domain events.
- 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 11, “Sagas”: the Saga that survives restarts, stuck Sagas and choreography.
- Chapter 12, “Antipatterns and common mistakes”: including going all-in on DDD at once: the day-zero mistake.
- Chapter 13, “Tests”: code samples for every kind of test, contract tests between contexts included.