Software Architecture

Domain-Driven Design: Repositories for persisting Aggregates without coupling the domain

Design a storage-independent OrderRepository and compare it with a DAO, an ORM, and an Application Service. Implement in-memory and SQLite adapters, retrieve complete Aggregates, and check saving, version conflicts, and rollback with executable tests.

Updated on October 29, 2026

Content explored 0%
18px

The indicator keeps the furthest percentage explored; marking the article complete is your choice.

An order is confirmed correctly in memory. The backend updates its header and then saves the lines, but the second operation fails. The next read finds a confirmed order with old or incomplete data.

In another flow, a service retrieves an ORM model directly and modifies its properties. The rest of the application needs to know that tool's relationships, sessions, and particular methods to work with the order.

A Repository aims to offer a way to retrieve and persist Domain objects without requiring its consumers to know those mechanisms. For the separation to be useful, the contract must also explain what it saves, what it returns, and what happens when a conflict exists.

What a Repository represents in DDD

A Repository provides access to Domain objects through a collection-like interface, hiding mapping and storage access. Fowler describes this mediation in his Repository pattern, and Evans develops it in his DDD reference.

In a model with Aggregates, it is normally designed around their Aggregate Roots: the entry points that control modifications to the group. OrderRepository retrieves an Order ready to execute its operations, not a header without the lines needed to check its rules.

This does not mean loading all data related to a sale. The order can retain references to customer and product by identity without reconstructing their complete profiles.

The contract can be defined in Domain or at the application boundary that needs it, depending on the chosen organization. The concrete implementation belongs to Infrastructure. What matters is that the consumer depends on its own abstraction, not on an ORM session, connection, or type.

Repository, DAO, ORM, and Application Service

A DAO, or Data Access Object, abstracts mechanisms for accessing a data source. Oracle's original definition does not necessarily limit it to a table. The useful distinction is the contract: in DDD, the Repository is expressed in objects and needs of the model, while a DAO may offer operations centered on records or queries.

An ORM, or Object-Relational Mapper, is a tool for mapping between objects and relational storage. It can be used inside a Repository. It does not automatically replace contract design or guarantee that retrieved objects match your Aggregates.

An Application Service coordinates a Use Case. For example: retrieve the order, ask it to confirm itself, and save. The confirmation rule belongs to the model; the SQL query belongs to the adapter. The Repository should not calculate discounts or decide which orders deserve approval.

The separation is visible in this flow:

ConfirmOrder -> OrderRepository [contract]
                    ^
                    | implemented by
             MemoryOrderRepository
             SqliteOrderRepository

Both retrieve Order; Order knows neither SQL nor SQLite.

A small contract with explicit guarantees

We will use three operations: add, to insert a new Aggregate; findById, to retrieve an existing one; and save, to save an update conditional on the version read.

We will not create an ambiguous save that inserts or updates without distinguishing intent. In this example, a duplicate identifier when adding is an error; saving a stale version is too. A technical failure is not translated into “order does not exist.”

The version travels alongside the Aggregate as persistence metadata. It is neither a SQL column exposed to Domain nor a business rule of the order: it is a number the contract uses to detect incompatible updates. Another design might use an equivalent opaque token.

Complete example: the same contract, two implementations

Setup and scope

The project includes all the following files and requires no package installation:

repository-example/
  package.json
  domain.ts
  application.ts
  memory-repository.ts
  sqlite-repository.ts
  repository.test.ts

Contents of package.json:

{"name":"repository-example","private":true,"type":"module"}

We will use Node.js 24.21.0 and its built-in node:sqlite module. The relational adapter uses DatabaseSync, which executes queries synchronously; the Repository interface retains asynchronous methods to represent the contract without tying it to that mechanism. This teaching implementation is not a concurrency or performance recommendation for a production server. Consult the Node.js SQLite documentation when adapting the APIs to another version.

The tests create a real SQLite database with :memory:: SQL runs and transactions are checked, but the data does not survive closing. No existing database is modified.

1. Domain and independent contract

File domain.ts:

export type OrderSnapshot = {
  id: string;
  status: 'draft' | 'confirmed';
  lines: { id: string; productId: string; quantity: number; unitPriceMinorUnits: number }[];
};

class Money {
  readonly minorUnits: number;
  constructor(minorUnits: number) {
    if (!Number.isSafeInteger(minorUnits) || minorUnits < 0) throw new Error('Importe inválido');
    this.minorUnits = minorUnits;
    Object.freeze(this);
  }
}

export class Order {
  #state: OrderSnapshot;

