JAFSJosé Antonio Fuentes Santiago

DDD in a Zombie Apocalypse. Part 4

2026-03-22 · [ leer en español ]

In the last three parts we laid the shelter's foundations: the ubiquitous language and bounded contexts that get everyone speaking the same language, the domain services, repositories, application layer and domain events that connect the core to the outside world, and the Sagas, antipatterns and tests that keep things consistent when they get messy.

On the night of day 94 we found out the hard way whether any of it had actually helped. A bigger horde than usual forced an emergency evacuation from Shelter 3 to Shelter 7. The system processed the orders and the records looked right, but the Medical context never got the alerts: three survivors with open wounds spent the night without a medical check. By morning, one of them had infected his bunkmate, and the whole ward had to be sealed off to contain the outbreak. The code was correct. The infrastructure wasn't.

There are three places where almost every team crashes when they take DDD to production. This article is about those three places, about building the defenses a drill never asks for but a horde attack does, and about watching the whole system run from start to finish.

Operations center with several monitors showing the status of the shelters (labels in Spanish)

1. The dual-write problem and the Outbox pattern

In part two we published events like this, right after saving the aggregate:

async handle(cmd: AdmitSurvivorCommand): Promise<void> {
  const shelter = await this.shelterRepo.findById(cmd.shelterId);
  shelter.admit(cmd.survivor);
  await this.shelterRepo.save(shelter);      // ← DB transaction committed

  await this.eventBus.publish({              // ← if the system fails here...
    type: "SurvivorAdmitted",
    shelterId: shelter.id,
    survivorId: cmd.survivor.id,
    timestamp: new Date().toISOString()
  });
}

And we left a footnote with a very short mention of the Outbox pattern. What happened on the night of day 94 was that footnote coming true.

The problem: two pieces of infrastructure, zero atomicity

The code above tries to do two things in two different pieces of infrastructure. The relational database and the message bus (Kafka, RabbitMQ or messages over walkie-talkie) are two independent systems. Nothing guarantees that both operations succeed or fail together.

If the network hits a one-millisecond latency spike between the save and the publish, or the process dies right at that moment, the shelter has the survivor inside but the medical team never hears about it. The wounded guy is in the compound, bleeding on his bunk, and nobody's coming to treat him because the system as a whole is out of sync. That's exactly what happened on the night of day 94, times three.

This is the dual-write problem: any attempt to coordinate two writes in different systems without an explicit guarantee is exposed to this kind of silent failure.

The fix: the Outbox pattern

The idea is simple: instead of publishing the event straight to the bus, we store it in a table in the same database, along with the aggregate's state, inside the same SQL transaction. Either both get saved or neither does.

// outbox_events table in the database
// id | event_type | payload (JSON) | created_at | processed_at (null = pending)

async handle(cmd: AdmitSurvivorCommand): Promise<void> {
  await this.uow.run(async () => {
    // We load inside the unit of work to avoid dirty reads
    const shelter = await this.uow.shelters.findById(cmd.shelterId);
    shelter.admit(cmd.survivor);

    // 1. Save the aggregate's state
    await this.uow.shelters.save(shelter);

    // 2. Save the pending event in the same unit of work
    await this.uow.outbox.save({
      event_type: "SurvivorAdmitted",
      payload: JSON.stringify({
        shelterId: shelter.id,
        survivorId: cmd.survivor.id,
        timestamp: new Date().toISOString()
      })
    });
    // If anything fails here, the Unit of Work rolls back both writes
  });
}

NOTE FROM THE CABIN

That this.uow is the Unit of Work pattern, an application-layer abstraction that groups several operations into one atomic unit. The handler gets it through dependency injection and only knows that uow.run() guarantees that either everything is persisted or nothing is. The concrete implementation (the one that opens the SQL transaction, knows about Knex or Postgres and passes the context to each repository) lives in infrastructure. That way the use case follows the dependency rule: it depends on abstractions, not on database details.

