Functional Core, Imperative Shell

Lesson 8 of the DDD course · Where I/O lives, repositories as parsers, one honest request handler · ~30 minutes

1 · Value objects 2 · Entities & identity 3 · Aggregates 4 · Lifecycle state machines 5 · Domain events 6 · Bounded contexts 7 · Context mapping 8 · Functional core 9 · Capstone
Why this matters for your mission Everything so far is pure — but orders must survive restarts and payments must hit real providers. This lesson draws the one architectural line of your product: pure business logic inside, all I/O at the rim — so the system stays testable as it grows.

Lessons 1–7 built a domain core that never touches a database, a clock, or a network. Today we wrap it in the thinnest possible layer of messy reality.

1 · The line

Gary Bernhardt's formulation — functional core, imperative shell — is the architecture this whole course has been walking toward: the core is pure functions over immutable values; the shell is a thin imperative layer that fetches input, calls the core, and performs the effects.[Bernhardt]

Core (src/core/)Shell (src/shell/)
Containstypes, transitions, events — lessons 1–5HTTP handlers, repositories, ACLs, clocks, queues
Issynchronous, deterministic, totalasync, effectful, thin
Tests needplain inputs and outputsa running world (few, coarse tests)
The decision rule When you don't know where code goes: does it decide (business rules) or do (talk to the world)? Deciding goes in the core; doing goes in the shell. If a shell file starts deciding, move the decision inward. If the core starts doing, inject the data as a parameter instead.

2 · The database is just another untrusted boundary

The insight that makes this click: you already learned to treat HTTP bodies as untrusted input that must be parsed into domain types (Lesson 1). A database row is exactly the same kind of stranger. It was written by old code, old schemas, or an old teammate. Parsing on load isn't paranoia — it's the same rule, one more boundary:

// src/shell/order-repo.ts
interface OrderRow { id: string; status: string; total_cents: number; email: string }

export function rowToOrder(row: OrderRow): Result<Order, RepoError> {
  // parse every field; one bad column = typed error, never a corrupted aggregate
}

export async function loadOrder(id: OrderId): Promise<Result<Order, RepoError>> {
  const row = await db.one("select * from orders where id = $1", [id]);
  return row ? rowToOrder(row) : { ok: false, error: "order not found" };
}

export async function saveOrder(o: Order): Promise<void> {
  await db.none("insert into orders … on conflict (id) do update …", [orderToRow(o)]);
}

Notice there's no repository class, no interface-with-one-implementation ceremony — the functional repository is a module of functions: loadOrder, saveOrder, and the pair of pure translators rowToOrder / orderToRow. The aggregate never learns SQL; the SQL never learns the aggregate.

3 · One honest request handler

Here is Meridian's POST /orders/:id/place, complete. Read it as a pipeline — parse, load, decide, save, announce, respond:

// src/shell/place-order-handler.ts — the shell; every effect lives here
export async function handlePlaceOrder(req: Request): Promise<Response> {
  const body   = parsePlaceBody(req.body);      // parse → Result<PlaceBody>
  if (!body.ok) return badRequest(body.error);

  const loaded = await loadOrder(body.value.orderId);
  if (!loaded.ok) return notFound();

  const placed = place(loaded.value, body.value.payment);   // ← the core, pure
  if (!placed.ok) return unprocessable(placed.error);

  await saveOrder(placed.value.placed);
  dispatch(placed.value.events);                             // Lesson 5's events
  return ok(placed.value.placed);
}

Every hard-won pattern shows up as one line: parse the body (L1), load an entity (L2), call the aggregate transition (L3–L4), collect events (L5), persist and dispatch (today). The handler contains zero business rules — it's a composition, which is why it stays readable as the product grows. Swap Postgres for a different store and this file changes on exactly one line.

Gotchas (1) Clocks and randomness are effects: read time in the shell, pass it in — place(draft, payment, now). (2) If a transition wants to await, it's a design smell — the core stays synchronous; put the async step in the shell around it. (3) Don't let “just one small query” into the core; queries are data before the call, never during.

4 · Practice: parse the database row

5 · Retrieval check

6 · Where this goes next

Every piece is now on the board. Next lesson is the capstone: the whole Meridian checkout assembled end-to-end — and a checklist for running the same play on your own product.

Your teacher is the agent The classic failure here is a core function that secretly wants the database “just to check one thing”. If you suspect one of yours, describe it to me — deciding vs. doing is a line you learn to see fastest with a second pair of eyes.
Primary source for this lesson Watch Gary Bernhardt's “Boundaries” (SCNA 2012, ~35 min) — the talk that named this architecture. Pair it with King's “Parse, don't validate” for why the repository parses.
← Lesson 7: Context mapping Patterns cheat sheet →