  private constructor(state: OrderSnapshot) {
    const validId = (value: string) => typeof value === 'string' && value.trim().length > 0;
    if (!validId(state.id) || !['draft', 'confirmed'].includes(state.status)) {
      throw new Error('Pedido inválido');
    }
    if (state.lines.length === 0) throw new Error('El pedido necesita líneas');
    const ids = new Set<string>();
    const products = new Set<string>();
    let total = 0;
    for (const line of state.lines) {
      if (!validId(line.id) || !validId(line.productId) || ids.has(line.id) ||
        products.has(line.productId) || !Number.isSafeInteger(line.quantity) || line.quantity <= 0) {
        throw new Error('Línea inválida o duplicada');
      }
      const price = new Money(line.unitPriceMinorUnits);
      total = new Money(total + new Money(price.minorUnits * line.quantity).minorUnits).minorUnits;
      ids.add(line.id);
      products.add(line.productId);
    }
    this.#state = structuredClone(state);
  }

  static start(id: string, lines: OrderSnapshot['lines']): Order {
    return new Order({ id, status: 'draft', lines });
  }

  static restore(state: OrderSnapshot): Order { return new Order(state); }

  confirm(): void {
    if (this.#state.status !== 'draft') throw new Error('Pedido ya confirmado');
    this.#state = { ...this.#state, status: 'confirmed' };
  }

  snapshot(): OrderSnapshot { return structuredClone(this.#state); }
}

export class OrderAlreadyExists extends Error {}
export class OrderWriteConflict extends Error {}

export interface OrderRepository {
  add(order: Order): Promise<number>;
  findById(id: string): Promise<{ order: Order; version: number } | null>;
  save(order: Order, expectedVersion: number): Promise<number>;
}

Prices are integer minor units of EUR and lines cannot be duplicated. The minimal model avoids repeating the complete Aggregate design. Its methods contain no SQL, connections, or persistence decorators.

restore() preserves identity and state instead of starting another order in draft. Inputs are known structures; it is not a general JSON parser. An external adapter must validate the received shape and the model checks the rules that belong to it.

2. An in-memory implementation that does not share references

File memory-repository.ts:

import {
  Order, OrderAlreadyExists, OrderWriteConflict,
  type OrderRepository, type OrderSnapshot,
} from './domain.ts';

export class MemoryOrderRepository implements OrderRepository {
  #rows = new Map<string, { state: OrderSnapshot; version: number }>();

  async add(order: Order): Promise<number> {
    const state = order.snapshot();
    if (this.#rows.has(state.id)) throw new OrderAlreadyExists('Pedido duplicado');
    this.#rows.set(state.id, { state, version: 0 });
    return 0;
  }

  async findById(id: string) {
    const row = this.#rows.get(id);
    return row ? { order: Order.restore(row.state), version: row.version } : null;
  }

  async save(order: Order, expectedVersion: number): Promise<number> {
    const state = order.snapshot();
    const current = this.#rows.get(state.id);
    if (!current || current.version !== expectedVersion) {
      throw new OrderWriteConflict('El pedido cambió o ya no existe');
    }
    const version = expectedVersion + 1;
    this.#rows.set(state.id, { state, version });
    return version;
  }
}

Saving snapshots and reconstructing instances prevents order.confirm() from silently changing storage before calling save. The comparison and replacement have no await between them; this simulation only coordinates its instance's state within one process.

3. A Use Case receives the contract

File application.ts:

import type { OrderRepository } from './domain.ts';

export class ConfirmOrder {
  #orders: OrderRepository;
  constructor(orders: OrderRepository) { this.#orders = orders; }

  async execute(orderId: string) {
    const loaded = await this.#orders.findById(orderId);
    if (!loaded) throw new Error('Pedido inexistente');
    loaded.order.confirm();
    const version = await this.#orders.save(loaded.order, loaded.version);
    return { id: orderId, status: loaded.order.snapshot().status, version };
  }
}

Passing the Repository through the constructor is simple Dependency Injection. Changing the implementation does not require modifying the Use Case. A controller could translate its results and errors to HTTP; that transport is outside the example.

4. Relational persistence and explicit mapping

File sqlite-repository.ts:

import { DatabaseSync } from 'node:sqlite';
import {
  Order, OrderAlreadyExists, OrderWriteConflict,
  type OrderRepository, type OrderSnapshot,
} from './domain.ts';

export function createDemoDatabase(): DatabaseSync {
  const db = new DatabaseSync(':memory:');
  db.exec(`
    PRAGMA foreign_keys = ON;
    CREATE TABLE orders (
      id TEXT PRIMARY KEY,
      status TEXT NOT NULL CHECK (status IN ('draft', 'confirmed')),
      version INTEGER NOT NULL CHECK (version >= 0)
    );
    CREATE TABLE order_lines (
      order_id TEXT NOT NULL REFERENCES orders(id),
      line_id TEXT NOT NULL,
      product_id TEXT NOT NULL,
      quantity INTEGER NOT NULL CHECK (quantity > 0),
      unit_price_minor INTEGER NOT NULL CHECK (unit_price_minor >= 0),
      PRIMARY KEY (order_id, line_id),
      UNIQUE (order_id, product_id)
    );
  `);
  return db;
}

type JoinedRow = {
  order_id: string;
  status: OrderSnapshot['status'];
  version: number;
  line_id: string | null;
  product_id: string;
  quantity: number;
  unit_price_minor: number;
};

export class SqliteOrderRepository implements OrderRepository {
  #db: DatabaseSync;
  constructor(db: DatabaseSync) { this.#db = db; }

  #transaction<T>(work: () => T): T {
    this.#db.exec('BEGIN IMMEDIATE');
    try {
      const result = work();
      this.#db.exec('COMMIT');
      return result;
    } catch (error) {
      this.#db.exec('ROLLBACK');
      throw error;
    }
  }

  #insertLines(state: OrderSnapshot): void {
    const insert = this.#db.prepare(`INSERT INTO order_lines
      (order_id, line_id, product_id, quantity, unit_price_minor) VALUES (?, ?, ?, ?, ?)`);
    for (const line of state.lines) {
      insert.run(state.id, line.id, line.productId, line.quantity, line.unitPriceMinorUnits);
    }
  }

  async add(order: Order): Promise<number> {
    const state = order.snapshot();
    return this.#transaction(() => {
      if (this.#db.prepare('SELECT id FROM orders WHERE id = ?').get(state.id)) {
        throw new OrderAlreadyExists('Pedido duplicado');
      }
      this.#db.prepare('INSERT INTO orders (id, status, version) VALUES (?, ?, 0)')
        .run(state.id, state.status);
      this.#insertLines(state);
      return 0;
    });
  }

  async findById(id: string) {
    const rows = this.#db.prepare(`
      SELECT o.id AS order_id, o.status, o.version,
             l.line_id, l.product_id, l.quantity, l.unit_price_minor
      FROM orders o LEFT JOIN order_lines l ON l.order_id = o.id
      WHERE o.id = ? ORDER BY l.line_id
    `).all(id) as unknown as JoinedRow[];
    if (rows.length === 0) return null;
    const first = rows[0];
    if (!Number.isSafeInteger(first.version) || first.version < 0) {
      throw new Error('Versión persistida inválida');
    }
    const state: OrderSnapshot = {
      id: first.order_id, status: first.status,
      lines: rows.filter(row => row.line_id !== null).map(row => ({
        id: row.line_id as string, productId: row.product_id,
        quantity: row.quantity, unitPriceMinorUnits: row.unit_price_minor,
      })),
    };
    return { order: Order.restore(state), version: first.version };
  }

  async save(order: Order, expectedVersion: number): Promise<number> {
    const state = order.snapshot();
    return this.#transaction(() => {
      const result = this.#db.prepare(`UPDATE orders SET status = ?, version = version + 1
        WHERE id = ? AND version = ?`).run(state.status, state.id, expectedVersion);
      if (result.changes !== 1) throw new OrderWriteConflict('El pedido cambió o ya no existe');
      // Reemplazamos solo las líneas de este pedido, dentro de la misma transacción.
      this.#db.prepare('DELETE FROM order_lines WHERE order_id = ?').run(state.id);
      this.#insertLines(state);
      return expectedVersion + 1;
    });
  }
}

The mapping translates unit_price_minor to unitPriceMinorUnits and delivers a reconstructed Aggregate. The joined query retrieves header and lines in one statement, avoiding combining two reads from different moments. The as casts describe types to TypeScript; they do not validate data by themselves. The controlled schema and the model and version checks support this example.

Line order is defined here by identifier during retrieval. If the business needs a different display order, persist and map an explicit position; do not depend on a table's accidental order.

Queries use parameters and do not concatenate received identifiers into SQL. The scoped deletion of lines is part of this demonstration's update strategy. In a model with auditing, external references, or many lines, you may need to calculate differences rather than replace them.

BEGIN IMMEDIATE, COMMIT, and ROLLBACK follow SQLite transaction rules. This connection must not already have an open transaction and is not shared for interleaved operations. Do not copy this control without adapting it to your application's client and connection management.

5. Contract and rollback tests

File repository.test.ts:

import assert from 'node:assert/strict';
import test from 'node:test';
import { Order, OrderAlreadyExists, OrderWriteConflict, type OrderRepository } from './domain.ts';
import { ConfirmOrder } from './application.ts';
import { MemoryOrderRepository } from './memory-repository.ts';
import { createDemoDatabase, SqliteOrderRepository } from './sqlite-repository.ts';

function exampleOrder() {
  return Order.start('order-1', [
    { id: 'line-1', productId: 'book', quantity: 2, unitPriceMinorUnits: 1200 },
    { id: 'line-2', productId: 'notebook', quantity: 1, unitPriceMinorUnits: 300 },
  ]);
}

const implementations: [string, () => { repository: OrderRepository; close(): void }][] = [
  ['memoria', () => ({ repository: new MemoryOrderRepository(), close() {} })],
  ['SQLite', () => {
    const db = createDemoDatabase();
    return { repository: new SqliteOrderRepository(db), close: () => db.close() };
  }],
];

for (const [name, create] of implementations) {
  test(`${name}: recuperar, guardar y detectar versiones obsoletas`, async () => {
    const { repository, close } = create();
    try {
      assert.equal(await repository.findById('missing'), null);
      const original = exampleOrder();
      assert.equal(await repository.add(original), 0);
      await assert.rejects(() => repository.add(original), OrderAlreadyExists);

      const stale = await repository.findById('order-1');
      assert.ok(stale);
      original.confirm();
      assert.equal((await repository.findById('order-1'))?.order.snapshot().status, 'draft');

      assert.deepEqual(await new ConfirmOrder(repository).execute('order-1'), {
        id: 'order-1', status: 'confirmed', version: 1,
      });
      const saved = await repository.findById('order-1');
      assert.ok(saved);
      assert.equal(saved.order.snapshot().status, 'confirmed');
      assert.deepEqual(saved.order.snapshot().lines, original.snapshot().lines);
      await assert.rejects(() => repository.save(stale.order, stale.version), OrderWriteConflict);
      assert.equal((await repository.findById('order-1'))?.version, 1);
    } finally { close(); }
  });
}

test('SQLite revierte cabecera, versión y líneas si falla la escritura de una línea', async () => {
  const db = createDemoDatabase();
  const repository = new SqliteOrderRepository(db);
  try {
    await repository.add(exampleOrder());
    // Fallo deliberado de almacenamiento para comprobar atomicidad, no una regla del negocio.
    db.exec(`CREATE TRIGGER fail_line BEFORE INSERT ON order_lines
      WHEN NEW.line_id = 'line-2'
      BEGIN SELECT RAISE(ABORT, 'simulated storage failure'); END;`);
    const loaded = await repository.findById('order-1');
    assert.ok(loaded);
    loaded.order.confirm();
    await assert.rejects(() => repository.save(loaded.order, loaded.version), /simulated/);
    const unchanged = await repository.findById('order-1');
    assert.ok(unchanged);
    assert.equal(unchanged.version, 0);
    assert.deepEqual(unchanged.order.snapshot(), exampleOrder().snapshot());
  } finally { db.close(); }
});

Run:

node --test repository.test.ts

The first tests run the same contract against two mechanisms. The Use Case confirms the order without knowing which it uses. The failure test demonstrates that an exception when inserting the second line leaves neither the header confirmed nor the version incremented.

The three tests were run and passed with Node.js 24.21.0 and the SQLite library built into that environment. No static analysis with the TypeScript compiler was performed and no other relational engine was tested.

The version test uses two logically stale reads, not concurrent load from multiple processes. It checks version-conditional rejection; it does not measure production isolation, contention, or performance.

Concurrency and Unit of Work: what saving guarantees

save(order, expectedVersion) uses Optimistic Concurrency Control: it accepts an update only if the version is still the one read. Checking and saving every component happen inside the transaction. A conflict must not become an unconditional save to “make it work.”

If you retry, retrieve the Aggregate again and execute the operation using the current state. Also check whether the Use Case can be repeated: a rejected write does not undo external effects you have already executed.

A Unit of Work records the objects affected by an operation and coordinates writing changes and concurrency issues, as defined by Fowler. It is not simply another name for BEGIN and COMMIT.

In our design, each add or save completes its own transaction. If an operation needed to coordinate more local writes, you would have to establish a common boundary and involve the adapters. It is not enough to call several save operations that commit separately, or to nest transactions the engine does not support.

Education: retrieve to decide, query to display

An academy needs to approve an enrollment and list thousands of participants. Approval requires retrieving the Aggregate with the information needed for its rules. The list can use a paginated query returning identifier, display name, and status.

Forcing EnrollmentRepository to reconstruct every enrollment to display three columns can add unnecessary work. A dedicated reader can return a DTO, a structure for transferring data, without offering modification operations.

Separating these flows does not require implementing CQRS or another complete system. This example teaches distinguishing a read intended to execute behavior from a projection intended for display.

Logistics: an external query is not persisting a local Aggregate

An integration queries a carrier's status. The HTTP adapter can validate and translate its response; calling it ShipmentRepository does not automatically turn it into a collection of your own Aggregates with the same guarantees as your database.

Define whether you need to query external evidence or retrieve a shipment your system controls. If they belong to different Bounded Contexts, keep their implementations separate and use an HTTP ACL with consumer contracts when that is the agreed integration.

A query failure is not equivalent to “shipment does not exist.” There is also no shared transaction between the HTTP call and local saving merely because both operations receive the same process identifier. Here, the decision is to name and limit the contract according to the actual guarantee it can offer.

When you do not need another generic Repository

A GenericRepository<T> class with findWhere, include, join, and ORM-specific options can preserve coupling under new names. Start with the operations your consumers need: findById, saving changes, or searching a bounded selection of orders, with criteria understandable to the model.

This does not require inventing business names for every query or duplicating the ORM's entire API. Technical details can be reused within Infrastructure without becoming the common contract for all Aggregates.

For a small CRUD catalog, validation and simple data access may suffice. If there is no Aggregate behavior to protect, adding an interface that merely forwards every call may not add enough value. Separation must reduce concrete dependencies, not satisfy a class checklist.

Prompts to guide and review AI-generated code

Design the necessary contract

Analyze the attached order Use Cases and propose an OrderRepository without ORM types or arbitrary engine queries. Distinguish insertion, retrieval, updating, and read projections. Specify absence, duplicate, and conflict. Do not implement or add operations by default. A person will validate what information the Aggregate needs and what guarantees each consumer expects.

Implement mapping and saving

Implement the existing contract in memory and in the supplied relational adapter. Return reconstructed Aggregates without sharing references. Save header and lines atomically and condition the update on the version read. Do not add business rules to the Repository or install another ORM. Provide tests for the contract, unsaved state, stale version, and failure when writing a line. A person will run the tests against the corresponding engine.

Review leaks and transactions

Review this diff for ORM types or sessions in Domain, incomplete Aggregates, technical errors treated as null, writes outside the transaction, and conflicts overwritten without reloading. Do not change files. Return evidence and an observable scenario for each finding. A person will verify connections, isolation, emitted queries, and actual constraints; do not assume a shared transaction over HTTP.

An in-memory implementation can pass tests even when SQL fails because of constraints or isolation. Use it to check behavior and retain real adapter tests for guarantees that depend on it.

Three exercises with reasoned solutions

1. Retrieve only the header

AI optimizes findById() and stops loading lines, but returns an Order that can be asked to confirm(). What would you review?

Reasoned solution: whether the object contains what it needs to check its rules. In the example model, an order requires lines; an incomplete header is not a retrieved Aggregate. It can serve as a list DTO under another contract, but must not pretend to be an Order ready to modify.

2. Retry after a conflict

The adapter gets zero updated rows and repeats the UPDATE after removing the version condition. Does it preserve the contract?

Reasoned solution: no. It overwrites a version you did not evaluate. Return the conflict and decide in Application whether to retrieve, reevaluate, and retry. Tests must check that a rejected write changes neither state nor version.

3. Pass an ORM transaction to the model

Someone proposes order.confirm(entityManager) so the Entity saves its changes. What dependency does this introduce?

Reasoned solution: it couples the Domain operation to a persistence mechanism. The Entity can check and change its state without that object; the Use Case and Repository coordinate saving. If several writes must be atomic, establish their transactional boundary outside the model and check that they share the same actual unit.

How to recognize a Repository that adds value

Check which object it retrieves, what saving it means, and what guarantees it promises for absence, failure, and concurrency. Then review that public types do not force the consumer to know connections, tables, or ORM mechanisms.

A useful Repository lets you execute Aggregate behavior and persist it through an explicit contract. This separation is demonstrated through mapping, transactions, and adapter tests, as well as an interface with good names.

Loading conversation…

Keep learning