You can read more about it in Martin Fowler's excellent Patterns of Enterprise Application Architecture.

The aggregate's state and the event are now tied together atomically. Next we need something to publish those pending events.

The worker: from the table to the bus

A background process reads the outbox_events table every so often and publishes the pending events to the bus:

export class OutboxWorker {
  constructor(
    private readonly eventBus: EventBus
  ) {}

  async processPendingEvents(): Promise<void> {
    const pending = await db("outbox_events")
      .whereNull("processed_at")
      .orderBy("created_at", "asc")
      .limit(10);

    for (const record of pending) {
      // Publish to the message bus
      await this.eventBus.publish(JSON.parse(record.payload));

      // Only once the bus confirms receipt do we mark it as processed
      await db("outbox_events")
        .where("id", record.id)
        .update({ processed_at: new Date() });
    }
  }
}

This method runs every few seconds through cron, a setInterval or whatever scheduled-task mechanism your stack uses.

Think of it this way: the outbox_events table is the paper logbook in the shelter's radio room. When the guard admits a survivor, he writes the entry in the main register and, in the same motion, jots the pending message in that logbook. Both happen together or neither does. The worker is the radio operator who checks the logbook every few minutes, sends the pending messages over the radio (the message bus) and crosses them out only after the recipient confirms they got them. If the power goes out mid-transmission, the logbook is still there: the next operator on shift finds the message not crossed out and sends it again. The blackout doesn't take the alert with it.

Diagram of the Outbox pattern (labels in Spanish)

At-least-once delivery and idempotency

The radio operator sends the message, the guard at the destination shelter confirms he got it, but the operator passes out before crossing it off the logbook. When the next shift starts, the message is still there and goes out again.

In code terms: the worker publishes the event, the bus receives it and confirms, but the worker dies just before running the UPDATE processed_at. When it restarts, it sees that event still pending and sends it again.

This is called at-least-once delivery: the system guarantees the event arrives, but not that it arrives exactly once. The direct consequence is that consumers must be idempotent: they have to be able to receive the same event more than once without duplicate side effects.

// The Medical service listens for admissions
eventBus.on("SurvivorAdmitted", async (event) => {
  // Check whether we already scheduled a checkup for this survivor
  const alreadyScheduled = await medicalRepo.hasCheckupFor(event.survivorId);
  if (alreadyScheduled) return; // Ignore the duplicate, no error, no effect

  await medicalService.scheduleCheckup(event.survivorId);
});

If the doctor already has survivor 42's checkup on the schedule and gets the alert a second time, he just ignores it. Nobody gets two beds. This property isn't optional in a system that uses the Outbox pattern: it's a design requirement every event consumer has to meet.

Idempotency in command handlers

The people listening to the radio aren't the only ones who need idempotency. The guard at the gate can also get the same order twice: the signal from headquarters cut out and the operator sent it again just in case. Without protection, he'd admit the same survivor twice.

Handlers themselves should be able to receive the same command twice without duplicate effects, which is common when there are network retries or clients that resend requests. The fix is to include a unique commandId in every command and record the processed ones inside the same transaction:

async handle(cmd: AdmitSurvivorCommand): Promise<void> {
  await this.uow.run(async () => {
    // Check whether this command was already processed
    const alreadyProcessed = await this.uow.processedCommands.findById(cmd.commandId);
    if (alreadyProcessed) return;

    const shelter = await this.uow.shelters.findById(cmd.shelterId);
    if (!shelter) throw new Error("Shelter not found");

    shelter.admit(cmd.survivor);
    await this.uow.shelters.save(shelter);

    await this.uow.outbox.save({ /* ... */ });

    // Record the commandId so we can spot future duplicates
    await this.uow.processedCommands.save({
      command_id: cmd.commandId,
      processed_at: new Date()
    });
  });
}

Back at the shelter, that unique ID is the guard's checklist: he writes down the headquarters order number when he handles the signal. If the number's already on the list, he ignores the message and keeps the gate shut. The signal can arrive twice; the gate only opens once.

FURTHER READING

Dual writes, idempotency and at-least-once delivery are covered in depth in Designing Data-Intensive Applications by Martin Kleppmann, probably the best book on modern distributed systems out there.

A word about 2PC

After the night of day 94, someone on the crisis committee proposed a different fix: headquarters would act as a central coordinator and require confirmation from every shelter before treating any operation as valid. First it would ask each shelter "are you ready to commit?" (phase 1), and only when they all said yes would it send the final order to commit (phase 2). Total guarantee, in theory.

The problem is that while each shelter waits for the final confirmation, its resources are locked: nobody gets in or out until the coordinator closes the loop. And if headquarters goes down between the two phases (a power cut, a sniper, a zombie in the generator room), every shelter is frozen indefinitely, waiting for an order that never comes. What was a coordination point becomes a single point of failure. On top of that, not every shelter speaks the same radio protocol, and requiring all of them to support it is an operational constraint nobody can guarantee in the middle of the apocalypse.

What we just described is the Two-Phase Commit protocol (2PC). In theory it solves the dual-write problem. In practice you've turned a coordination point into a single point of failure, added latency to every operation and required every system to support the protocol. In high-availability systems the cost almost always outweighs the benefit. The Outbox pattern with idempotent consumers covers the vast majority of cases with much less operational complexity. Save 2PC for truly exceptional scenarios where you can afford the operational cost and atomicity is strictly non-negotiable.

Ordering and concurrency

When dozens of groups are sending radio alerts at the same time, messages can arrive in a different order than they were sent. A departure alert that shows up after the arrival alert can make the system think the survivor came in before he left.

In highly concurrent systems, an earlier event can arrive after a later one. Adding a version or sequence number to the aggregate's events lets the Saga detect out-of-order events and reject them (or queue them). To keep two parallel instances of the same Saga from advancing the same state at once, the Saga's record has to be protected with pessimistic locking or a uniqueness constraint in the database, so two processes can't modify the same state at the same time.

2. A survivor in the wasteland: eventual consistency between aggregates

In part two we introduced SurvivorTransferService as the way to transfer a survivor between two shelters. Let's take a critical look at it. In fact, this was the very service that bit us on the night of day 94: with four survivors heading to Shelter 7 in parallel, the writes stepped on each other and two transfers ended up in an inconsistent state. The system thought those survivors were still in Shelter 3, which had already been sealed. Nobody knew where they were for hours.

// From part 2: modifies TWO aggregates in the same flow
export class SurvivorTransferService {
  public transfer(
    survivor: Survivor,
    fromShelter: Shelter,
    toShelter: Shelter
  ): void {
    if (survivor.isInfected()) throw new DomainError("...");
    if (!toShelter.hasCapacity()) throw new DomainError("...");
    if (survivor.isSpecialist() && fromShelter.wouldBeUnsafeWithout(survivor)) {
      throw new DomainError("...");
    }

    fromShelter.removeSurvivor(survivor.id);
    toShelter.admit(survivor);
    // Whoever calls this saves both shelters. Two aggregates. One transaction.
  }
}

The business logic is fine. The problem is what happens at scale: picture dozens of shelters sending survivors to the same well-stocked central shelter. Every transfer locks two database rows at once, the source shelter's and the destination's. With enough concurrency, you get an avalanche of cascading locks that can freeze the system at the worst possible moment.

It also breaks DDD's golden rule: one aggregate, one transaction. Aggregates define consistency boundaries that, by design, should be independent of each other.

The fix: let the survivor walk

The physical version of what we want looks like this: the source shelter opens its gates, the survivor walks out into the wasteland, the gates close and the guard logs his departure. The destination shelter doesn't know anything yet. Hours later, the survivor shows up and bangs on the door. Only then does the destination shelter decide, with its own current rules, whether there's room.

Each shelter only locks its own row. Never both at once.

Step 1: the initial command only touches the source shelter.

// New method on Shelter: handles the departure and returns the survivor
public transferOut(survivorId: string): Survivor {
  const survivor = this.survivors.find(s => s.id === survivorId);
  if (!survivor) {
    throw new DomainError(`Survivor ${survivorId} not found`);
  }
  if (survivor.isInfected()) {
    throw new DomainError("An infected survivor can't be transferred");
  }
  this.survivors = this.survivors.filter(s => s.id !== survivorId);
  this.currentCount--;
  return survivor;
}

// Handler: one transaction, one aggregate
export class InitiateTransferHandler {
  async handle(cmd: InitiateTransferCommand): Promise<void> {
    await db.transaction(async (trx) => {
      const fromShelter = await this.shelterRepo.findById(cmd.fromShelterId, trx);

      // The source shelter applies its rules and hands back the survivor
      const survivor = fromShelter.transferOut(cmd.survivorId);
      await this.shelterRepo.save(fromShelter, trx);

      // The survivor is "in transit": we serialize him into the event
      await trx("outbox_events").insert({
        id: crypto.randomUUID(),
        event_type: "SurvivorTransferInitiated",
        payload: JSON.stringify({
          survivorId: cmd.survivorId,
          fromShelterId: cmd.fromShelterId,
          toShelterId: cmd.toShelterId,
          survivorSnapshot: survivor.toSnapshot()  // More on this in section 3
        }),
        created_at: new Date(),
        processed_at: null
      });
    });
    // The transaction ends here. The destination shelter doesn't know anything yet.
  }
}

Step 2: the destination shelter reacts on its own when it receives the event.

eventBus.on("SurvivorTransferInitiated", async (event) => {
  await db.transaction(async (trx) => {
    const toShelter = await shelterRepo.findById(event.toShelterId, trx);
    const survivor = Survivor.reconstitute(event.survivorSnapshot);

    try {
      // The destination applies its own rules right now
      toShelter.admit(survivor);
      await shelterRepo.save(toShelter, trx);

      await trx("outbox_events").insert({
        id: crypto.randomUUID(),
        event_type: "SurvivorTransferCompleted",
        payload: JSON.stringify({
          survivorId: event.survivorId,
          shelterId: event.toShelterId
        }),
        created_at: new Date(),
        processed_at: null
      });
    } catch (error) {
      // The destination can't admit him: we emit the rejection
      await trx("outbox_events").insert({
        id: crypto.randomUUID(),
        event_type: "SurvivorAdmissionRejected",
        payload: JSON.stringify({
          survivorId: event.survivorId,
          fromShelterId: event.fromShelterId,
          toShelterId: event.toShelterId,
          survivorSnapshot: event.survivorSnapshot,
          reason: error.message
        }),
        created_at: new Date(),
        processed_at: null
      });
    }
  });
});
sequenceDiagram
    actor G as Guard
    participant O as Source shelter
    participant DB as Database
    participant W as OutboxWorker
    participant D as Destination shelter

    G->>O: InitiateTransferCommand
    rect rgb(20, 40, 20)
        note over O,DB: Transaction 1: source only
        O->>O: transferOut(survivorId)
        O->>DB: save(fromShelter)
        O->>DB: outbox ← SurvivorTransferInitiated
    end

    W->>DB: reads pending events
    W->>D: publishes SurvivorTransferInitiated

    alt Destination has capacity
        rect rgb(20, 20, 40)
            note over D,DB: Transaction 2: destination only
            D->>D: admit(survivor)
            D->>DB: save(toShelter)
            D->>DB: outbox ← SurvivorTransferCompleted
        end
    else Destination is full
        rect rgb(40, 20, 20)
            note over D,DB: Transaction 2: compensation
            D->>DB: outbox ← SurvivorAdmissionRejected
        end
    end

The case we can't ignore: the nomad

Eventual consistency opens a can of worms the design has to face: what happens if the survivor walks all the way to the destination shelter and they tell him there's no room? It's not a hypothetical. It happens when a simultaneous evacuation from another shelter filled up the destination while he was on the road. He's been walking for hours and the door won't open.

The source shelter already took him off its roster. If we just try to send him back, we put him in danger, because there are zombies on the way back. Compensation isn't always possible, and the system has to model this state explicitly.

eventBus.on("SurvivorAdmissionRejected", async (event) => {
  // Option 1: redirect to another shelter with capacity
  const alternative = await shelterRepo.findWithCapacity();
  if (alternative) {
    await outboxRepo.insert({
      event_type: "SurvivorTransferInitiated",
      payload: JSON.stringify({
        ...event,
        toShelterId: alternative.id
      })
    });
    return;
  }

  // Option 2: there's no alternative. The survivor is a Nomad.
  // This isn't an error state: it's a legitimate domain concept.
  await nomadRegistry.register({
    survivorId: event.survivorId,
    survivorSnapshot: event.survivorSnapshot,
    lastKnownShelterId: event.fromShelterId,
    reason: event.reason,
    registeredAt: new Date()
  });

  await alertService.sendUrgentNotification(
    `Survivor ${event.survivorId} has nowhere to go: start rescue protocol`
  );
});

The Nomad isn't a system error or an exception state. It's a fact of the domain that eventual consistency forces us to model. In a zombie apocalypse, some people end up without a shelter. Leaving that state out of the code won't stop it from happening. It'll just happen without anyone knowing.

Persisting the Saga's state

The Saga coordinating the evacuation always knows which survivors have been transferred and which phase the process is in. But what if the server goes down halfway through the evacuation? Without persistence, the Saga loses that context when it restarts and the system is left in an unknown state: some survivors are already in shelter B, others are still in A, and nobody knows exactly how many or which ones.

The fix is to persist the Saga's state in its own table, inside the same transaction as the aggregate's changes:

// One row per running Saga instance
// saga_id | saga_type | state (JSON) | current_step | started_at | updated_at

export class EvacuationSaga {
  private survivorsTransferred: string[] = [];
  private currentStep: "initiating" | "transferring" | "completing" | "compensating" = "initiating";

  public toState(): object {
    return {
      survivorsTransferred: this.survivorsTransferred,
      currentStep: this.currentStep
    };
  }

  public static reconstitute(savedState: Record<string, unknown>): EvacuationSaga {
    const saga = new EvacuationSaga();
    saga.survivorsTransferred = savedState["survivorsTransferred"] as string[];
    saga.currentStep = savedState["currentStep"] as typeof saga.currentStep;
    return saga;
  }
}

If the server goes down while the survivors are on the road, the Saga knows exactly where it left off when it comes back: who already made it across, who didn't, and what the next step is (or which compensation to run). That's what makes Sagas the resilient mechanism for long-running operations. The logic itself is ordinary; what matters is that it survives restarts.

Tactical map showing a survivor in transit between two shelters, and a nomad in the wasteland when no shelter has room (labels in Spanish)

FURTHER READING

The Saga pattern and handling eventual consistency in microservices are covered in detail in Microservices Patterns by Chris Richardson.

3. The Snapshot pattern: persistence without giving up purity

There's a third problem that didn't cause the night of day 94, but would have shown up sooner or later: how does the repository save and load an aggregate's internal state without breaking its encapsulation?

In part two we showed the PostgreSQL repository like this:

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;
    return this.mapToAggregate(row); // ← How does this method work?
  }
}

And we left it there. That mapToAggregate hides exactly the problem we need to talk about now.

The wall: how does the repository get to the private state?

The shelter's survivors and supplies arrays are private. They have no setters. That's the right design: nobody should be able to change them from outside without going through the business methods.

But the repository needs to read that state to save it, and rebuild it to load it. Without an explicit solution, teams end up doing one of two things:

// ❌ WRONG: ORM decorators right in the domain
class Shelter {
  @Column()
  public id: string;

  @OneToMany(() => Survivor)
  public survivors: Survivor[];  // ← private... but now with a TypeORM decorator
}

// ❌ WRONG: Reflection to get around privacy
const shelter = new Shelter(row.id, row.capacity);
(shelter as any)["survivors"] = survivors.map(mapRow);

Both options wreck what we were protecting. The first one couples the domain to the ORM: if you switch from TypeORM to Prisma, or to raw PostgreSQL, or to a notebook, you have to touch your most critical business classes. The second one uses (shelter as any) to force its way past TypeScript, which is the same thing, just more honest about what it's doing.

The fix: the Snapshot pattern

The idea is that the aggregate itself exposes a flat representation of its state, purely so infrastructure can work with it. An object with no behavior and no business rules, just data:

// Snapshot interface: data only, no behavior
export interface ShelterSnapshot {
  id: string;
  capacity: number;
  currentCount: number;
  survivors: Array<{ id: string; name: string; health: number }>;
  supplies: Array<{ name: string; amount: number }>;
}

export interface SurvivorSnapshot {
  id: string;
  name: string;
  health: number;
}

The aggregate gets two new methods: one to extract its state and one to rebuild itself from a snapshot.

export class Shelter {
  private survivors: Survivor[] = [];
  private supplies: Supply[] = [];
  private currentCount = 0;

  constructor(
    public readonly id: string,
    public readonly capacity: number
  ) {}

  // ── Existing business methods ───────────────────────────────────────────────

  public admit(s: Survivor): void {
    if (this.currentCount + 1 > this.capacity) {
      throw new DomainError("Shelter full: we can't admit any more survivors");
    }
    this.survivors.push(s);
    this.currentCount++;
  }

  // ... rest of the business methods

  // ── Persistence ─────────────────────────────────────────────────────────────

  /**
   * Returns the current state as a plain object.
   * Only the repository should use it, to persist.
   */
  public toSnapshot(): ShelterSnapshot {
    return {
      id: this.id,
      capacity: this.capacity,
      currentCount: this.currentCount,
      survivors: this.survivors.map(s => s.toSnapshot()),
      supplies: this.supplies.map(s => ({ name: s.name, amount: s.amount }))
    };
  }

  /**
   * Rebuilds a Shelter from a snapshot stored in the database.
   * It does NOT apply business invariants: it's loading a historical fact, not processing a new command.
   */
  public static reconstitute(snapshot: ShelterSnapshot): Shelter {
    const shelter = new Shelter(snapshot.id, snapshot.capacity);
    shelter.currentCount = snapshot.currentCount;
    shelter.survivors = snapshot.survivors.map(s => Survivor.reconstitute(s));
    shelter.supplies = snapshot.supplies.map(s => new Supply(s.name, s.amount));
    return shelter;
  }
}

export class Survivor {
  constructor(
    public readonly id: string,
    public name: string,
    public health: number
  ) {}

  public toSnapshot(): SurvivorSnapshot {
    return { id: this.id, name: this.name, health: this.health };
  }

  public static reconstitute(snapshot: SurvivorSnapshot): Survivor {
    return new Survivor(snapshot.id, snapshot.name, snapshot.health);
  }
}

Why reconstitute skips the invariants: the time trap

This is the deepest lesson in this section, so let's get it straight before moving on: there's a fundamental difference between acting in the present and reading the past.

Picture the sealed files in the bunker's archive. The September 15 entry says: "100 survivors admitted, shelter at capacity." When the guard opens that folder today, he doesn't check whether the shelter has enough oxygen for 100 people. Why would he? That already happened, and it was valid at the time. Reading the file doesn't trigger any of today's rules. It just brings back the memory of what was.

reconstitute works exactly like that. It doesn't process a new command: it rebuilds a state that already existed and was correct when it was saved. Business invariants apply to new commands, not to history.

Say that on day 40, with the information available back then, the business rule set a shelter's maximum capacity at 100 people. The shelter filled up with 100 survivors and that state was saved to the database.

On day 80, the ventilation system in the north sector collapsed, which forced the maximum capacity down to 50 people and the code to be updated to match.

If the repository tried to rebuild the shelter by running all 100 survivors through admit() one by one, the system would throw an exception at survivor number 51 and fall over. You couldn't even load the system to see who's inside.

// ❌ What the repository must NOT do:
const shelter = new Shelter(row.id, row.capacity); // capacity = 50 in the current code
for (const survivorRow of survivorRows) {
  shelter.admit(new Survivor(survivorRow.id, ...)); // ← throws at survivor 51
}

// ✅ What it should do:
const shelter = Shelter.reconstitute(snapshot); // loads directly, no validation

reconstitute doesn't validate because the data comes from your own database: these are facts that already happened and that were valid when they were saved. You're not trying to squeeze 50 more people in today. You're just waking the object up so it remembers how many people it has inside.

Invariants apply to new commands, not to history. If someone tries to admit a new survivor under the new rule of 50, admit() will rightly turn them away.

The updated repository

With toSnapshot() and reconstitute() in place, the repository stays clean and never touches the domain:

export class PostgreSQLShelterRepository implements ShelterRepository {
  async findById(id: string): Promise<Shelter | null> {
    const row = await db("shelters").where({ id }).first();
    if (!row) return null;

    const survivors = await db("survivors").where({ shelter_id: id });
    const supplies = await db("supplies").where({ shelter_id: id });

    // Rebuild from the snapshot: no ORM decorators, no reflection
    return Shelter.reconstitute({
      id: row.id,
      capacity: row.capacity,
      currentCount: row.current_count,
      survivors: survivors.map(s => ({ id: s.id, name: s.name, health: s.health })),
      supplies: supplies.map(s => ({ name: s.name, amount: s.amount }))
    });
  }

  async save(shelter: Shelter, trx?: Knex.Transaction): Promise<void> {
    const conn = trx ?? db;
    const snap = shelter.toSnapshot(); // Ask the aggregate for its picture

    await conn("shelters")
      .insert({ id: snap.id, capacity: snap.capacity, current_count: snap.currentCount })
      .onConflict("id").merge();

    // Replace the survivors: simple enough for this model
    await conn("survivors").where({ shelter_id: snap.id }).delete();
    if (snap.survivors.length > 0) {
      await conn("survivors").insert(
        snap.survivors.map(s => ({ ...s, shelter_id: snap.id }))
      );
    }

    await conn("supplies").where({ shelter_id: snap.id }).delete();
    if (snap.supplies.length > 0) {
      await conn("supplies").insert(
        snap.supplies.map(s => ({ ...s, shelter_id: snap.id }))
      );
    }
  }
}

The domain knows nothing about SQL. The infrastructure knows nothing about business rules. The boundary is exactly where it should be.

This approach is a variant of the Data Mapper pattern: instead of an external mapper that has to know the aggregate's internal structure (breaking encapsulation), the aggregate itself exposes and consumes its serializable representation through toSnapshot() and reconstitute(). The effect is the same as using explicit mapping DTOs, without coupling infrastructure to the domain. The domain doesn't know there's a SQL table; the infrastructure doesn't know which business rules the domain enforces.

Diagram of the Snapshot pattern (labels in Spanish)

FURTHER READING

The Data Mapper pattern, which Snapshot is a variant of, is documented in Patterns of Enterprise Application Architecture by Martin Fowler (the same book that covers the Unit of Work pattern mentioned earlier).

4. Putting it all together: three days in the shelter

Time for the full drill. The code is on GitHub, with three chained scenarios covering everything we've seen: admission, transfer and the Nomad case with real concurrency.

Day 95: María and Carlos arrive at Shelter 7

Shelter 7 has room for two people. AdmitSurvivorHandler handles each arrival separately: it loads the shelter from the repository (using reconstitute under the hood), calls shelter.admit() so the domain applies its rules, persists the new state (using toSnapshot) and leaves the SurvivorAdmitted event in the outbox. The worker publishes it, Medical schedules the checkups and Logistics updates the rations. The shelter is now full.

AdmitSurvivorHandler → [Domain] admit() → [Repo] toSnapshot → [Outbox] SurvivorAdmitted
OutboxWorker → Medical schedules checkup · Logistics updates rations

Day 96: Carlos moves to Shelter 8

Shelter 7 is full and Carlos needs to move. InitiateTransferHandler only touches the source shelter: it takes Carlos out with transferOut(), saves the updated state and emits SurvivorTransferInitiated with Carlos's snapshot serialized inside. One transaction, one aggregate. The worker processes the event: TransferEventHandlers loads Shelter 8, applies its own rules and admits Carlos. Shelter 8: full.

InitiateTransferHandler → [Domain] transferOut() → [Outbox] SurvivorTransferInitiated
OutboxWorker → TransferEventHandlers → [Domain] admit() at destination → SurvivorTransferCompleted

Day 97: Pedro becomes a Nomad

Pedro takes the spot Carlos left in Shelter 7 (so the shelter is full again), and then his transfer to Shelter 8 starts. At that point Pedro's event is sitting in the outbox, waiting to be processed. Before the worker gets to it, Ana arrives and takes the spot Pedro just freed up in Shelter 7. When the worker finally processes the transfer, Shelter 8 is full, and so is Shelter 7. There's no alternative. Pedro is a Nomad and his record shows up in data/nomads/.

This third scenario isn't made up. It's exactly what happens when eventual consistency and concurrency cross paths: the system can't guarantee the destination will still be available between the moment the transfer order goes out and the moment it runs. Adding more locks won't fix it (that sends us right back to the problem in section 2). What does fix it is modeling the Nomad for what it is: a fact of the domain with its own state, its own alert and its own rescue protocol.

InitiateTransferHandler → [Outbox] SurvivorTransferInitiated (Pedro in transit)
[Concurrency] Ana admitted → Shelter 7 full
OutboxWorker → Shelter 8 full → SurvivorAdmissionRejected
             → no alternative → Pedro registered in data/nomads/

5. The shelter holds

Four articles later, the system has gone from a user.status = 2 to a domain that speaks the language of the apocalypse, protects its invariants, coordinates several contexts without coupling them to each other and persists its state without giving up its purity.

But the most important lesson isn't technical. DDD is, above all, an ongoing conversation with the domain. The tools (bounded contexts, aggregates, repositories, Outbox, Snapshots) come from listening carefully to that domain and modeling what you find, including the awkward states, like the nomad survivor a comfortable system would rather ignore.

A well-modeled domain isn't one without edge cases. It's one that names them, handles them and turns them into code anyone on the team can read without opening the docs.

Keep the gates shut and the code clean.

In the next and final installment we'll wrap up the series with a frequently asked questions article, a quick DDD checklist to keep handy and, maybe most important of all, an honest guide to when DDD is worth it and when it isn't. Because not every apocalypse needs a rich domain.

Other articles in the series

  • Part 1: Ubiquitous language, bounded contexts, entities, value objects and aggregates.
  • Part 2: Domain services, repositories, application layer and domain events.
  • Part 3: Sagas, antipatterns and tests.
  • FAQ: Frequently asked questions.
THIS CONTINUES IN THE SHELTER

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 7, “Repositories”: the Snapshot pattern, CQRS and several persistence technologies in the same context.
  • Chapter 9, “Domain events”: the Outbox pattern, at-least-once delivery and idempotent consumers.
  • Chapter 11, “Sagas”: what to do when there's no going back, stuck Sagas and choreography.