Skip to content

Repositories: Collections of Aggregates, Not Table Gateways ​

"For each type of aggregate that needs global access, create a service that can provide the illusion of an in-memory collection of all objects of that aggregate's root type." — Eric Evans, Domain-Driven Design Reference (2015), Repositories

Summary: A repository is the door through which the application loads and saves whole aggregates, one repository per aggregate root, in the language of the domain; it hides the database, never commits a transaction, and never answers reporting questions. Focus: Evans and Fowler definitions, collection-oriented vs persistence-oriented interfaces, what belongs in a repository and what moves to read models, the Specification pattern and its limits, transactions and the unit of work, optimistic concurrency in Save, reconstitution, three Laravel strategies (Eloquent as aggregate, Eloquent mapped, query builder), Go with pgx and sqlc, fakes and shared contract tests, caching, event dispatch, and the anti-patterns. Learning goal: Design an OrderRepository for one aggregate in Go and Laravel, implement it twice (in-memory and Postgres) so one contract test passes both, wire the transaction at the application service, detect lost updates with a version column, and recognise a repository that has decayed into a DAO.

This chapter belongs to group DD 02 (Tactical Design). It assumes Aggregates & Factories (what an aggregate is and where its boundary lies) and Entities & Value Objects. It owns one question: how does the domain get an aggregate back, and hand one over for storage, without knowing about SQL? The neighbours own the rest: the general persistence debate (Active Record vs Data Mapper, Unit of Work, Identity Map) lives in Data Persistence Design; the services that call repositories are in Domain, Application & Infrastructure Services; the events a repository stores are in Domain Events vs Integration Events and the Outbox Pattern; the query side is in Data Patterns; version columns are in Optimistic vs Pessimistic Locking.

Page map ​

If you are looking forGo to
The whole chapter in four tablesEverything in one minute
Why a door is needed at allWhy repositories exist
Evans 2003, Fowler 2003, Vernon 2013Where it comes from
One per aggregate root, whole aggregates in and outWhat a repository is
Add/Remove vs Save, and which fits Go and PHPCollection-oriented vs persistence-oriented
Finders, Save, Remove, what to leave outWhat belongs in a repository
Reports, lists, paginationWhat does not belong
Composable domain queriesSpecification pattern
Who begins and commitsRepositories and transactions
Version column, compare-and-setOptimistic concurrency in Save
Rows to aggregate, private constructorsReconstitution
Eloquent as aggregate, mapped, query builderThree Laravel strategies
Fakes and shared contract testsFakes and contract tests
Cache inside a repositoryCaching
Events recorded by the aggregateEvent dispatch on save
Generic Repository<T>, DAO, leaksAnti-patterns
Running example in GoGo
Running example in LaravelLaravel
Per context and per serviceIn architecture
Hands-onLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The vocabulary. Every row is unpacked in the concept catalogue.

TermIn plain wordsTiny exampleWhat goes wrong without it
RepositoryA collection-like door to the stored aggregates of one root typeOrderRepository.Get(id) returns a whole OrderSQL and table names spread through use cases
Aggregate rootThe one entity outsiders may hold and ask forOrder, not OrderLineLines are saved behind the root's back
Collection-orientedLooks like a set: Add, Remove, no saveHibernate session, Doctrine persist + flushYou need change tracking you may not have
Persistence-orientedExplicit Save after every changeorders.Save(ctx, order)Callers forget to save
SpecificationA named, composable domain rule that can select aggregatesUnpaidLongerThan(now, 48h)Query logic duplicated in services
Unit of workThe boundary of one commit, owned by the application serviceDB::transaction(...), UnitOfWork.DoA repository commits half a use case
Optimistic concurrencyDetect a competing write with a version numberUPDATE ... WHERE version = $loadedSilent lost updates
ReconstitutionRebuilding an aggregate from stored state without running commandssales.Reconstitute(snapshot)Invalid state enters, or events fire on load
Read modelA query-only shape built for a screen or reportOrderListRow from a SQL viewLists force the aggregate to load everything

Three shapes of the same interface (compared in Collection-oriented vs persistence-oriented):

StyleMethodsWho notices a changeNatural homeCost
Collection-orientedAdd, Remove, Get, findersThe ORM's unit of work, at flushHibernate, Doctrine ORM, EF CoreNeeds an identity map and change tracking
Persistence-orientedGet, Save, Remove, findersThe caller, by calling SaveGo, Eloquent, key-value and document storesOne more call to remember
Closure-style updateUpdate(ctx, id, func(*Order) error)The repository, around your closureGo (Three Dots Labs)Closure shape hides the transaction

Where each question goes:

QuestionAnswer fromWhy
"Give me order 42 to cancel it"OrderRepository.GetA command needs the whole aggregate and its invariants
"Orders placed but unpaid for two days"Repository + specification, or a read modelDomain query; small result; each is then a command target
"Page 3 of the order list with totals"Query service / read modelNot a command; the aggregate is the wrong shape
"Revenue by customer segment"Reporting storeCross-aggregate aggregation
"Save this order and tell Billing"Save stores state + event in one transactionAtomic write, publish later (outbox)

Laravel strategies at a glance (details in Three Laravel strategies):

OptionDomain objectRepositoryBest whenHonest cost
1. Eloquent is the aggregateEloquent modelThin or noneCRUD-heavy contexts, small teamsave(), update(), mass assignment stay public
2. MappedPure PHP classMaps OrderRecord to OrderReal invariants, tests without a databaseMapping code, two classes per table
3. Query builderPure PHP classDB::table() rows mapped by handHot paths, odd schemas, bulk loadsMost code, no relation helpers

Why repositories exist ​

A domain model is useless if getting an aggregate out of the database is so painful that developers give up and write SQL in the use case. Evans names the failure: "The sheer technical complexity of applying most database access infrastructure quickly swamps the client code, which leads developers to dumb-down the domain layer, which makes the model irrelevant." The second failure is the opposite: unconstrained queries "pull specific fields from objects, breaching encapsulation, or instantiate a few specific objects from the interior of an aggregate, blindsiding the aggregate root and making it impossible for these objects to enforce the rules of the domain model."

A repository is the compromise: one narrow, domain-shaped interface through which whole aggregates travel.

Without a repositoryWith one repository per aggregate root
Use cases build SQL and know table namesUse cases call Get and Save
Any code can update order_lines directlyOnly the root is loaded and saved, so its rules run
Changing storage touches every use caseChanging storage touches one class
Unit tests need a databaseUnit tests use an in-memory repository
Queries are scattered and duplicatedDomain queries have names and one home
Good for: scripts, reportsGood for: a model with real invariants

The analogy we reuse on this page: a library desk. You do not walk the stacks. You ask the desk for "the complete set of volumes of this encyclopedia" and receive the whole set; you do not borrow volume 3 alone and swap in a page from another encyclopedia. When you return it, the desk checks it is complete. The desk knows the shelving system; you only know the encyclopedia's name. If a second reader returned the same set with different pages while you held it, the desk would refuse your return (that is the version check). Asking the desk "how many red-covered books do you have?" is a different service: a catalogue, not the lending desk (that is a read model).

Applicationservice (tx)domain layer: one aggregate = one consistency boundaryOrderRepository (interface)Get · Save · Remove · FindSatisfyingOrder (root)version, statusOrderLine ×ninternal entitiesloaded and saved whole, always through the rootPostgres / Eloquentimplementation (infrastructure)ordersorder_linesoutboxone transactionno OrderLineRepositorylines have no door of their owndirect line writes

The picture shows the repository interface sitting inside the domain layer, the implementation outside it, and the aggregate crossing the line whole. Lines have no door of their own.

Three common misunderstandings, up front ​

  1. "A repository is a wrapper around an ORM or a table." A repository is a wrapper around an aggregate. One table may serve three aggregates, and one aggregate may span four tables.
  2. "Repositories exist so we can swap the database." That is a pleasant side effect. The point is to keep persistence out of the model and to give invariants a single entry. Three Dots Labs says it plainly: "If you can swap the database, it's a sign that you implemented the repository pattern correctly", a test of the pattern, not the goal.
  3. "Every entity needs a repository." Only aggregate roots do. Evans: "Provide repositories only for aggregate roots that actually need direct access."

Where it comes from ​

Fowler and Hieatt/Mee, 2003. Patterns of Enterprise Application Architecture has a Repository entry by Edward Hieatt and Rob Mee: it "Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects." The pattern sits on top of a Data Mapper; "Objects can be added to and removed from the Repository, as they can from a simple collection of objects, and the mapping code encapsulated by the Repository will carry out the appropriate operations behind the scenes." Note that PoEAA's repository takes "query specifications", a link to the next paper.

Evans, 2003. Domain-Driven Design (Chapter 6, "The Life Cycle of a Domain Object") puts Repository next to Aggregate and Factory: aggregates give you the unit of consistency, factories create them, repositories find and store them. The DDD Reference (2015) gives the short form we quote on this page.

Evans and Fowler, Specifications. A paper by Eric Evans and Martin Fowler: "The central idea of Specification is to separate the statement of how to match a candidate, from the candidate object that it is matched against." It names three implementations: Hard Coded, Parameterized and Composite Specification, and the Subsumption pattern.

Vernon, 2013. Implementing Domain-Driven Design, chapter 12 "Repositories", splits the pattern into two styles: collection-oriented repositories that follow Evans's original description (no save step) and persistence-oriented repositories for stores that do not track changes (key-value stores, data grids), where you must call a save method. We read only a search-result summary of that chapter (O'Reilly and Safari pages returned 403 to our fetcher), so this chapter states the two styles in our words and does not quote Vernon verbatim. The chapter also covers Hibernate, TopLink, Coherence and MongoDB implementations and how a repository differs from a DAO (from the same summary).

Khononov, 2021. Learning Domain-Driven Design is on this chapter's source list as background reading on aggregates and transaction scope. We did not fetch or read it for this chapter, so we quote nothing from it and attribute no claim to it.

Microsoft, .NET microservices guide. "You should only define one repository for each aggregate root"; "you should never create a repository for each table in the database". Same rule, different stack.

Three Dots Labs, 2020. Robert Laszczak's The Repository pattern in Go shows an interface with three implementations (Firestore, MySQL, in-memory) and the closure-style update function for transactions; we use its ideas for the Go angle.

text
     Year   Source                           What it fixed
1    2003   PoEAA: Repository               A collection-like layer over the data mapper
2    2003   Evans, DDD, ch. 6                Repository per aggregate root; query in domain terms
3    2003+  Evans and Fowler, Specification  Named, composable selection rules
4    2013   Vernon, IDDD ch. 12              Collection-oriented vs persistence-oriented
5    2015   DDD Reference                    Short normative wording
6    2020   Three Dots Labs (Go)             Closure-style update; contract-style tests
7    2021   Khononov                         Repository scope = transaction scope = aggregate

What a repository is ​

A repository is an object (an interface in the domain, an implementation in infrastructure) that:

  1. is defined per aggregate root (never per entity, never per table);
  2. returns whole, valid aggregates (never half-loaded entities from inside, except lazy proxies that behave as whole);
  3. accepts whole aggregates to store, so invariants run because the root was involved;
  4. offers finders in domain terms (FindSatisfying(UnpaidLongerThan(...))), not generic field filters;
  5. hides the storage technology, schema and query language;
  6. does not own the transaction: it joins the one the application service opened.
text
     Caller (application service)              Repository                        Database
1    BEGIN (unit of work) ----------------------------------------------------->  BEGIN
2    Get(id) -------------------------------> SELECT order + lines  ---------->  rows
3                                              Reconstitute(snapshot)
4    order.Place(now)   // domain rules, event recorded in the aggregate
5    Save(order) ---------------------------> UPDATE ... WHERE version = N ---->  1 row
6                                              replace lines, INSERT outbox  --->  rows
7    COMMIT -------------------------------------------------------------------->  COMMIT

The concept catalogue ​

Collection-oriented vs persistence-oriented Must-know ​

In plain words: A collection-oriented repository acts like a Set<Order>: you Add an order, change it, and the system notices the change by itself. A persistence-oriented repository makes you say Save every time.

Common misunderstanding: "The DDD repository has no Save, so a Save method means you are doing it wrong." Evans's collection metaphor assumes an ORM whose session tracks changes (Hibernate, Doctrine ORM, EF Core). Without change tracking, the honest interface has Save. Go has no persistence context and Eloquent models have no identity map across the request, so persistence-oriented is the natural fit there.

Definition: In a collection-oriented repository the interface offers Add, Remove, Get and finders; a unit of work with an identity map and snapshot comparison writes the changes at commit. In a persistence-oriented repository the interface offers Save (insert or update), Remove, Get and finders; the caller must call Save after each change.

text
     Collection-oriented                       Persistence-oriented
1    order = orders.Get(id)                    order = orders.Get(id)
2    order.AddLine(...)                        order.AddLine(...)
3    -- nothing --                             orders.Save(order)   // explicit
4    uow.Commit()  // diff vs snapshot         tx.Commit()
5    -> UPDATE emitted by the unit of work     -> UPDATE emitted by Save

Real scenario: A Java service on Hibernate calls orders.add(order) and relies on flush. A Go service on pgx calls Save. A Laravel app calls $repo->save($order) because Eloquent only tracks dirty attributes per model instance, not per aggregate.

StackChange tracking across the aggregateNatural styleNote
Hibernate / JPA (Java)Persistence context, dirty checkingCollection-orientedpersist, flush on commit
Doctrine ORM (PHP)UnitOfWork, persist, flushCollection-orientedNeeds Doctrine, not Eloquent
EF Core (.NET)Change trackerCollection-orientedMicrosoft: DbContext is repository + unit of work
Eloquent (Laravel)Per-model isDirty(), no identity mapPersistence-orientedRelations are separate models
Go database/sql, pgx, sqlcNonePersistence-orientedYou write the SQL
GORM, ent (Go)Per-call, no persistent sessionPersistence-orientedTransactions via db.Transaction, client.Tx
MongoDB, Redis, DynamoDBNonePersistence-orientedWhole-document replace is natural

Fix / how to use it: Pick persistence-oriented in Go and Laravel. If a team insists on collection semantics, build the small unit of work shown in Go below, or move to Doctrine; do not pretend Eloquent tracks aggregates.

go
// Package style contrasts the two repository styles from Vernon's chapter 12.
// A collection-oriented repository has Add/Remove and NO save: changes to
// loaded aggregates are noticed by a unit of work (identity map + snapshot
// diff, what Hibernate and Doctrine do). Go and Eloquent do not track changes
// for you, so this file shows the machinery you would have to build.
package style

import (
	"context"
	"reflect"

	"academy/repositories/sales"
)

// Store is the low-level persistence-oriented port the collection wraps.
type Store interface {
	Get(ctx context.Context, id sales.OrderID) (*sales.Order, error)
	Save(ctx context.Context, o *sales.Order) error
	Remove(ctx context.Context, id sales.OrderID) error
}

// OrderCollection is collection-oriented: Add, Remove, Get. There is no Save.
type OrderCollection interface {
	Add(o *sales.Order)
	Remove(id sales.OrderID)
	Get(ctx context.Context, id sales.OrderID) (*sales.Order, error)
}

// TrackedCollection is a unit of work in miniature. It remembers what it
// handed out and, at Commit, writes back whatever changed.
type TrackedCollection struct {
	store    Store
	identity map[sales.OrderID]*sales.Order   // identity map: one instance per id
	original map[sales.OrderID]sales.Snapshot // state when loaded
	added    map[sales.OrderID]bool
	removed  map[sales.OrderID]bool
}

// NewTracked returns a collection backed by store.
func NewTracked(store Store) *TrackedCollection {
	return &TrackedCollection{store: store,
		identity: map[sales.OrderID]*sales.Order{}, original: map[sales.OrderID]sales.Snapshot{},
		added: map[sales.OrderID]bool{}, removed: map[sales.OrderID]bool{}}
}

func (c *TrackedCollection) Add(o *sales.Order) {
	c.identity[o.ID()] = o
	c.added[o.ID()] = true
}

func (c *TrackedCollection) Remove(id sales.OrderID) { c.removed[id] = true }

func (c *TrackedCollection) Get(ctx context.Context, id sales.OrderID) (*sales.Order, error) {
	if o, ok := c.identity[id]; ok {
		return o, nil
	}
	o, err := c.store.Get(ctx, id)
	if err != nil {
		return nil, err
	}
	c.identity[id] = o
	c.original[id] = o.Snapshot()
	return o, nil
}

// Commit is the flush: new -> Save, changed -> Save, removed -> Remove.
// A caller who forgets Commit loses the change silently; that is the price of
// "no explicit save" in a language without a persistence context.
func (c *TrackedCollection) Commit(ctx context.Context) error {
	for id := range c.removed {
		if err := c.store.Remove(ctx, id); err != nil {
			return err
		}
	}
	for id, o := range c.identity {
		if c.removed[id] {
			continue
		}
		dirty := c.added[id] || !reflect.DeepEqual(c.original[id], o.Snapshot())
		if dirty {
			if err := c.store.Save(ctx, o); err != nil {
				return err
			}
		}
	}
	return nil
}
Collection-oriented (Add / Remove)Persistence-oriented (Get / Save)orders.Get(id)order.AddLine(...)(nothing: no save)Unit of workidentity mapsnapshot diffflush on commitorders.Get(id)order.AddLine(...)orders.Save(order)RepositoryUPDATE ... WHEREversion = loaded0 rows = conflictHibernate, Doctrine ORM, EF Core track for youForget commit: change silently lostGo, Eloquent, key-value stores: explicitForget Save: change silently lost, but visible in code

What belongs in a repository Must-know ​

In plain words: Get one by id, store it, delete it, and ask the few questions the domain itself asks.

Common misunderstanding: "A repository should offer every query the screens need." Screens need lists, filters, totals and sorting; the aggregate is the wrong shape and the repository the wrong place. Keep the interface to what commands need.

Definition: The minimum is Get(id), Save(aggregate), and Remove(id) when deletion exists. Add a finder only if a use case needs aggregates found by something other than id and then acts on them (FindSatisfying(spec), FindOverdue(now)). Add NextID() if identity is assigned by the model.

MethodBelongs?Reason
Get(ctx, id)YesEvery command starts here
Save(ctx, order)YesInsert or version-checked update
Remove(ctx, id)Yes, if orders can be deletedMany domains cancel instead of delete
FindSatisfying(ctx, spec)YesA domain query that feeds commands
NextID()OftenLets the model assign identity before saving
GetAll()RarelyUnbounded; use a query service
Count(), Exists()RarelyReporting or guard rails; consider Get
Paginate(page, size)NoUI concern; query side
Where(field, op, value)NoLeaks the schema
UpdateStatus(id, status)NoBypasses the root
Raw(sql, args...)NoLeaks the dialect
text
     Rule of thumb for a finder
1    Does a use case LOAD the result and call a command on it?   yes -> repository finder
2    Does it only DISPLAY or SUMMARISE?                           yes -> query service
3    Does it cross aggregates or contexts?                        yes -> read model

What does not belong: reports, lists and pagination Must-know ​

In plain words: If a screen shows it, the aggregate is not the right thing to load.

Common misunderstanding: "CQRS is a big framework, so we cannot split reads." The split can be one extra class: a query service that runs SQL and returns a flat DTO. See Data Patterns for the full CQRS discussion and Pagination for keyset paging.

Definition: Queries that return data to display (lists, dashboards, exports, totals) bypass the repository and the aggregate, and run on a query service or a read model that may even use a different table or database. They are allowed to be eventually consistent; commands are not.

NeedHomeImplementation
Order list for a customer screenQuery serviceSELECT ... LIMIT with keyset paging into a DTO
Admin search with filtersQuery serviceQuery builder or a search engine
Daily revenueReporting storeMaterialised view, warehouse
"Is this SKU still sellable?"Catalog API or read modelAnother context's data, never a cross-context repository
Orders to cancel after 48 hRepository + specificationEach result is then a command target
text
     Order list screen
1    GET /orders?customer=c-1&page=3
2    OrderQueries.ListFor(customer, cursor)     -- query service, not the repository
3    SELECT id, status, total_minor, placed_at FROM orders WHERE customer_id = $1 AND (placed_at, id) < ($2, $3) ORDER BY placed_at DESC, id DESC LIMIT 20
4    -> []OrderListRow (flat DTO), no aggregate loaded, no lines

Specification pattern for domain queries Important ​

In plain words: Give a domain rule a name and let it be combined with And, Or, Not, so the repository can answer "find everything that satisfies this rule".

Common misunderstanding: "A specification is a query builder with extra steps." A specification states what the domain means ("unpaid longer than 48 hours"); a query builder states how a database finds it. The same specification can be tested in memory against one aggregate or translated into SQL for many.

Definition: A Spec has IsSatisfiedBy(candidate) bool. Composite specifications (And, Or, Not) combine them. A repository's FindSatisfying(spec) either translates known specifications to SQL or loads a superset and filters in memory.

text
     Specification used three ways
1    Validate:   spec.IsSatisfiedBy(order)                  -- one aggregate in memory
2    Select:     orders.FindSatisfying(spec)                -- repository translates to SQL
3    Construct:  factory builds an order that satisfies spec -- (Evans and Fowler's third use)

Translating to SQL, and the limits. The repository holds a translator: a type switch over the specification types it knows (ForCustomer, InStatus, PlacedBefore, AndSpec, OrSpec, NotSpec). An unknown specification is an error, not a silent full scan. Limits that matter:

LimitWhyRemedy
The domain rule uses logic SQL cannot expressA method call on the aggregate that reads three linesLoad a superset with a coarse SQL pre-filter, then IsSatisfiedBy in memory
Every new spec needs a translator branchOpen/closed breaks at the repositoryKeep the list short; add a dedicated finder when a rule is hot
Result size is unboundedA broad spec returns thousands of aggregatesAdd limit to the finder, or use a query service
Performance depends on indexes the spec does not knowplaced_at < $1 needs an indexAdd the index with the spec; check the plan
Cross-aggregate rules"customers with 3 unpaid orders"Query service or read model

Real scenario: Billing's nightly job: orders.FindSatisfying(UnpaidLongerThan(now, 48h)), then for each result order.Cancel("payment timeout") and Save. The rule's name is the ubiquitous language ("unpaid longer than"), and the same spec is used by the unit test with no database.

Fix / how to use it:

sql
-- What the Go translator emits for UnpaidLongerThan(now, 48h)
SELECT id, customer_id, currency, status, placed_at, version
FROM orders
WHERE (status = $1 AND placed_at < $2)   -- $1 = 'placed', $2 = now - 48h
ORDER BY id;
-- supported by: CREATE INDEX orders_status_placed_at ON orders (status, placed_at);
go
package sales

import "time"

// Spec is a domain rule that can test an aggregate in memory. Repositories
// may also translate known specs to SQL (see postgres/spec.go).
type Spec interface {
	IsSatisfiedBy(o *Order) bool
}

// ForCustomer matches orders of one customer.
type ForCustomer struct{ ID CustomerID }

// InStatus matches orders in one state.
type InStatus struct{ Status Status }

// PlacedBefore matches orders placed strictly before T.
type PlacedBefore struct{ T time.Time }

// AndSpec, OrSpec and NotSpec are the composite specification.
type (
	AndSpec struct{ Specs []Spec }
	OrSpec  struct{ Specs []Spec }
	NotSpec struct{ Spec Spec }
)

func (s ForCustomer) IsSatisfiedBy(o *Order) bool { return o.customer == s.ID }
func (s InStatus) IsSatisfiedBy(o *Order) bool    { return o.status == s.Status }
func (s PlacedBefore) IsSatisfiedBy(o *Order) bool {
	return !o.placedAt.IsZero() && o.placedAt.Before(s.T)
}

func (s AndSpec) IsSatisfiedBy(o *Order) bool {
	for _, c := range s.Specs {
		if !c.IsSatisfiedBy(o) {
			return false
		}
	}
	return true
}

func (s OrSpec) IsSatisfiedBy(o *Order) bool {
	for _, c := range s.Specs {
		if c.IsSatisfiedBy(o) {
			return true
		}
	}
	return false
}

func (s NotSpec) IsSatisfiedBy(o *Order) bool { return !s.Spec.IsSatisfiedBy(o) }

// And, Or and Not read better at call sites than the struct literals.
func And(s ...Spec) Spec { return AndSpec{Specs: s} }
func Or(s ...Spec) Spec  { return OrSpec{Specs: s} }
func Not(s Spec) Spec    { return NotSpec{Spec: s} }

// UnpaidLongerThan is the domain-language query "placed, still unpaid after d".
// The name lives in the model; the SQL does not leak into callers.
func UnpaidLongerThan(now time.Time, d time.Duration) Spec {
	return And(InStatus{Placed}, PlacedBefore{now.Add(-d)})
}
go
package postgres

import (
	"errors"
	"fmt"
	"strings"

	"academy/repositories/sales"
)

// ErrUnsupportedSpec is returned for a specification this repository cannot
// express in SQL. The caller may load a superset and filter in memory.
var ErrUnsupportedSpec = errors.New("specification cannot be translated to SQL")

// toSQL turns a known specification into a WHERE fragment with $n placeholders
// numbered from start. The set of translatable specs is deliberately small:
// it is the list of queries the domain actually asks.
func toSQL(spec sales.Spec, start int) (string, []any, error) {
	switch s := spec.(type) {
	case sales.ForCustomer:
		return fmt.Sprintf("customer_id = $%d", start), []any{string(s.ID)}, nil
	case sales.InStatus:
		return fmt.Sprintf("status = $%d", start), []any{string(s.Status)}, nil
	case sales.PlacedBefore:
		return fmt.Sprintf("placed_at < $%d", start), []any{s.T}, nil
	case sales.NotSpec:
		inner, args, err := toSQL(s.Spec, start)
		if err != nil {
			return "", nil, err
		}
		return "NOT (" + inner + ")", args, nil
	case sales.AndSpec:
		return join(s.Specs, " AND ", start)
	case sales.OrSpec:
		return join(s.Specs, " OR ", start)
	default:
		return "", nil, fmt.Errorf("%w: %T", ErrUnsupportedSpec, spec)
	}
}

func join(specs []sales.Spec, op string, start int) (string, []any, error) {
	if len(specs) == 0 {
		return "", nil, fmt.Errorf("%w: empty composite", ErrUnsupportedSpec)
	}
	parts := make([]string, 0, len(specs))
	var all []any
	for _, c := range specs {
		sql, args, err := toSQL(c, start+len(all))
		if err != nil {
			return "", nil, err
		}
		parts = append(parts, sql)
		all = append(all, args...)
	}
	return "(" + strings.Join(parts, op) + ")", all, nil
}

Repositories and transactions Must-know ​

In plain words: The use case opens the transaction; the repository only takes part in it.

Common misunderstanding: "Save should commit, so the data is safe." If Save commits, a use case that saves two aggregates (or an aggregate plus an outbox row) is no longer atomic, and a failure between the two leaves half a business operation. The commit belongs to whoever knows the use case is complete.

Definition: The unit of work boundary is the application service (Domain, Application & Infrastructure Services). Repositories obtain the connection from the ambient transaction, if any. One use case changes one aggregate per transaction (see Aggregates & Factories); the outbox row is the second row in the same transaction.

one transaction owned by the application service; the repository only joins itBEGINrepo.Getversion = 4order.Place()records eventrepo.SaveWHERE version = 4COMMIT0 rows: ErrConcurrentModificationROLLBACK, reload, retry (app decides)Save writes: orders row, order_lines, outbox event
TechniqueGoLaravel
Transaction ownerApplication service via UnitOfWork.Do(ctx, fn)DB::transaction(fn) in the handler
Repository joins bypgx.Tx stored in context.ContextThe default connection already inside the transaction
Explicit alternativeTx-scoped repository: repo.WithTx(tx)DB::connection($name)->transaction(...)
Closure-styleUpdate(ctx, id, func(*Order) error) (Three Dots Labs)$repo->update($id, fn (Order $o) => ...)
Retry on deadlockYour loop around DoDB::transaction($cb, attempts: 5)
Retry on version conflictExplicit loop in the application serviceExplicit loop; attempts does not cover it
Nested callJoin (context already has a tx)Savepoint (DB::transaction nested)
TestsFake Tx that just calls fnRefreshDatabase wraps each test in a transaction

Laravel's documentation says the transaction method "accepts an optional second argument which defines the number of times a transaction should be retried when a deadlock occurs." That is deadlock retry, not optimistic-lock retry: a ConcurrentModification thrown by your repository needs its own loop.

Passing the transaction in Go. Three options, with honest costs:

OptionHowStrengthWeakness
Transaction in context.Contextctx = context.WithValue(ctx, txKey{}, tx); repository reads itNo signature change; repositories stay smallHidden dependency; easy to forget to pass the derived ctx
Tx-scoped repositoryrepos := postgres.New(tx) per use caseExplicit, compile-time visibleFactory per use case; wiring grows
Closure updateRepository runs Get, your fn, Save inside its own txTransaction cannot leakOnly fits load-modify-save use cases

Three Dots Labs tried the context approach and reports that it was "a bit magical, not explicit, and slow in some cases" in their experiments, and prefers the closure; we show the context approach because it keeps the interface small, and say so openly.

go
// Package app is the application layer: it owns the transaction, the
// repository does not.
package app

import (
	"context"
	"time"

	"academy/repositories/sales"
)

// Tx runs fn atomically. postgres.UnitOfWork.Do satisfies it.
type Tx interface {
	Do(ctx context.Context, fn func(ctx context.Context) error) error
}

// PlaceOrder is one use case = one transaction = one aggregate.
type PlaceOrder struct {
	Tx     Tx
	Orders sales.OrderRepository
	Now    func() time.Time
}

// Handle loads, runs the domain command, saves. If Save loses an optimistic
// race it reports ErrConcurrentModification and the transaction rolls back;
// whether to retry is decided here, not in the repository.
func (h PlaceOrder) Handle(ctx context.Context, id sales.OrderID) error {
	var err error
	for attempt := 0; attempt < 3; attempt++ {
		err = h.Tx.Do(ctx, func(ctx context.Context) error {
			o, err := h.Orders.Get(ctx, id)
			if err != nil {
				return err
			}
			if err := o.Place(h.Now()); err != nil {
				return err
			}
			return h.Orders.Save(ctx, o)
		})
		if err != sales.ErrConcurrentModification {
			return err
		}
	}
	return err
}

Optimistic concurrency in Save Must-know ​

In plain words: Each stored aggregate has a version number; Save only succeeds if the number is still the one you loaded.

Common misunderstanding: "A transaction already prevents two users overwriting each other." Under READ COMMITTED (PostgreSQL default) two transactions can both read version 4, both change the order, and the second UPDATE overwrites the first, silently. A transaction gives atomicity, not "nobody changed it since I read it". See Isolation Levels.

Definition: The aggregate carries a version (0 = never saved). Save runs UPDATE ... SET version = version + 1 WHERE id = $1 AND version = $loaded. Zero rows updated means someone else saved first: return ErrConcurrentModification; the application service reloads and re-runs the command. Compare Optimistic vs Pessimistic Locking.

text
     User A                               User B                               DB version
1    Get(order 7) -> v4                   Get(order 7) -> v4                   4
2    order.MarkPaid()                     order.Cancel()
3    Save: UPDATE ... WHERE version=4     
     1 row, version := 5                                                       5
4                                         Save: UPDATE ... WHERE version=4
                                          0 rows -> ErrConcurrentModification   5
5                                         Reload (v5, paid), Cancel() now fails the domain rule
Engine / storeVersion mechanismNote
PostgreSQLInteger version column, or xmin system columnxmin changes on every update but is a 32-bit transaction id that wraps around; prefer an explicit column
MySQL / InnoDBInteger version or updated_at with microsecondsupdated_at collides under load; prefer an integer
SQL Serverrowversion columnAutomatic, binary
OracleORA_ROWSCN or a version columnExplicit column is portable
MongoDBfindOneAndUpdate with {_id, version} filterSingle-document atomicity
DynamoDBConditional write: ConditionExpression: version = :vStandard approach
RedisWATCH / MULTI / EXECOptimistic by design
Hibernate / JPA@VersionAutomatic
EloquentNone built inAdd the WHERE version yourself
GORMNone built in by defaultgorm.io/plugin/optimisticlock is a plugin; check its docs before use

Two rules: the version lives in the aggregate root only (never per line), and the repository bumps it only after every statement succeeded.

go
// Package postgres implements sales.OrderRepository with pgx. The repository
// never commits a transaction it did not start: if the caller put a pgx.Tx in
// the context (see UnitOfWork), every statement joins it; otherwise Save opens
// and commits its own short transaction.
package postgres

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgconn"
	"github.com/jackc/pgx/v5/pgxpool"

	"academy/repositories/sales"
)

// DBTX is satisfied by *pgxpool.Pool and pgx.Tx; sqlc generates the same
// interface, which is why sqlc code works inside and outside a transaction.
type DBTX interface {
	Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
	Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
	QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
}

type txKey struct{}

// UnitOfWork runs fn in one transaction; repositories called with the ctx it
// passes join that transaction. This is the application layer's tool: the
// repository itself has no Begin/Commit.
type UnitOfWork struct{ Pool *pgxpool.Pool }

// Do begins a transaction, runs fn, commits on nil and rolls back on error.
func (u UnitOfWork) Do(ctx context.Context, fn func(ctx context.Context) error) error {
	tx, err := u.Pool.Begin(ctx)
	if err != nil {
		return err
	}
	defer func() { _ = tx.Rollback(ctx) }() // no-op after Commit
	if err := fn(context.WithValue(ctx, txKey{}, tx)); err != nil {
		return err
	}
	return tx.Commit(ctx)
}

// Repository is the Postgres implementation.
type Repository struct{ pool *pgxpool.Pool }

// New returns a repository on the pool.
func New(pool *pgxpool.Pool) *Repository { return &Repository{pool: pool} }

func (r *Repository) db(ctx context.Context) DBTX {
	if tx, ok := ctx.Value(txKey{}).(pgx.Tx); ok {
		return tx
	}
	return r.pool
}

func (r *Repository) Get(ctx context.Context, id sales.OrderID) (*sales.Order, error) {
	db := r.db(ctx)
	var s sales.Snapshot
	var placed *time.Time
	err := db.QueryRow(ctx, `SELECT id, customer_id, currency, status, placed_at, version FROM orders WHERE id = $1`, string(id)).
		Scan(&s.ID, &s.Customer, &s.Currency, &s.Status, &placed, &s.Version)
	if errors.Is(err, pgx.ErrNoRows) {
		return nil, sales.ErrNotFound
	}
	if err != nil {
		return nil, err
	}
	if placed != nil {
		s.PlacedAt = *placed
	}
	lines, err := r.lines(ctx, db, []string{string(id)})
	if err != nil {
		return nil, err
	}
	s.Lines = lines[id]
	return sales.Reconstitute(s)
}

func (r *Repository) lines(ctx context.Context, db DBTX, ids []string) (map[sales.OrderID][]sales.LineSnapshot, error) {
	rows, err := db.Query(ctx, `SELECT order_id, sku, quantity, unit_price_minor FROM order_lines WHERE order_id = ANY($1::text[]) ORDER BY order_id, sku`, ids)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	out := map[sales.OrderID][]sales.LineSnapshot{}
	for rows.Next() {
		var oid sales.OrderID
		var l sales.LineSnapshot
		if err := rows.Scan(&oid, &l.SKU, &l.Quantity, &l.UnitPriceMinor); err != nil {
			return nil, err
		}
		out[oid] = append(out[oid], l)
	}
	return out, rows.Err()
}

func (r *Repository) Save(ctx context.Context, o *sales.Order) error {
	if _, inTx := ctx.Value(txKey{}).(pgx.Tx); !inTx {
		// Standalone call: open our own short transaction and join it.
		return UnitOfWork{Pool: r.pool}.Do(ctx, func(ctx context.Context) error { return r.Save(ctx, o) })
	}
	db := r.db(ctx)
	s := o.Snapshot()
	var placed *time.Time
	if !s.PlacedAt.IsZero() {
		placed = &s.PlacedAt
	}
	next := s.Version + 1
	if s.Version == 0 {
		_, err := db.Exec(ctx, `INSERT INTO orders (id, customer_id, currency, status, placed_at, version) VALUES ($1,$2,$3,$4,$5,1)`,
			string(s.ID), string(s.Customer), s.Currency, string(s.Status), placed)
		var pgErr *pgconn.PgError
		if errors.As(err, &pgErr) && pgErr.Code == "23505" { // unique_violation: someone inserted the same id
			return sales.ErrConcurrentModification
		}
		if err != nil {
			return err
		}
	} else {
		tag, err := db.Exec(ctx, `UPDATE orders SET customer_id=$2, currency=$3, status=$4, placed_at=$5, version=version+1 WHERE id=$1 AND version=$6`,
			string(s.ID), string(s.Customer), s.Currency, string(s.Status), placed, s.Version)
		if err != nil {
			return err
		}
		if tag.RowsAffected() == 0 { // stale version, or the row is gone
			return sales.ErrConcurrentModification
		}
	}
	// The aggregate is stored whole: replace its internal rows.
	if _, err := db.Exec(ctx, `DELETE FROM order_lines WHERE order_id = $1`, string(s.ID)); err != nil {
		return err
	}
	for _, l := range s.Lines {
		if _, err := db.Exec(ctx, `INSERT INTO order_lines (order_id, sku, quantity, unit_price_minor) VALUES ($1,$2,$3,$4)`,
			string(s.ID), string(l.SKU), l.Quantity, l.UnitPriceMinor); err != nil {
			return err
		}
	}
	// Events go to the outbox in the same transaction (no broker call here).
	for _, e := range o.PendingEvents() {
		topic, ok := outboxTopics[e.EventName()]
		if !ok {
			return fmt.Errorf("no published topic for %s", e.EventName())
		}
		payload, err := json.Marshal(e)
		if err != nil {
			return err
		}
		if _, err := db.Exec(ctx, `INSERT INTO outbox (topic, payload) VALUES ($1, $2)`, topic, payload); err != nil {
			return err
		}
	}
	o.Persisted(next) // only after every statement succeeded
	return nil
}

// outboxTopics maps domain event class names to the dotted, versioned topic
// of the published language. Only the outbox row carries the wire name.
var outboxTopics = map[string]string{
	"OrderPlaced": "sales.order.placed.v1",
}

func (r *Repository) Remove(ctx context.Context, id sales.OrderID) error {
	tag, err := r.db(ctx).Exec(ctx, `DELETE FROM orders WHERE id = $1`, string(id)) // lines go by ON DELETE CASCADE
	if err != nil {
		return err
	}
	if tag.RowsAffected() == 0 {
		return sales.ErrNotFound
	}
	return nil
}

func (r *Repository) FindSatisfying(ctx context.Context, spec sales.Spec) ([]*sales.Order, error) {
	where, args, err := toSQL(spec, 1)
	if err != nil {
		return nil, err
	}
	db := r.db(ctx)
	rows, err := db.Query(ctx, `SELECT id, customer_id, currency, status, placed_at, version FROM orders WHERE `+where+` ORDER BY id`, args...)
	if err != nil {
		return nil, err
	}
	var snaps []sales.Snapshot
	var ids []string
	for rows.Next() {
		var s sales.Snapshot
		var placed *time.Time
		if err := rows.Scan(&s.ID, &s.Customer, &s.Currency, &s.Status, &placed, &s.Version); err != nil {
			rows.Close()
			return nil, err
		}
		if placed != nil {
			s.PlacedAt = *placed
		}
		snaps = append(snaps, s)
		ids = append(ids, string(s.ID))
	}
	rows.Close()
	if err := rows.Err(); err != nil {
		return nil, err
	}
	if len(snaps) == 0 {
		return nil, nil
	}
	lines, err := r.lines(ctx, db, ids) // one query for all lines, not one per order
	if err != nil {
		return nil, err
	}
	out := make([]*sales.Order, 0, len(snaps))
	for _, s := range snaps {
		s.Lines = lines[s.ID]
		o, err := sales.Reconstitute(s)
		if err != nil {
			return nil, fmt.Errorf("order %s: %w", s.ID, err)
		}
		out = append(out, o)
	}
	return out, nil
}

Reconstitution Must-know ​

In plain words: Rebuilding an aggregate from stored rows is not the same as creating it, so it must not run the "create" rules or fire events.

Common misunderstanding: "Just call the constructor with the row's values." The constructor (or the NewOrder factory) enforces creation rules and records "created" events; calling it on load replays history. Loading needs a separate path that trusts the stored state but still refuses what a corrupt row could break.

Definition: Reconstitution is building an object from persisted state. Tools: a named constructor (Reconstitute(snapshot), Order::reconstitute($array)) separate from the factory; a flat snapshot (memento) crossing the boundary in both directions; private fields so only the root's methods change state.

TechniqueLanguageProsCons
Snapshot struct + ReconstituteGoExplicit, compile-checked, no reflectionFields listed three times (struct, snapshot, mapper)
Exported fields on the aggregateGoNo mappingAnyone can set state; invariants unprotected
Reflection or unsafeGoNo snapshot typeBrittle, slow, hides renames
Private constructor + static reconstitutePHPExplicitSame triple listing
ReflectionClass::newInstanceWithoutConstructor + property setPHPUsed by DoctrineBypasses all rules; needs a tested mapper
Eloquent hydration (newFromBuilder)PHPFreeThe model is the aggregate and the database row at once
Serializer (JSON/Symfony Serializer)PHPShortSame bypass; validate before trusting
What reconstitution must doWhat it must not do
Set every field, including versionRun commands such as Place
Check invariants a corrupt row could break (status in the enum, quantity at least 1)Record OrderPlaced events
Return a fresh instance each timeShare a live instance between callers (cache hazard)
Fail loudly on an unknown statusDefault unknown values silently
go
// Package sales is the Sales bounded context. Order is the aggregate root;
// the repository in this chapter loads and saves it as one unit.
package sales

import (
	"errors"
	"fmt"
	"time"
)

type (
	// OrderID is the identity of the Order aggregate.
	OrderID string
	// CustomerID references the Identity context's customer by id only.
	CustomerID string
	// SKU references a Catalog product by id only.
	SKU string
)

// Status is the order state machine.
type Status string

const (
	Draft     Status = "draft"
	Placed    Status = "placed"
	Paid      Status = "paid"
	Cancelled Status = "cancelled"
)

var (
	ErrNotEditable = errors.New("only a draft order can be edited")
	ErrEmptyOrder  = errors.New("an order needs at least one line")
	ErrBadQuantity = errors.New("quantity must be at least 1")
	ErrBadStatus   = errors.New("unknown order status")
	ErrBadState    = errors.New("stored state violates an order invariant")
)

// Money is a value object in minor units.
type Money struct {
	Minor    int64
	Currency string
}

type line struct {
	sku       SKU
	quantity  int
	unitPrice int64
}

// Order is the aggregate root. All fields are private: only the root's
// methods change state, only Snapshot/Reconstitute move state across the
// persistence boundary.
type Order struct {
	id       OrderID
	customer CustomerID
	currency string
	status   Status
	lines    []line
	placedAt time.Time
	version  int // optimistic concurrency token; 0 means "never saved"
	events   []Event
}

// NewOrder starts a draft order (the factory for a brand-new aggregate).
func NewOrder(id OrderID, customer CustomerID, currency string) *Order {
	return &Order{id: id, customer: customer, currency: currency, status: Draft}
}

// AddLine adds or merges a line while the order is a draft.
func (o *Order) AddLine(sku SKU, qty int, unitPriceMinor int64) error {
	if o.status != Draft {
		return ErrNotEditable
	}
	if qty < 1 {
		return ErrBadQuantity
	}
	for i := range o.lines {
		if o.lines[i].sku == sku {
			o.lines[i].quantity += qty
			return nil
		}
	}
	o.lines = append(o.lines, line{sku: sku, quantity: qty, unitPrice: unitPriceMinor})
	return nil
}

// Place commits the order and records OrderPlaced for the outbox.
func (o *Order) Place(now time.Time) error {
	if o.status != Draft {
		return fmt.Errorf("place: %w", ErrNotEditable)
	}
	if len(o.lines) == 0 {
		return ErrEmptyOrder
	}
	o.status = Placed
	o.placedAt = now
	o.events = append(o.events, OrderPlaced{OrderID: o.id, Total: o.Total(), At: now})
	return nil
}

// MarkPaid is called when Billing reports a captured payment.
func (o *Order) MarkPaid() error {
	if o.status != Placed {
		return errors.New("only a placed order can be paid")
	}
	o.status = Paid
	return nil
}

// Total is derived from the lines.
func (o *Order) Total() Money {
	var t int64
	for _, l := range o.lines {
		t += l.unitPrice * int64(l.quantity)
	}
	return Money{Minor: t, Currency: o.currency}
}

func (o *Order) ID() OrderID            { return o.id }
func (o *Order) Customer() CustomerID   { return o.customer }
func (o *Order) Status() Status         { return o.status }
func (o *Order) Version() int           { return o.version }
func (o *Order) PlacedAt() time.Time    { return o.placedAt }
func (o *Order) LineCount() int         { return len(o.lines) }
func (o *Order) PendingEvents() []Event { return append([]Event(nil), o.events...) }

// Persisted is called by repository implementations after a successful save:
// it records the new version and clears the events the repository has stored.
func (o *Order) Persisted(newVersion int) {
	o.version = newVersion
	o.events = nil
}

// LineSnapshot is the flat state of one line.
type LineSnapshot struct {
	SKU            SKU
	Quantity       int
	UnitPriceMinor int64
}

// Snapshot is the flat, exported state of the whole aggregate. It is the
// shape that crosses the persistence boundary in both directions.
type Snapshot struct {
	ID       OrderID
	Customer CustomerID
	Currency string
	Status   Status
	Lines    []LineSnapshot
	PlacedAt time.Time
	Version  int
}

// Snapshot copies the state out (a memento). It never exposes internal slices.
func (o *Order) Snapshot() Snapshot {
	s := Snapshot{ID: o.id, Customer: o.customer, Currency: o.currency, Status: o.status,
		PlacedAt: o.placedAt, Version: o.version}
	for _, l := range o.lines {
		s.Lines = append(s.Lines, LineSnapshot{SKU: l.sku, Quantity: l.quantity, UnitPriceMinor: l.unitPrice})
	}
	return s
}

// Reconstitute rebuilds an aggregate from stored state. It runs no commands,
// records no events, and re-checks only what a corrupt row could break.
func Reconstitute(s Snapshot) (*Order, error) {
	switch s.Status {
	case Draft, Placed, Paid, Cancelled:
	default:
		return nil, fmt.Errorf("%w: %q", ErrBadStatus, s.Status)
	}
	if s.Status != Draft && len(s.Lines) == 0 {
		return nil, fmt.Errorf("%w: %s has no lines", ErrBadState, s.ID)
	}
	o := &Order{id: s.ID, customer: s.Customer, currency: s.Currency, status: s.Status,
		placedAt: s.PlacedAt, version: s.Version}
	for _, l := range s.Lines {
		if l.Quantity < 1 {
			return nil, fmt.Errorf("%w: line %s quantity %d", ErrBadState, l.SKU, l.Quantity)
		}
		o.lines = append(o.lines, line{sku: l.SKU, quantity: l.Quantity, unitPrice: l.UnitPriceMinor})
	}
	return o, nil
}

Three Laravel strategies Must-know ​

In plain words: In Laravel you choose between letting the Eloquent model be the aggregate, mapping Eloquent to a pure class, or skipping Eloquent and mapping query-builder rows.

Common misunderstanding: "DDD in Laravel means wrapping every Eloquent model in a repository interface." A repository that returns Eloquent models and exposes save() is the model with extra indirection. The honest choice is made per context, by how many real invariants it has.

Definition:

1 Eloquent IS the aggregate2 Repository maps Eloquent3 Repository on query builderOrder extends ModelOrder::with('lines')->find($id)save() is public on the aggregate+ least code, relations free- persistence API leaks, no pure unit test- discipline, not compiler, guards itOrderRecord (Eloquent) + Order (pure)toDomain() / snapshot() in one classEloquent never leaves the repository+ pure domain, fake-able, same tables- mapping code to write and test- two classes per tableDB::table() + array rowshand-written hydrate()explicit SQL, version in WHERE+ no hidden queries or events- most code, no relations helper+ closest to Go/sqlc styleorders · order_lines · outbox (same schema, same transaction rules)
Question1. Eloquent IS the aggregate2. Repository maps Eloquent to domain3. Repository on query builder
Domain classApp\Sales\EloquentAggregate\Order extends ModelApp\Sales\Domain\Order (pure PHP)App\Sales\Domain\Order (pure PHP)
Persistence classesNoneOrderRecord, OrderLineRecord (Eloquent)None
RepositoryNone or a thin finderEloquentOrderRepositoryQueryBuilderOrderRepository
Unit tests without a databaseNo (the model wants a connection to save)Yes, with InMemoryOrderRepositoryYes, with InMemoryOrderRepository
Persistence API on the aggregatePublic: save, update, delete, fillHiddenHidden
Relations, eager loadingFree: with('lines')Free inside the repositoryYou write the second query
Optimistic lockAdd by hand: saveWithVersionInside saveInside save
Model events / observersFire (can surprise)Fire on the record, not the aggregateNone
Mapping codeNonetoDomain and savehydrate and save
Typical teamCRUD-heavy context, small teamCore domain with real invariantsHot paths, legacy schema, bulk loading
Honest costDiscipline, not compiler, protects the rulesTwo classes per table; mapping testsMost code; no relation sugar

Decision rule. Count the invariants that span more than one row (line limits, totals, state machine, "cannot be dispatched unpaid"). Zero or one: option 1 is fine, keep $fillable = [] and add domain methods. Several: option 2. One query you measured as hot: option 3 for that repository only. Mixing per context is normal: Catalog (generic, CRUD) uses option 1; Sales (core) uses option 2.

Eloquent behaviour you rely on (checked against the Laravel 13 docs): isDirty() and getDirty() show which attributes of one model changed since it was retrieved; DB::transaction(callback, attempts: n) retries on deadlock; lockForUpdate() and sharedLock() exist on the query builder; RefreshDatabase wraps each test in a transaction.

php
<?php

declare(strict_types=1);

namespace App\Sales\Domain;

use DateTimeImmutable;
use DomainException;

/**
 * Aggregate root of the Sales context. State is private; only commands change
 * it, only snapshot()/reconstitute() move it across the persistence boundary.
 */
final class Order
{
    /** @var list<array{sku: string, quantity: int, unit_price_minor: int}> */
    private array $lines = [];

    /** @var list<object> */
    private array $events = [];

    private function __construct(
        private readonly string $id,
        private readonly string $customerId,
        private readonly string $currency,
        private string $status,
        private ?DateTimeImmutable $placedAt,
        private int $version,
    ) {
    }

    /** Factory for a brand-new aggregate (version 0 = never saved). */
    public static function draft(string $id, string $customerId, string $currency): self
    {
        return new self($id, $customerId, $currency, 'draft', null, 0);
    }

    /**
     * Rebuild from stored state: no commands run, no events recorded.
     *
     * @param array{id: string, customer_id: string, currency: string, status: string, placed_at: ?string, version: int, lines: list<array{sku: string, quantity: int, unit_price_minor: int}>} $s
     */
    public static function reconstitute(array $s): self
    {
        if (!in_array($s['status'], ['draft', 'placed', 'paid', 'cancelled'], true)) {
            throw new DomainException("unknown order status {$s['status']}");
        }
        $o = new self(
            $s['id'],
            $s['customer_id'],
            $s['currency'],
            $s['status'],
            $s['placed_at'] === null ? null : new DateTimeImmutable($s['placed_at']),
            $s['version'],
        );
        $o->lines = $s['lines'];

        return $o;
    }

    public function addLine(string $sku, int $quantity, int $unitPriceMinor): void
    {
        if ($this->status !== 'draft') {
            throw new DomainException('only a draft order can be edited');
        }
        if ($quantity < 1) {
            throw new DomainException('quantity must be at least 1');
        }
        foreach ($this->lines as $i => $line) {
            if ($line['sku'] === $sku) {
                $this->lines[$i]['quantity'] += $quantity;

                return;
            }
        }
        $this->lines[] = ['sku' => $sku, 'quantity' => $quantity, 'unit_price_minor' => $unitPriceMinor];
    }

    public function place(DateTimeImmutable $now): void
    {
        if ($this->status !== 'draft') {
            throw new DomainException('only a draft order can be placed');
        }
        if ($this->lines === []) {
            throw new DomainException('an order needs at least one line');
        }
        $this->status = 'placed';
        $this->placedAt = $now;
        $this->events[] = new OrderPlaced($this->id, $this->totalMinor(), $now);
    }

    public function markPaid(): void
    {
        if ($this->status !== 'placed') {
            throw new DomainException('only a placed order can be paid');
        }
        $this->status = 'paid';
    }

    public function totalMinor(): int
    {
        return array_sum(array_map(fn (array $l) => $l['quantity'] * $l['unit_price_minor'], $this->lines));
    }

    public function id(): string { return $this->id; }
    public function customerId(): string { return $this->customerId; }
    public function status(): string { return $this->status; }
    public function placedAt(): ?DateTimeImmutable { return $this->placedAt; }
    public function version(): int { return $this->version; }
    public function lineCount(): int { return count($this->lines); }

    /** Events recorded since the last save; repositories store them. @return list<object> */
    public function pendingEvents(): array { return $this->events; }

    /** Called by repositories after a successful save. */
    public function persisted(int $newVersion): void
    {
        $this->version = $newVersion;
        $this->events = [];
    }

    /** @return array{id: string, customer_id: string, currency: string, status: string, placed_at: ?string, version: int, lines: list<array{sku: string, quantity: int, unit_price_minor: int}>} */
    public function snapshot(): array
    {
        return [
            'id' => $this->id,
            'customer_id' => $this->customerId,
            'currency' => $this->currency,
            'status' => $this->status,
            'placed_at' => $this->placedAt?->format('Y-m-d H:i:s'),
            'version' => $this->version,
            'lines' => $this->lines,
        ];
    }
}

Fakes and contract tests Must-know ​

In plain words: An in-memory repository lets domain and use-case tests run in milliseconds; one shared test suite proves the fake and the real repository behave the same.

Common misunderstanding: "Mocking the repository interface is enough." A mock returns what you scripted and checks calls; it cannot tell you that Save bumps the version, that Get returns a copy, or that a stale save fails. A fake with real behaviour, kept honest by a contract test, can.

Definition: A fake is a working lightweight implementation. A contract test is one test function (Go) or one trait (PHP) that takes a repository factory and asserts the interface's promises; each implementation runs it.

text
     Contract test per implementation
1    repotest.Run(t, memory.New)                          -- always, milliseconds
2    repotest.Run(t, postgres.New(pool))                  -- when DATABASE_URL is set; expected, not run here
3    repotest.Run(t, cache.Wrap(memory.New()))            -- decorators must keep the contract too
4    -- any failing case on the fake = fix the fake, not the test
Contract caseWhat it protects
Save then Get returns the same stateMapping both ways
Unknown id is ErrNotFoundThe error the use case maps to 404
Save bumps version and clears eventsHand-off to the outbox
Stale save is ErrConcurrentModificationOptimistic concurrency
Whole aggregate saved (lines included)No partial saves
Remove then Get failsLifecycle
FindSatisfying answers specificationsQuery translation
go
// Package repotest holds the contract every sales.OrderRepository must pass.
// The in-memory fake and the Postgres implementation run the SAME function,
// so the fake cannot drift away from the real behaviour.
package repotest

import (
	"context"
	"errors"
	"testing"
	"time"

	"academy/repositories/sales"
)

// Factory returns a fresh, empty repository for one test.
type Factory func(t *testing.T) sales.OrderRepository

var t0 = time.Date(2026, 11, 1, 10, 0, 0, 0, time.UTC)

func newPlaced(t *testing.T, id sales.OrderID, cust sales.CustomerID, at time.Time) *sales.Order {
	t.Helper()
	o := sales.NewOrder(id, cust, "EUR")
	must(t, o.AddLine("sku-1", 2, 1500))
	must(t, o.AddLine("sku-2", 1, 999))
	must(t, o.Place(at))
	return o
}

func must(t *testing.T, err error) {
	t.Helper()
	if err != nil {
		t.Fatal(err)
	}
}

// Run executes every contract case against repositories built by f.
func Run(t *testing.T, f Factory) {
	ctx := context.Background()

	t.Run("save then get returns the same state", func(t *testing.T) {
		r := f(t)
		o := newPlaced(t, "o-1", "c-1", t0)
		must(t, r.Save(ctx, o))
		got, err := r.Get(ctx, "o-1")
		must(t, err)
		if got.Status() != sales.Placed || got.LineCount() != 2 || got.Total() != o.Total() {
			t.Fatalf("round trip lost state: %+v", got.Snapshot())
		}
		if !got.PlacedAt().Equal(t0) {
			t.Fatalf("placedAt = %v", got.PlacedAt())
		}
	})

	t.Run("get unknown id is ErrNotFound", func(t *testing.T) {
		_, err := f(t).Get(ctx, "nope")
		if !errors.Is(err, sales.ErrNotFound) {
			t.Fatalf("err = %v", err)
		}
	})

	t.Run("save bumps the version and clears events", func(t *testing.T) {
		r := f(t)
		o := newPlaced(t, "o-2", "c-1", t0)
		if len(o.PendingEvents()) != 1 {
			t.Fatal("expected OrderPlaced before save")
		}
		must(t, r.Save(ctx, o))
		if o.Version() != 1 || len(o.PendingEvents()) != 0 {
			t.Fatalf("version=%d events=%d", o.Version(), len(o.PendingEvents()))
		}
	})

	t.Run("stale save fails with ErrConcurrentModification", func(t *testing.T) {
		r := f(t)
		must(t, r.Save(ctx, newPlaced(t, "o-3", "c-1", t0)))
		a, _ := r.Get(ctx, "o-3")
		b, _ := r.Get(ctx, "o-3")
		must(t, a.MarkPaid())
		must(t, r.Save(ctx, a))
		must(t, b.MarkPaid())
		if err := r.Save(ctx, b); !errors.Is(err, sales.ErrConcurrentModification) {
			t.Fatalf("err = %v", err)
		}
	})

	t.Run("the aggregate is saved whole, lines included", func(t *testing.T) {
		r := f(t)
		o := sales.NewOrder("o-4", "c-1", "EUR")
		must(t, o.AddLine("sku-1", 1, 100))
		must(t, r.Save(ctx, o))
		again, _ := r.Get(ctx, "o-4")
		must(t, again.AddLine("sku-9", 3, 50))
		must(t, r.Save(ctx, again))
		final, _ := r.Get(ctx, "o-4")
		if final.LineCount() != 2 || final.Total().Minor != 250 {
			t.Fatalf("lines=%d total=%d", final.LineCount(), final.Total().Minor)
		}
	})

	t.Run("remove deletes the aggregate", func(t *testing.T) {
		r := f(t)
		must(t, r.Save(ctx, newPlaced(t, "o-5", "c-1", t0)))
		must(t, r.Remove(ctx, "o-5"))
		if _, err := r.Get(ctx, "o-5"); !errors.Is(err, sales.ErrNotFound) {
			t.Fatalf("err = %v", err)
		}
		if err := r.Remove(ctx, "o-5"); !errors.Is(err, sales.ErrNotFound) {
			t.Fatalf("second remove err = %v", err)
		}
	})

	t.Run("FindSatisfying answers a domain specification", func(t *testing.T) {
		r := f(t)
		now := t0.Add(72 * time.Hour)
		old := newPlaced(t, "o-6", "c-1", t0)                    // placed 3 days ago, unpaid
		fresh := newPlaced(t, "o-7", "c-1", now.Add(-time.Hour)) // placed an hour ago
		paid := newPlaced(t, "o-8", "c-2", t0)
		must(t, paid.MarkPaid())
		for _, o := range []*sales.Order{old, fresh, paid} {
			must(t, r.Save(ctx, o))
		}
		got, err := r.FindSatisfying(ctx, sales.UnpaidLongerThan(now, 48*time.Hour))
		must(t, err)
		if len(got) != 1 || got[0].ID() != "o-6" {
			t.Fatalf("got %d orders", len(got))
		}
		mixed, err := r.FindSatisfying(ctx, sales.Or(sales.ForCustomer{ID: "c-2"}, sales.Not(sales.InStatus{Status: sales.Paid})))
		must(t, err)
		if len(mixed) != 3 {
			t.Fatalf("or/not: got %d, want 3", len(mixed))
		}
	})
}
go
// Package memory is the in-memory OrderRepository used by unit tests and by
// the contract tests. It stores copies (snapshots), never the live pointer,
// so it behaves like a database: mutating a loaded order changes nothing
// until Save.
package memory

import (
	"context"
	"sort"
	"sync"

	"academy/repositories/sales"
)

// Repository is safe for concurrent use.
type Repository struct {
	mu     sync.Mutex
	rows   map[sales.OrderID]sales.Snapshot
	events []sales.Event // what the outbox table would hold
}

// New returns an empty repository.
func New() *Repository { return &Repository{rows: map[sales.OrderID]sales.Snapshot{}} }

// Stored returns the events saved so far (test helper).
func (r *Repository) Stored() []sales.Event {
	r.mu.Lock()
	defer r.mu.Unlock()
	return append([]sales.Event(nil), r.events...)
}

func (r *Repository) Get(_ context.Context, id sales.OrderID) (*sales.Order, error) {
	r.mu.Lock()
	defer r.mu.Unlock()
	s, ok := r.rows[id]
	if !ok {
		return nil, sales.ErrNotFound
	}
	return sales.Reconstitute(clone(s))
}

func (r *Repository) Save(_ context.Context, o *sales.Order) error {
	r.mu.Lock()
	defer r.mu.Unlock()
	stored, exists := r.rows[o.ID()]
	switch {
	case !exists && o.Version() != 0:
		return sales.ErrConcurrentModification // it was removed under us
	case exists && stored.Version != o.Version():
		return sales.ErrConcurrentModification
	}
	snap := o.Snapshot()
	snap.Version = o.Version() + 1
	r.rows[o.ID()] = clone(snap)
	r.events = append(r.events, o.PendingEvents()...)
	o.Persisted(snap.Version)
	return nil
}

func (r *Repository) Remove(_ context.Context, id sales.OrderID) error {
	r.mu.Lock()
	defer r.mu.Unlock()
	if _, ok := r.rows[id]; !ok {
		return sales.ErrNotFound
	}
	delete(r.rows, id)
	return nil
}

func (r *Repository) FindSatisfying(_ context.Context, spec sales.Spec) ([]*sales.Order, error) {
	r.mu.Lock()
	defer r.mu.Unlock()
	var out []*sales.Order
	for _, s := range r.rows {
		o, err := sales.Reconstitute(clone(s))
		if err != nil {
			return nil, err
		}
		if spec.IsSatisfiedBy(o) {
			out = append(out, o)
		}
	}
	sort.Slice(out, func(i, j int) bool { return out[i].ID() < out[j].ID() })
	return out, nil
}

func clone(s sales.Snapshot) sales.Snapshot {
	s.Lines = append([]sales.LineSnapshot(nil), s.Lines...)
	return s
}
php
<?php

declare(strict_types=1);

namespace Tests\Sales;

use App\Sales\Domain\ConcurrentModification;
use App\Sales\Domain\Order;
use App\Sales\Domain\OrderNotFound;
use App\Sales\Domain\OrderRepository;
use App\Sales\Domain\UnpaidLongerThan;
use DateTimeImmutable;

/**
 * Contract tests as a trait: every repository test class uses it and supplies
 * repository() (in-memory, Eloquent, query builder). A fake that passes a different test
 * suite than the real thing is a lie.
 */
trait OrderRepositoryContract
{
    abstract protected function repository(): OrderRepository;

    private function placed(string $id, string $customer, string $at): Order
    {
        $o = Order::draft($id, $customer, 'EUR');
        $o->addLine('sku-1', 2, 1500);
        $o->addLine('sku-2', 1, 999);
        $o->place(new DateTimeImmutable($at));

        return $o;
    }

    public function test_round_trip_keeps_the_whole_aggregate(): void
    {
        $repo = $this->repository();
        $o = $this->placed('o-1', 'c-1', '2026-11-01 10:00:00');
        $repo->save($o);
        $got = $repo->get('o-1');
        $this->assertSame('placed', $got->status());
        $this->assertSame(2, $got->lineCount());
        $this->assertSame($o->totalMinor(), $got->totalMinor());
    }

    public function test_unknown_id_is_not_found(): void
    {
        $this->expectException(OrderNotFound::class);
        $this->repository()->get('nope');
    }

    public function test_save_bumps_version_and_clears_events(): void
    {
        $repo = $this->repository();
        $o = $this->placed('o-2', 'c-1', '2026-11-01 10:00:00');
        $this->assertCount(1, $o->pendingEvents());
        $repo->save($o);
        $this->assertSame(1, $o->version());
        $this->assertSame([], $o->pendingEvents());
    }

    public function test_stale_save_is_rejected(): void
    {
        $repo = $this->repository();
        $repo->save($this->placed('o-3', 'c-1', '2026-11-01 10:00:00'));
        $a = $repo->get('o-3');
        $b = $repo->get('o-3');
        $a->markPaid();
        $repo->save($a);
        $b->markPaid();
        $this->expectException(ConcurrentModification::class);
        $repo->save($b);
    }

    public function test_remove_then_get_fails(): void
    {
        $repo = $this->repository();
        $repo->save($this->placed('o-4', 'c-1', '2026-11-01 10:00:00'));
        $repo->remove('o-4');
        $this->expectException(OrderNotFound::class);
        $repo->get('o-4');
    }

    public function test_find_satisfying_a_specification(): void
    {
        $repo = $this->repository();
        $now = new DateTimeImmutable('2026-11-04 10:00:00');
        $paid = $this->placed('o-7', 'c-2', '2026-11-01 10:00:00');
        $paid->markPaid();
        $repo->save($this->placed('o-5', 'c-1', '2026-11-01 10:00:00')); // old, unpaid
        $repo->save($this->placed('o-6', 'c-1', '2026-11-04 09:00:00')); // recent
        $repo->save($paid);

        $overdue = $repo->findSatisfying(UnpaidLongerThan::spec($now, 48 * 3600));
        $this->assertSame(['o-5'], array_map(fn (Order $o) => $o->id(), $overdue));
    }
}

Caching inside a repository Good to know ​

In plain words: A cache in front of Get can save reads, but it must never let you save from a stale copy without noticing.

Common misunderstanding: "Caching aggregates is free speed." A cached aggregate is a copy; if two requests share the same live object they mutate each other's state, and stale data feeds commands. Cache snapshots, return a fresh instance each time, invalidate on Save/Remove, and keep the version check as the safety net.

Definition: Implement the cache as a decorator that implements the same interface, caches Get only, and invalidates on write. With the version check, a stale read costs at most one ErrConcurrentModification. Never cache FindSatisfying for commands. See Storage & Data Scaling for cache tiers and Redis.

RuleReason
Cache the snapshot, not the live aggregateCallers mutate what they receive
Invalidate before and after SaveA failed save must not leave a stale entry
Invalidate on RemoveOtherwise a deleted order is served
Keep the version checkIt turns staleness into a retry, not corruption
TTL as a backstopMulti-instance deployments cannot invalidate each other
Do not cache for read screens hereScreens use a read model with its own cache
go
// Package cache is a read-through decorator for the Order repository.
// It caches Get only, and drops the entry on every Save/Remove, so a stale
// copy can at worst cause one ErrConcurrentModification, never a lost update.
package cache

import (
	"context"
	"sync"

	"academy/repositories/sales"
)

// Repository wraps another OrderRepository.
type Repository struct {
	sales.OrderRepository
	mu    sync.Mutex
	items map[sales.OrderID]sales.Snapshot
}

// Wrap returns the caching decorator.
func Wrap(inner sales.OrderRepository) *Repository {
	return &Repository{OrderRepository: inner, items: map[sales.OrderID]sales.Snapshot{}}
}

func (r *Repository) Get(ctx context.Context, id sales.OrderID) (*sales.Order, error) {
	r.mu.Lock()
	s, ok := r.items[id]
	r.mu.Unlock()
	if ok {
		return sales.Reconstitute(s) // a fresh instance every time: never share the live aggregate
	}
	o, err := r.OrderRepository.Get(ctx, id)
	if err != nil {
		return nil, err
	}
	r.mu.Lock()
	r.items[id] = o.Snapshot()
	r.mu.Unlock()
	return o, nil
}

func (r *Repository) Save(ctx context.Context, o *sales.Order) error {
	r.forget(o.ID()) // invalidate before AND after: a failed save must not leave a stale entry
	err := r.OrderRepository.Save(ctx, o)
	r.forget(o.ID())
	return err
}

func (r *Repository) Remove(ctx context.Context, id sales.OrderID) error {
	r.forget(id)
	err := r.OrderRepository.Remove(ctx, id)
	r.forget(id)
	return err
}

func (r *Repository) forget(id sales.OrderID) {
	r.mu.Lock()
	delete(r.items, id)
	r.mu.Unlock()
}

Event dispatch on save Important ​

In plain words: The aggregate remembers what happened; the repository stores those facts together with the state; a relay publishes them later.

Common misunderstanding: "Save should publish the event to the broker." A broker call inside the transaction can succeed while the commit fails (a ghost event), or the commit can succeed while the publish fails (a lost event). Publish after commit from a stored record. That is the Outbox Pattern.

Definition: The aggregate appends domain events while handling commands (o.events = append(...)). Save writes the state row(s) and one outbox row per event in the same transaction, then calls Persisted(newVersion) which clears the pending list. A relay (polling or CDC, see Change Data Capture) publishes the outbox. Consumers must be idempotent (Idempotent Consumer & Inbox). Domain events vs integration events are separated in that chapter.

ApproachAtomic with state?Cost
Publish inside SaveNoGhost or lost events
Publish in the application service after SaveNoLost event if the process dies between
Dispatch Laravel events after commit (afterCommit)Per process onlyLost on crash; fine for in-process listeners
Outbox row in Save + relayYesA table and a relay process
Event sourcing (events are the state)YesDifferent model; see Event Sourcing & CQRS

Anti-patterns Important ​

In plain words: The decay of a repository is gradual: one more method, one more Where, until it is a table gateway.

Common misunderstanding: "A generic Repository<T> removes boilerplate, so it is good design." It removes the part that should differ per aggregate (the finders, the loading rules, the transaction semantics) and keeps the part that should not exist (generic field queries).

Definition and fixes:

Anti-patternSymptomWhy it hurtsFix
Generic Repository<T> with 30 methodsGetAll, Where, Paginate, Raw on every typeNo aggregate semantics; becomes a DAOOne small interface per aggregate root
Repository for a child entityOrderLineRepository.UpdateQuantityBypasses the root, so line limits and totals are skippedOnly Order has a repository; lines change through Order.AddLine
Leaking Builder / Queryrepo.Query() returns an Eloquent Builder or *sql.RowsCallers write SQL; storage change breaks all of themReturn aggregates or DTOs; add a named finder
"Repository" is a DAO over tablesOne class per table, CRUD onlyAggregate spread over four classes, no invariantsAggregate-shaped interface
Business logic in the repositoryif order.Total > limit inside SaveRules invisible to domain testsMove to the aggregate or a domain service
Repository commitstx.Commit() inside SaveUse cases lose atomicityApplication service owns the transaction
Repository returns half-loaded aggregatesLines nil until touchedInvariants checked on partial stateLoad whole, or use lazy proxies that behave whole
Repository calls another contextSalesOrderRepository queries catalog_productsCross-context couplingCatalog API or a local read copy
Active Record in disguiseDomain method calls save()Domain depends on persistenceRepository saves, aggregate never does
Save-from-anywhereControllers call $repo->save()Invariants skippedApplication service is the only caller
go
// Package wrong shows the repository anti-patterns. Do not copy.
package wrong

import "context"

// Repository is the "one generic repository for everything" trap. Thirty
// methods later it is a DAO: it knows every table and enforces no invariant.
type Repository[T any] interface {
	GetByID(ctx context.Context, id string) (T, error)
	GetAll(ctx context.Context) ([]T, error)
	Create(ctx context.Context, e T) error
	Update(ctx context.Context, e T) error
	Delete(ctx context.Context, id string) error
	FindBy(ctx context.Context, field string, value any) ([]T, error)
	// ... Count, Exists, Paginate, Where(...), Raw(sql string, args ...any) ...
}

// OrderLineRepository is wrong in a different way: OrderLine is not an
// aggregate root. Saving lines on their own bypasses Order's invariants
// (line limit, status checks, total).
type OrderLineRepository interface {
	Create(ctx context.Context, orderID string, sku string, qty int) error
	UpdateQuantity(ctx context.Context, orderID string, sku string, qty int) error
}

// QueryLeak returns the persistence tool itself, so every caller now depends
// on the SQL dialect and the table layout.
type QueryLeak interface {
	Query(ctx context.Context) (queryBuilder any)
}
php
<?php

declare(strict_types=1);

namespace App\Wrong;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

/**
 * Anti-pattern: one "repository" for every model. It is a DAO over tables:
 * it enforces no invariant, leaks Builder, and invites Order::lines updates
 * that bypass the Order root.
 *
 * @template T of Model
 */
abstract class GenericRepository
{
    /** @return class-string<T> */
    abstract protected function model(): string;

    public function find(int|string $id): ?Model { return $this->model()::find($id); }
    public function all(): iterable { return $this->model()::all(); }
    public function create(array $attrs): Model { return $this->model()::create($attrs); }
    public function update(int|string $id, array $attrs): bool { return $this->model()::whereKey($id)->update($attrs) > 0; }
    public function delete(int|string $id): bool { return $this->model()::destroy($id) > 0; }

    // The leak: every caller now writes Eloquent queries (and filters,
    // joins and raw SQL) against the persistence model.
    public function query(): Builder { return $this->model()::query(); }
}

Mechanics ​

Save step by step Must-know ​

text
     Save(ctx, order)          -- inside the application service's transaction
1    snapshot := order.Snapshot()
2    version == 0 ?  INSERT INTO orders (..., version) VALUES (..., 1)      -- unique_violation 23505 -> conflict
3    version  > 0 ?  UPDATE orders SET ..., version = version + 1 WHERE id = $1 AND version = $loaded
4                    rows affected = 0 -> ErrConcurrentModification
5    DELETE FROM order_lines WHERE order_id = $1; INSERT each line          -- replace children
6    INSERT INTO outbox (topic, payload) for each pending event
7    order.Persisted(version + 1)  -- only now: new version, events cleared
ConcernDetail
Replace vs diff childrenReplace is simple and fine under about 100 lines; diff when a line has foreign keys or history
Unique violationPostgreSQL SQLSTATE 23505; MySQL error 1062; both mean someone inserted the id first
Serialisation failure40001 under REPEATABLE READ or SERIALIZABLE: retry the transaction, see Isolation Levels
Deadlock40P01 (PostgreSQL), 1213 (MySQL): retry; DB::transaction(..., attempts: n) does it in Laravel
Lock waitMySQL 1205; PostgreSQL lock_timeout raises 55P03
Foreign key cascadeON DELETE CASCADE on order_lines makes Remove one statement

Get step by step Must-know ​

text
     Get(ctx, id)
1    SELECT ... FROM orders WHERE id = $1                    -- 0 rows -> ErrNotFound
2    SELECT ... FROM order_lines WHERE order_id = ANY($1)    -- one query for all lines
3    Reconstitute(snapshot)                                  -- validates; no events
4    return *Order (fresh instance, version = stored version)

FindSatisfying loads many aggregates in two queries (orders, then all their lines with = ANY($1::text[]) or whereIn) rather than one query per order. That is the repository's defence against the N+1 problem described in ORM Pitfalls.

sqlc and pgx in Go Important ​

ToolWhat it isRole in a repository
pgx (github.com/jackc/pgx/v5)PostgreSQL driver and toolkitpgx.Tx, pgxpool.Pool, Exec, Query, QueryRow
sqlcGenerates type-safe Go from SQL filesOne generated method per query; DBTX interface works with pool or tx; WithTx
GORMORMdb.Transaction(func(tx *gorm.DB) error); default write transactions can be disabled with SkipDefaultTransaction
entEntity framework with codegenclient.Tx(ctx), tx.Client() for a transactional client
database/sqlStandard librarydb.BeginTx, tx.ExecContext

sqlc's README describes it in three steps: you write queries in SQL, run sqlc to generate code with type-safe interfaces to those queries, and write application code that calls the generated code. We keep the query file in postgres/queries.sql and a hand-written DBTX with the same shape, because sqlc is not installed in this build; the contract test is the safety net either way.

sql
-- sqlc input (sqlc.yaml: engine postgresql, sql_package pgx/v5). sqlc would
-- generate a Queries struct with one typed method per query below and a
-- DBTX interface; repository.go uses the same shape written by hand so this
-- module compiles without running the generator.

-- name: GetOrder :one
SELECT id, customer_id, currency, status, placed_at, version
FROM orders WHERE id = $1;

-- name: ListLinesForOrders :many
SELECT order_id, sku, quantity, unit_price_minor
FROM order_lines WHERE order_id = ANY($1::text[]) ORDER BY order_id, sku;

-- name: InsertOrder :exec
INSERT INTO orders (id, customer_id, currency, status, placed_at, version)
VALUES ($1, $2, $3, $4, $5, 1);

-- name: UpdateOrder :execrows
UPDATE orders
SET customer_id = $2, currency = $3, status = $4, placed_at = $5, version = version + 1
WHERE id = $1 AND version = $6;

-- name: DeleteLines :exec
DELETE FROM order_lines WHERE order_id = $1;

-- name: InsertLine :exec
INSERT INTO order_lines (order_id, sku, quantity, unit_price_minor) VALUES ($1, $2, $3, $4);

-- name: InsertOutbox :exec
INSERT INTO outbox (topic, payload) VALUES ($1, $2);

-- name: DeleteOrder :execrows
DELETE FROM orders WHERE id = $1;

Go ​

The Go module academy/repositories contains the whole running example. Everything except the Postgres integration test runs without a database: go vet ./... && go test ./....

The aggregate and its snapshot ​

go
// Package sales is the Sales bounded context. Order is the aggregate root;
// the repository in this chapter loads and saves it as one unit.
package sales

import (
	"errors"
	"fmt"
	"time"
)

type (
	// OrderID is the identity of the Order aggregate.
	OrderID string
	// CustomerID references the Identity context's customer by id only.
	CustomerID string
	// SKU references a Catalog product by id only.
	SKU string
)

// Status is the order state machine.
type Status string

const (
	Draft     Status = "draft"
	Placed    Status = "placed"
	Paid      Status = "paid"
	Cancelled Status = "cancelled"
)

var (
	ErrNotEditable = errors.New("only a draft order can be edited")
	ErrEmptyOrder  = errors.New("an order needs at least one line")
	ErrBadQuantity = errors.New("quantity must be at least 1")
	ErrBadStatus   = errors.New("unknown order status")
	ErrBadState    = errors.New("stored state violates an order invariant")
)

// Money is a value object in minor units.
type Money struct {
	Minor    int64
	Currency string
}

type line struct {
	sku       SKU
	quantity  int
	unitPrice int64
}

// Order is the aggregate root. All fields are private: only the root's
// methods change state, only Snapshot/Reconstitute move state across the
// persistence boundary.
type Order struct {
	id       OrderID
	customer CustomerID
	currency string
	status   Status
	lines    []line
	placedAt time.Time
	version  int // optimistic concurrency token; 0 means "never saved"
	events   []Event
}

// NewOrder starts a draft order (the factory for a brand-new aggregate).
func NewOrder(id OrderID, customer CustomerID, currency string) *Order {
	return &Order{id: id, customer: customer, currency: currency, status: Draft}
}

// AddLine adds or merges a line while the order is a draft.
func (o *Order) AddLine(sku SKU, qty int, unitPriceMinor int64) error {
	if o.status != Draft {
		return ErrNotEditable
	}
	if qty < 1 {
		return ErrBadQuantity
	}
	for i := range o.lines {
		if o.lines[i].sku == sku {
			o.lines[i].quantity += qty
			return nil
		}
	}
	o.lines = append(o.lines, line{sku: sku, quantity: qty, unitPrice: unitPriceMinor})
	return nil
}

// Place commits the order and records OrderPlaced for the outbox.
func (o *Order) Place(now time.Time) error {
	if o.status != Draft {
		return fmt.Errorf("place: %w", ErrNotEditable)
	}
	if len(o.lines) == 0 {
		return ErrEmptyOrder
	}
	o.status = Placed
	o.placedAt = now
	o.events = append(o.events, OrderPlaced{OrderID: o.id, Total: o.Total(), At: now})
	return nil
}

// MarkPaid is called when Billing reports a captured payment.
func (o *Order) MarkPaid() error {
	if o.status != Placed {
		return errors.New("only a placed order can be paid")
	}
	o.status = Paid
	return nil
}

// Total is derived from the lines.
func (o *Order) Total() Money {
	var t int64
	for _, l := range o.lines {
		t += l.unitPrice * int64(l.quantity)
	}
	return Money{Minor: t, Currency: o.currency}
}

func (o *Order) ID() OrderID            { return o.id }
func (o *Order) Customer() CustomerID   { return o.customer }
func (o *Order) Status() Status         { return o.status }
func (o *Order) Version() int           { return o.version }
func (o *Order) PlacedAt() time.Time    { return o.placedAt }
func (o *Order) LineCount() int         { return len(o.lines) }
func (o *Order) PendingEvents() []Event { return append([]Event(nil), o.events...) }

// Persisted is called by repository implementations after a successful save:
// it records the new version and clears the events the repository has stored.
func (o *Order) Persisted(newVersion int) {
	o.version = newVersion
	o.events = nil
}

// LineSnapshot is the flat state of one line.
type LineSnapshot struct {
	SKU            SKU
	Quantity       int
	UnitPriceMinor int64
}

// Snapshot is the flat, exported state of the whole aggregate. It is the
// shape that crosses the persistence boundary in both directions.
type Snapshot struct {
	ID       OrderID
	Customer CustomerID
	Currency string
	Status   Status
	Lines    []LineSnapshot
	PlacedAt time.Time
	Version  int
}

// Snapshot copies the state out (a memento). It never exposes internal slices.
func (o *Order) Snapshot() Snapshot {
	s := Snapshot{ID: o.id, Customer: o.customer, Currency: o.currency, Status: o.status,
		PlacedAt: o.placedAt, Version: o.version}
	for _, l := range o.lines {
		s.Lines = append(s.Lines, LineSnapshot{SKU: l.sku, Quantity: l.quantity, UnitPriceMinor: l.unitPrice})
	}
	return s
}

// Reconstitute rebuilds an aggregate from stored state. It runs no commands,
// records no events, and re-checks only what a corrupt row could break.
func Reconstitute(s Snapshot) (*Order, error) {
	switch s.Status {
	case Draft, Placed, Paid, Cancelled:
	default:
		return nil, fmt.Errorf("%w: %q", ErrBadStatus, s.Status)
	}
	if s.Status != Draft && len(s.Lines) == 0 {
		return nil, fmt.Errorf("%w: %s has no lines", ErrBadState, s.ID)
	}
	o := &Order{id: s.ID, customer: s.Customer, currency: s.Currency, status: s.Status,
		placedAt: s.PlacedAt, version: s.Version}
	for _, l := range s.Lines {
		if l.Quantity < 1 {
			return nil, fmt.Errorf("%w: line %s quantity %d", ErrBadState, l.SKU, l.Quantity)
		}
		o.lines = append(o.lines, line{sku: l.SKU, quantity: l.Quantity, unitPrice: l.UnitPriceMinor})
	}
	return o, nil
}

The interface lives in the domain ​

go
package sales

import (
	"context"
	"errors"
)

var (
	// ErrNotFound means no aggregate has this identity.
	ErrNotFound = errors.New("order not found")
	// ErrConcurrentModification means the stored version moved since we loaded
	// the aggregate. Reload, re-run the command, save again.
	ErrConcurrentModification = errors.New("order was modified concurrently")
)

// OrderRepository is the persistence-oriented repository of the Order
// aggregate. One interface per aggregate root; no LineRepository exists.
// It lives in the domain package; implementations live in infrastructure.
type OrderRepository interface {
	// Get loads the whole aggregate or returns ErrNotFound.
	Get(ctx context.Context, id OrderID) (*Order, error)
	// Save stores the whole aggregate and its pending events. A new aggregate
	// (Version 0) is inserted; an existing one is updated only if the stored
	// version still equals o.Version(), otherwise ErrConcurrentModification.
	// Save never commits a transaction the caller opened.
	Save(ctx context.Context, o *Order) error
	// Remove deletes the aggregate and everything inside it.
	Remove(ctx context.Context, id OrderID) error
	// FindSatisfying returns aggregates matching a domain specification.
	FindSatisfying(ctx context.Context, spec Spec) ([]*Order, error)
}

Two implementations, one contract ​

go
// Package memory is the in-memory OrderRepository used by unit tests and by
// the contract tests. It stores copies (snapshots), never the live pointer,
// so it behaves like a database: mutating a loaded order changes nothing
// until Save.
package memory

import (
	"context"
	"sort"
	"sync"

	"academy/repositories/sales"
)

// Repository is safe for concurrent use.
type Repository struct {
	mu     sync.Mutex
	rows   map[sales.OrderID]sales.Snapshot
	events []sales.Event // what the outbox table would hold
}

// New returns an empty repository.
func New() *Repository { return &Repository{rows: map[sales.OrderID]sales.Snapshot{}} }

// Stored returns the events saved so far (test helper).
func (r *Repository) Stored() []sales.Event {
	r.mu.Lock()
	defer r.mu.Unlock()
	return append([]sales.Event(nil), r.events...)
}

func (r *Repository) Get(_ context.Context, id sales.OrderID) (*sales.Order, error) {
	r.mu.Lock()
	defer r.mu.Unlock()
	s, ok := r.rows[id]
	if !ok {
		return nil, sales.ErrNotFound
	}
	return sales.Reconstitute(clone(s))
}

func (r *Repository) Save(_ context.Context, o *sales.Order) error {
	r.mu.Lock()
	defer r.mu.Unlock()
	stored, exists := r.rows[o.ID()]
	switch {
	case !exists && o.Version() != 0:
		return sales.ErrConcurrentModification // it was removed under us
	case exists && stored.Version != o.Version():
		return sales.ErrConcurrentModification
	}
	snap := o.Snapshot()
	snap.Version = o.Version() + 1
	r.rows[o.ID()] = clone(snap)
	r.events = append(r.events, o.PendingEvents()...)
	o.Persisted(snap.Version)
	return nil
}

func (r *Repository) Remove(_ context.Context, id sales.OrderID) error {
	r.mu.Lock()
	defer r.mu.Unlock()
	if _, ok := r.rows[id]; !ok {
		return sales.ErrNotFound
	}
	delete(r.rows, id)
	return nil
}

func (r *Repository) FindSatisfying(_ context.Context, spec sales.Spec) ([]*sales.Order, error) {
	r.mu.Lock()
	defer r.mu.Unlock()
	var out []*sales.Order
	for _, s := range r.rows {
		o, err := sales.Reconstitute(clone(s))
		if err != nil {
			return nil, err
		}
		if spec.IsSatisfiedBy(o) {
			out = append(out, o)
		}
	}
	sort.Slice(out, func(i, j int) bool { return out[i].ID() < out[j].ID() })
	return out, nil
}

func clone(s sales.Snapshot) sales.Snapshot {
	s.Lines = append([]sales.LineSnapshot(nil), s.Lines...)
	return s
}
go
// Package postgres implements sales.OrderRepository with pgx. The repository
// never commits a transaction it did not start: if the caller put a pgx.Tx in
// the context (see UnitOfWork), every statement joins it; otherwise Save opens
// and commits its own short transaction.
package postgres

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgconn"
	"github.com/jackc/pgx/v5/pgxpool"

	"academy/repositories/sales"
)

// DBTX is satisfied by *pgxpool.Pool and pgx.Tx; sqlc generates the same
// interface, which is why sqlc code works inside and outside a transaction.
type DBTX interface {
	Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
	Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
	QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
}

type txKey struct{}

// UnitOfWork runs fn in one transaction; repositories called with the ctx it
// passes join that transaction. This is the application layer's tool: the
// repository itself has no Begin/Commit.
type UnitOfWork struct{ Pool *pgxpool.Pool }

// Do begins a transaction, runs fn, commits on nil and rolls back on error.
func (u UnitOfWork) Do(ctx context.Context, fn func(ctx context.Context) error) error {
	tx, err := u.Pool.Begin(ctx)
	if err != nil {
		return err
	}
	defer func() { _ = tx.Rollback(ctx) }() // no-op after Commit
	if err := fn(context.WithValue(ctx, txKey{}, tx)); err != nil {
		return err
	}
	return tx.Commit(ctx)
}

// Repository is the Postgres implementation.
type Repository struct{ pool *pgxpool.Pool }

// New returns a repository on the pool.
func New(pool *pgxpool.Pool) *Repository { return &Repository{pool: pool} }

func (r *Repository) db(ctx context.Context) DBTX {
	if tx, ok := ctx.Value(txKey{}).(pgx.Tx); ok {
		return tx
	}
	return r.pool
}

func (r *Repository) Get(ctx context.Context, id sales.OrderID) (*sales.Order, error) {
	db := r.db(ctx)
	var s sales.Snapshot
	var placed *time.Time
	err := db.QueryRow(ctx, `SELECT id, customer_id, currency, status, placed_at, version FROM orders WHERE id = $1`, string(id)).
		Scan(&s.ID, &s.Customer, &s.Currency, &s.Status, &placed, &s.Version)
	if errors.Is(err, pgx.ErrNoRows) {
		return nil, sales.ErrNotFound
	}
	if err != nil {
		return nil, err
	}
	if placed != nil {
		s.PlacedAt = *placed
	}
	lines, err := r.lines(ctx, db, []string{string(id)})
	if err != nil {
		return nil, err
	}
	s.Lines = lines[id]
	return sales.Reconstitute(s)
}

func (r *Repository) lines(ctx context.Context, db DBTX, ids []string) (map[sales.OrderID][]sales.LineSnapshot, error) {
	rows, err := db.Query(ctx, `SELECT order_id, sku, quantity, unit_price_minor FROM order_lines WHERE order_id = ANY($1::text[]) ORDER BY order_id, sku`, ids)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	out := map[sales.OrderID][]sales.LineSnapshot{}
	for rows.Next() {
		var oid sales.OrderID
		var l sales.LineSnapshot
		if err := rows.Scan(&oid, &l.SKU, &l.Quantity, &l.UnitPriceMinor); err != nil {
			return nil, err
		}
		out[oid] = append(out[oid], l)
	}
	return out, rows.Err()
}

func (r *Repository) Save(ctx context.Context, o *sales.Order) error {
	if _, inTx := ctx.Value(txKey{}).(pgx.Tx); !inTx {
		// Standalone call: open our own short transaction and join it.
		return UnitOfWork{Pool: r.pool}.Do(ctx, func(ctx context.Context) error { return r.Save(ctx, o) })
	}
	db := r.db(ctx)
	s := o.Snapshot()
	var placed *time.Time
	if !s.PlacedAt.IsZero() {
		placed = &s.PlacedAt
	}
	next := s.Version + 1
	if s.Version == 0 {
		_, err := db.Exec(ctx, `INSERT INTO orders (id, customer_id, currency, status, placed_at, version) VALUES ($1,$2,$3,$4,$5,1)`,
			string(s.ID), string(s.Customer), s.Currency, string(s.Status), placed)
		var pgErr *pgconn.PgError
		if errors.As(err, &pgErr) && pgErr.Code == "23505" { // unique_violation: someone inserted the same id
			return sales.ErrConcurrentModification
		}
		if err != nil {
			return err
		}
	} else {
		tag, err := db.Exec(ctx, `UPDATE orders SET customer_id=$2, currency=$3, status=$4, placed_at=$5, version=version+1 WHERE id=$1 AND version=$6`,
			string(s.ID), string(s.Customer), s.Currency, string(s.Status), placed, s.Version)
		if err != nil {
			return err
		}
		if tag.RowsAffected() == 0 { // stale version, or the row is gone
			return sales.ErrConcurrentModification
		}
	}
	// The aggregate is stored whole: replace its internal rows.
	if _, err := db.Exec(ctx, `DELETE FROM order_lines WHERE order_id = $1`, string(s.ID)); err != nil {
		return err
	}
	for _, l := range s.Lines {
		if _, err := db.Exec(ctx, `INSERT INTO order_lines (order_id, sku, quantity, unit_price_minor) VALUES ($1,$2,$3,$4)`,
			string(s.ID), string(l.SKU), l.Quantity, l.UnitPriceMinor); err != nil {
			return err
		}
	}
	// Events go to the outbox in the same transaction (no broker call here).
	for _, e := range o.PendingEvents() {
		topic, ok := outboxTopics[e.EventName()]
		if !ok {
			return fmt.Errorf("no published topic for %s", e.EventName())
		}
		payload, err := json.Marshal(e)
		if err != nil {
			return err
		}
		if _, err := db.Exec(ctx, `INSERT INTO outbox (topic, payload) VALUES ($1, $2)`, topic, payload); err != nil {
			return err
		}
	}
	o.Persisted(next) // only after every statement succeeded
	return nil
}

// outboxTopics maps domain event class names to the dotted, versioned topic
// of the published language. Only the outbox row carries the wire name.
var outboxTopics = map[string]string{
	"OrderPlaced": "sales.order.placed.v1",
}

func (r *Repository) Remove(ctx context.Context, id sales.OrderID) error {
	tag, err := r.db(ctx).Exec(ctx, `DELETE FROM orders WHERE id = $1`, string(id)) // lines go by ON DELETE CASCADE
	if err != nil {
		return err
	}
	if tag.RowsAffected() == 0 {
		return sales.ErrNotFound
	}
	return nil
}

func (r *Repository) FindSatisfying(ctx context.Context, spec sales.Spec) ([]*sales.Order, error) {
	where, args, err := toSQL(spec, 1)
	if err != nil {
		return nil, err
	}
	db := r.db(ctx)
	rows, err := db.Query(ctx, `SELECT id, customer_id, currency, status, placed_at, version FROM orders WHERE `+where+` ORDER BY id`, args...)
	if err != nil {
		return nil, err
	}
	var snaps []sales.Snapshot
	var ids []string
	for rows.Next() {
		var s sales.Snapshot
		var placed *time.Time
		if err := rows.Scan(&s.ID, &s.Customer, &s.Currency, &s.Status, &placed, &s.Version); err != nil {
			rows.Close()
			return nil, err
		}
		if placed != nil {
			s.PlacedAt = *placed
		}
		snaps = append(snaps, s)
		ids = append(ids, string(s.ID))
	}
	rows.Close()
	if err := rows.Err(); err != nil {
		return nil, err
	}
	if len(snaps) == 0 {
		return nil, nil
	}
	lines, err := r.lines(ctx, db, ids) // one query for all lines, not one per order
	if err != nil {
		return nil, err
	}
	out := make([]*sales.Order, 0, len(snaps))
	for _, s := range snaps {
		s.Lines = lines[s.ID]
		o, err := sales.Reconstitute(s)
		if err != nil {
			return nil, fmt.Errorf("order %s: %w", s.ID, err)
		}
		out = append(out, o)
	}
	return out, nil
}
sql
CREATE TABLE orders (
    id          text        PRIMARY KEY,
    customer_id text        NOT NULL,
    currency    char(3)     NOT NULL,
    status      text        NOT NULL CHECK (status IN ('draft','placed','paid','cancelled')),
    placed_at   timestamptz,
    version     integer     NOT NULL DEFAULT 1
);
CREATE TABLE order_lines (
    order_id         text    NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
    sku              text    NOT NULL,
    quantity         integer NOT NULL CHECK (quantity >= 1),
    unit_price_minor bigint  NOT NULL,
    PRIMARY KEY (order_id, sku)
);
-- Written in the SAME transaction as the aggregate (see the outbox chapter).
CREATE TABLE outbox (
    id         bigserial   PRIMARY KEY,
    topic      text        NOT NULL,
    payload    jsonb       NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX orders_status_placed_at ON orders (status, placed_at);
CREATE INDEX orders_customer ON orders (customer_id);
go
package memory_test

import (
	"testing"

	"academy/repositories/memory"
	"academy/repositories/repotest"
	"academy/repositories/sales"
)

// The same contract the Postgres repository must pass.
func TestMemoryRepositoryContract(t *testing.T) {
	repotest.Run(t, func(t *testing.T) sales.OrderRepository { return memory.New() })
}
go
package postgres_test

import (
	"context"
	"os"
	"testing"

	"github.com/jackc/pgx/v5/pgxpool"

	"academy/repositories/postgres"
	"academy/repositories/repotest"
	"academy/repositories/sales"
)

// Runs only when DATABASE_URL points at a Postgres that already has
// schema.sql applied. Expected, not run in this chapter's build.
func TestPostgresRepositoryContract(t *testing.T) {
	url := os.Getenv("DATABASE_URL")
	if url == "" {
		t.Skip("DATABASE_URL not set")
	}
	pool, err := pgxpool.New(context.Background(), url)
	if err != nil {
		t.Fatal(err)
	}
	defer pool.Close()
	repotest.Run(t, func(t *testing.T) sales.OrderRepository {
		if _, err := pool.Exec(context.Background(), `TRUNCATE orders, outbox CASCADE`); err != nil {
			t.Fatal(err)
		}
		return postgres.New(pool)
	})
}

The unit test of a use case, with no database ​

go
package app_test

import (
	"context"
	"testing"
	"time"

	"academy/repositories/app"
	"academy/repositories/memory"
	"academy/repositories/sales"
)

// passthrough is a fake Tx: unit tests of the use case need no database.
type passthrough struct{}

func (passthrough) Do(ctx context.Context, fn func(context.Context) error) error { return fn(ctx) }

func TestPlaceOrderSavesAndRecordsEvent(t *testing.T) {
	ctx := context.Background()
	repo := memory.New()
	o := sales.NewOrder("o-1", "c-1", "EUR")
	_ = o.AddLine("s", 1, 100)
	_ = repo.Save(ctx, o)

	h := app.PlaceOrder{Tx: passthrough{}, Orders: repo, Now: func() time.Time { return time.Unix(0, 0) }}
	if err := h.Handle(ctx, "o-1"); err != nil {
		t.Fatal(err)
	}
	got, _ := repo.Get(ctx, "o-1")
	if got.Status() != sales.Placed {
		t.Fatalf("status = %s", got.Status())
	}
	if len(repo.Stored()) != 1 {
		t.Fatalf("stored events = %d", len(repo.Stored()))
	}
}

func TestPlaceOrderTwiceFailsInTheDomain(t *testing.T) {
	ctx := context.Background()
	repo := memory.New()
	o := sales.NewOrder("o-1", "c-1", "EUR")
	_ = o.AddLine("s", 1, 100)
	_ = repo.Save(ctx, o)
	h := app.PlaceOrder{Tx: passthrough{}, Orders: repo, Now: time.Now}
	if err := h.Handle(ctx, "o-1"); err != nil {
		t.Fatal(err)
	}
	if err := h.Handle(ctx, "o-1"); err == nil {
		t.Fatal("second place must fail")
	}
}

The Go angle ​

  • Interfaces are consumer-side. Define OrderRepository in sales (the consumer), not in the Postgres package; the Postgres package imports sales, never the reverse.
  • Accept interfaces, return structs applies to constructors (postgres.New returns *Repository), while the application layer holds the interface.
  • context.Context first, always; the transaction rides on it in our version.
  • Sentinel errors (ErrNotFound, ErrConcurrentModification) compare with errors.Is; the use case maps them to HTTP 404 and 409.
  • No generics for repositories. Repository[T any] compiles, but it erases exactly the per-aggregate differences you want.
  • sqlc over an ORM when the schema is yours; GORM or ent when you want less SQL, but the mapping to the domain object is still your code.
  • Struct copies are cheap. Return a fresh *Order from Get; do not hand out a pointer into a cache.

Laravel ​

The snippets are PHP 8.4 for Laravel 13 and are reviewed and syntax-checked (php -l), the in-memory repository is smoke-run without the framework; the database-backed repositories are not run here.

Domain: aggregate, interface, specifications ​

php
<?php

declare(strict_types=1);

namespace App\Sales\Domain;

/**
 * Persistence-oriented repository of the Order aggregate: one per aggregate
 * root, whole aggregates in and out, no Builder, no table names.
 * Implementations never commit a transaction the caller opened.
 */
interface OrderRepository
{
    /** @throws OrderNotFound */
    public function get(string $id): Order;

    /**
     * Insert (version 0) or update-if-version-matches.
     *
     * @throws ConcurrentModification when the stored version moved
     */
    public function save(Order $order): void;

    /** @throws OrderNotFound */
    public function remove(string $id): void;

    /** @return list<Order> */
    public function findSatisfying(OrderSpecification $spec): array;
}
php
<?php

declare(strict_types=1);

namespace App\Sales\Domain;

use DateTimeImmutable;

/** The domain-language query "placed, still unpaid after N seconds". */
final class UnpaidLongerThan
{
    public static function spec(DateTimeImmutable $now, int $ageSeconds): OrderSpecification
    {
        return new AllOf(
            new InStatus('placed'),
            new PlacedBefore($now->modify("-{$ageSeconds} seconds")),
        );
    }
}

Option 2: Eloquent maps to the domain object ​

php
<?php

declare(strict_types=1);

namespace App\Sales\Infrastructure;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * Persistence model for the orders table: a row, not the aggregate.
 * Used only inside EloquentOrderRepository.
 */
final class OrderRecord extends Model
{
    protected $table = 'orders';
    public $incrementing = false;
    protected $keyType = 'string';
    public $timestamps = false;
    protected $guarded = [];

    protected function casts(): array
    {
        return ['placed_at' => 'datetime', 'version' => 'integer'];
    }

    public function lines(): HasMany
    {
        return $this->hasMany(OrderLineRecord::class, 'order_id');
    }
}
php
<?php

declare(strict_types=1);

namespace App\Sales\Infrastructure;

use App\Sales\Domain\AllOf;
use App\Sales\Domain\AnyOf;
use App\Sales\Domain\ConcurrentModification;
use App\Sales\Domain\ForCustomer;
use App\Sales\Domain\InStatus;
use App\Sales\Domain\Not;
use App\Sales\Domain\Order;
use App\Sales\Domain\OrderNotFound;
use App\Sales\Domain\OrderRepository;
use App\Sales\Domain\OrderSpecification;
use App\Sales\Domain\PlacedBefore;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;

/**
 * Option 2: Eloquent is the mapper, the domain object is the aggregate.
 * Eloquent models never leave this class. Joins the caller's transaction
 * (DB::transaction in the application service); it never commits one.
 */
final class EloquentOrderRepository implements OrderRepository
{
    public function get(string $id): Order
    {
        $record = OrderRecord::query()->with('lines')->find($id);
        if ($record === null) {
            throw new OrderNotFound($id);
        }

        return $this->toDomain($record);
    }

    public function save(Order $order): void
    {
        $s = $order->snapshot();
        $attrs = [
            'customer_id' => $s['customer_id'],
            'currency' => $s['currency'],
            'status' => $s['status'],
            'placed_at' => $s['placed_at'],
        ];

        // Inside the application service's DB::transaction this becomes a nested
        // transaction (Laravel issues a SAVEPOINT); standalone it is our own.
        DB::transaction(function () use ($s, $attrs, $order): void {
            if ($s['version'] === 0) {
                OrderRecord::query()->insert(['id' => $s['id'], 'version' => 1] + $attrs);
            } else {
                $updated = OrderRecord::query()
                    ->whereKey($s['id'])
                    ->where('version', $s['version'])
                    ->update($attrs + ['version' => $s['version'] + 1]);
                if ($updated === 0) {
                    throw new ConcurrentModification($s['id']);
                }
            }

            OrderLineRecord::query()->where('order_id', $s['id'])->delete();
            OrderLineRecord::query()->insert(array_map(
                fn (array $l) => ['order_id' => $s['id']] + $l,
                $s['lines'],
            ));

            foreach ($order->pendingEvents() as $event) {
                DB::table('outbox')->insert([
                    'topic' => OutboxTopics::for($event),
                    'payload' => json_encode($event, JSON_THROW_ON_ERROR),
                    'created_at' => now(),
                ]);
            }
        });

        $order->persisted($s['version'] + 1); // only after the transaction succeeded
    }

    public function remove(string $id): void
    {
        if (OrderRecord::query()->whereKey($id)->delete() === 0) { // lines: ON DELETE CASCADE
            throw new OrderNotFound($id);
        }
    }

    public function findSatisfying(OrderSpecification $spec): array
    {
        $query = OrderRecord::query()->with('lines'); // one extra query, not N+1
        $query->where(fn (Builder $q) => $this->apply($q, $spec));

        return $query->orderBy('id')->get()->map(fn (OrderRecord $r) => $this->toDomain($r))->all();
    }

    /** Translate known specs to SQL; refuse anything else loudly. */
    private function apply(Builder $q, OrderSpecification $spec): void
    {
        match (true) {
            $spec instanceof ForCustomer => $q->where('customer_id', $spec->customerId),
            $spec instanceof InStatus => $q->where('status', $spec->status),
            $spec instanceof PlacedBefore => $q->where('placed_at', '<', $spec->at->format('Y-m-d H:i:s')),
            $spec instanceof Not => $q->whereNot(fn (Builder $n) => $this->apply($n, $spec->spec)),
            $spec instanceof AllOf => $q->where(function (Builder $n) use ($spec): void {
                foreach ($spec->specs as $s) {
                    $n->where(fn (Builder $c) => $this->apply($c, $s));
                }
            }),
            $spec instanceof AnyOf => $q->where(function (Builder $n) use ($spec): void {
                foreach ($spec->specs as $s) {
                    $n->orWhere(fn (Builder $c) => $this->apply($c, $s));
                }
            }),
            default => throw new InvalidArgumentException('cannot translate ' . $spec::class . ' to SQL'),
        };
    }

    private function toDomain(OrderRecord $r): Order
    {
        return Order::reconstitute([
            'id' => $r->id,
            'customer_id' => $r->customer_id,
            'currency' => $r->currency,
            'status' => $r->status,
            'placed_at' => $r->placed_at?->format('Y-m-d H:i:s'),
            'version' => (int) $r->version,
            'lines' => $r->lines->sortBy('sku')->map(fn (OrderLineRecord $l) => [
                'sku' => $l->sku,
                'quantity' => (int) $l->quantity,
                'unit_price_minor' => (int) $l->unit_price_minor,
            ])->values()->all(),
        ]);
    }
}

Option 3: query builder only ​

php
<?php

declare(strict_types=1);

namespace App\Sales\Infrastructure;

use App\Sales\Domain\ConcurrentModification;
use App\Sales\Domain\ForCustomer;
use App\Sales\Domain\InStatus;
use App\Sales\Domain\AllOf;
use App\Sales\Domain\Order;
use App\Sales\Domain\OrderNotFound;
use App\Sales\Domain\OrderRepository;
use App\Sales\Domain\OrderSpecification;
use App\Sales\Domain\PlacedBefore;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;

/**
 * Option 3: no Eloquent models at all. Plain query builder rows are mapped by
 * hand. Most control and fewest surprises (no hydration, no events, no
 * lazy loading), most code. Same contract as the Eloquent variant.
 */
final class QueryBuilderOrderRepository implements OrderRepository
{
    public function get(string $id): Order
    {
        $row = DB::table('orders')->where('id', $id)->first();
        if ($row === null) {
            throw new OrderNotFound($id);
        }

        return $this->hydrate($row, $this->linesFor([$id])[$id] ?? []);
    }

    public function save(Order $order): void
    {
        $s = $order->snapshot();
        $attrs = [
            'customer_id' => $s['customer_id'],
            'currency' => $s['currency'],
            'status' => $s['status'],
            'placed_at' => $s['placed_at'],
        ];

        DB::transaction(function () use ($s, $attrs, $order): void {
            if ($s['version'] === 0) {
                DB::table('orders')->insert(['id' => $s['id'], 'version' => 1] + $attrs);
            } else {
                $updated = DB::table('orders')
                    ->where('id', $s['id'])
                    ->where('version', $s['version']) // compare-and-set
                    ->update($attrs + ['version' => $s['version'] + 1]);
                if ($updated === 0) {
                    throw new ConcurrentModification($s['id']);
                }
            }
            DB::table('order_lines')->where('order_id', $s['id'])->delete();
            if ($s['lines'] !== []) {
                DB::table('order_lines')->insert(array_map(
                    fn (array $l) => ['order_id' => $s['id']] + $l,
                    $s['lines'],
                ));
            }
            foreach ($order->pendingEvents() as $event) {
                DB::table('outbox')->insert([
                    'topic' => OutboxTopics::for($event),
                    'payload' => json_encode($event, JSON_THROW_ON_ERROR),
                    'created_at' => now(),
                ]);
            }
        });

        $order->persisted($s['version'] + 1);
    }

    public function remove(string $id): void
    {
        if (DB::table('orders')->where('id', $id)->delete() === 0) {
            throw new OrderNotFound($id);
        }
    }

    public function findSatisfying(OrderSpecification $spec): array
    {
        $rows = DB::table('orders')
            ->where(fn (Builder $q) => $this->apply($q, $spec))
            ->orderBy('id')
            ->get();
        $lines = $this->linesFor($rows->pluck('id')->all());

        return $rows->map(fn (object $r) => $this->hydrate($r, $lines[$r->id] ?? []))->all();
    }

    private function apply(Builder $q, OrderSpecification $spec): void
    {
        match (true) {
            $spec instanceof ForCustomer => $q->where('customer_id', $spec->customerId),
            $spec instanceof InStatus => $q->where('status', $spec->status),
            $spec instanceof PlacedBefore => $q->where('placed_at', '<', $spec->at->format('Y-m-d H:i:s')),
            $spec instanceof AllOf => $q->where(function (Builder $n) use ($spec): void {
                foreach ($spec->specs as $s) {
                    $n->where(fn (Builder $c) => $this->apply($c, $s));
                }
            }),
            default => throw new InvalidArgumentException('cannot translate ' . $spec::class . ' to SQL'),
        };
    }

    /**
     * @param list<string> $ids
     * @return array<string, list<array{sku: string, quantity: int, unit_price_minor: int}>>
     */
    private function linesFor(array $ids): array
    {
        $out = [];
        foreach (DB::table('order_lines')->whereIn('order_id', $ids)->orderBy('sku')->get() as $l) {
            $out[$l->order_id][] = [
                'sku' => $l->sku,
                'quantity' => (int) $l->quantity,
                'unit_price_minor' => (int) $l->unit_price_minor,
            ];
        }

        return $out;
    }

    /** @param list<array{sku: string, quantity: int, unit_price_minor: int}> $lines */
    private function hydrate(object $r, array $lines): Order
    {
        return Order::reconstitute([
            'id' => $r->id,
            'customer_id' => $r->customer_id,
            'currency' => $r->currency,
            'status' => $r->status,
            'placed_at' => $r->placed_at,
            'version' => (int) $r->version,
            'lines' => $lines,
        ]);
    }
}

Option 1: Eloquent is the aggregate ​

php
<?php

declare(strict_types=1);

namespace App\Sales\EloquentAggregate;

use DomainException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * Option 1: the Eloquent model IS the aggregate. Repository is thin or absent:
 * Order::query()->with('lines')->findOrFail($id) is the "repository". The
 * price: the persistence API (save, update, delete, relations, mass
 * assignment) is public on the aggregate, so discipline replaces enforcement.
 */
final class Order extends Model
{
    protected $table = 'orders';
    public $incrementing = false;
    protected $keyType = 'string';
    public $timestamps = false;
    // Nothing is mass assignable: state changes only through the methods below.
    protected $fillable = [];

    public function lines(): HasMany
    {
        return $this->hasMany(OrderLine::class, 'order_id');
    }

    public static function draft(string $id, string $customerId, string $currency): self
    {
        $o = new self();
        $o->forceFill(['id' => $id, 'customer_id' => $customerId, 'currency' => $currency,
            'status' => 'draft', 'version' => 0]);

        return $o;
    }

    public function place(): void
    {
        if ($this->status !== 'draft') {
            throw new DomainException('only a draft order can be placed');
        }
        $this->status = 'placed';
    }

    /**
     * Optimistic save: the UPDATE carries the version we loaded.
     * Eloquent has no built-in version column, so we add the check ourselves.
     */
    public function saveWithVersion(): void
    {
        $loaded = (int) $this->getOriginal('version');
        if (!$this->exists) {
            $this->version = 1;
            $this->save();

            return;
        }
        $updated = self::query()
            ->whereKey($this->getKey())
            ->where('version', $loaded)
            ->update($this->getDirty() + ['version' => $loaded + 1]);
        if ($updated === 0) {
            throw new \App\Sales\Domain\ConcurrentModification((string) $this->getKey());
        }
        $this->version = $loaded + 1;
        $this->syncOriginal();
    }
}

Fake, application service and binding ​

php
<?php

declare(strict_types=1);

namespace App\Sales\Infrastructure;

use App\Sales\Domain\ConcurrentModification;
use App\Sales\Domain\Order;
use App\Sales\Domain\OrderNotFound;
use App\Sales\Domain\OrderRepository;
use App\Sales\Domain\OrderSpecification;

/**
 * Fake for unit tests. Stores snapshots, not live objects, so a loaded order
 * changes nothing until save() (same as a database). Passes the same contract
 * as the real repositories: see tests/OrderRepositoryContract.php.
 */
final class InMemoryOrderRepository implements OrderRepository
{
    /** @var array<string, array<string, mixed>> */
    private array $rows = [];

    /** @var list<object> what the outbox table would hold */
    public array $storedEvents = [];

    public function get(string $id): Order
    {
        if (!isset($this->rows[$id])) {
            throw new OrderNotFound($id);
        }

        return Order::reconstitute($this->rows[$id]);
    }

    public function save(Order $order): void
    {
        $s = $order->snapshot();
        $stored = $this->rows[$s['id']] ?? null;
        if (($stored === null && $s['version'] !== 0) || ($stored !== null && $stored['version'] !== $s['version'])) {
            throw new ConcurrentModification($s['id']);
        }
        $s['version']++;
        $this->rows[$s['id']] = $s;
        array_push($this->storedEvents, ...$order->pendingEvents());
        $order->persisted($s['version']);
    }

    public function remove(string $id): void
    {
        if (!isset($this->rows[$id])) {
            throw new OrderNotFound($id);
        }
        unset($this->rows[$id]);
    }

    public function findSatisfying(OrderSpecification $spec): array
    {
        $ids = array_keys($this->rows);
        sort($ids);
        $orders = array_map(fn (string $id) => Order::reconstitute($this->rows[$id]), $ids);

        return array_values(array_filter($orders, fn (Order $o) => $spec->isSatisfiedBy($o)));
    }
}
php
<?php

declare(strict_types=1);

namespace App\Sales\Application;

use App\Sales\Domain\ConcurrentModification;
use App\Sales\Domain\OrderRepository;
use DateTimeImmutable;
use Illuminate\Support\Facades\DB;

/**
 * Application service: owns the transaction. The repository never commits.
 * DB::transaction(..., attempts: 3) retries only on deadlocks, so the
 * optimistic-lock retry is an explicit loop around it.
 */
final class PlaceOrderHandler
{
    public function __construct(private readonly OrderRepository $orders)
    {
    }

    public function handle(string $orderId): void
    {
        for ($attempt = 1; ; $attempt++) {
            try {
                DB::transaction(function () use ($orderId): void {
                    $order = $this->orders->get($orderId);
                    $order->place(new DateTimeImmutable());
                    $this->orders->save($order); // aggregate + outbox row, one commit
                });

                return;
            } catch (ConcurrentModification $e) {
                if ($attempt >= 3) {
                    throw $e;
                }
            }
        }
    }
}
php
<?php

declare(strict_types=1);

namespace App\Providers;

use App\Sales\Domain\OrderRepository;
use App\Sales\Infrastructure\EloquentOrderRepository;
use Illuminate\Support\ServiceProvider;

final class SalesServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // Swap the binding to QueryBuilderOrderRepository or, in tests, to
        // InMemoryOrderRepository; callers only know the interface.
        $this->app->bind(OrderRepository::class, EloquentOrderRepository::class);
    }
}
php
<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('orders', function (Blueprint $t): void {
            $t->string('id')->primary();
            $t->string('customer_id')->index();
            $t->char('currency', 3);
            $t->string('status');
            $t->timestamp('placed_at')->nullable();
            $t->unsignedInteger('version')->default(1);
            $t->index(['status', 'placed_at']);
        });
        Schema::create('order_lines', function (Blueprint $t): void {
            $t->string('order_id');
            $t->string('sku');
            $t->unsignedInteger('quantity');
            $t->bigInteger('unit_price_minor');
            $t->primary(['order_id', 'sku']);
            $t->foreign('order_id')->references('id')->on('orders')->cascadeOnDelete();
        });
        // Written in the same transaction as the aggregate (outbox chapter).
        Schema::create('outbox', function (Blueprint $t): void {
            $t->id();
            $t->string('topic');
            $t->json('payload');
            $t->timestamp('created_at');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('outbox');
        Schema::dropIfExists('order_lines');
        Schema::dropIfExists('orders');
    }
};
php
<?php

declare(strict_types=1);

namespace Tests\Sales;

use App\Sales\Domain\OrderRepository;
use App\Sales\Infrastructure\EloquentOrderRepository;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

/**
 * The same contract against a real database. RefreshDatabase runs each test
 * inside a transaction (Laravel 13 docs), which is another reason repositories
 * must never commit on their own.
 */
final class EloquentOrderRepositoryTest extends TestCase
{
    use OrderRepositoryContract;
    use RefreshDatabase;

    protected function repository(): OrderRepository
    {
        return new EloquentOrderRepository();
    }
}

The Laravel angle ​

  • Eloquent is Active Record, so the aggregate-as-model option couples domain and storage; see Data Persistence Design for the debate.
  • $fillable = [] (or $guarded = ['*']) on aggregate-like models forces state changes through methods.
  • with('lines') eager loads in one extra query and is the Eloquent answer to N+1; Model::preventLazyLoading() can turn lazy loads into errors in development (check the Laravel 13 Eloquent docs for the exact call before adopting it).
  • DB::transaction(fn, attempts: n) retries deadlocks only; the version-conflict retry is your loop.
  • Nested DB::transaction creates a savepoint, so a repository can wrap its own writes in DB::transaction and still join the handler's.
  • lockForUpdate() gives a pessimistic alternative to the version column for hot rows; see Locks & Concurrency.
  • Service container binding ($this->app->bind(OrderRepository::class, ...)) is how tests and environments swap implementations.
  • Doctrine ORM is the PHP library with a real unit of work and identity map; if you want collection-oriented semantics in PHP, that is where they live, at the price of leaving Eloquent for that context.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost
SQL in use casesRepository interface per rootOrderRepository in the domain packageUse cases read like the businessOne class per aggregate
Lost updateVersion columnUPDATE ... WHERE version = $loadedNo locks heldRetry on conflict
Half-saved aggregateOne transaction per use caseUnitOfWork.Do, DB::transactionAtomic aggregate + outboxTransaction wiring
Slow domain testsIn-memory fake + contract testmemory.New()Milliseconds, still honestFake must be maintained
N+1 on loadTwo queries, = ANY / whereInLines loaded for all ids at onceConstant query countMapping by id
Query logic duplicatedSpecificationUnpaidLongerThanNamed rule, tested in memoryTranslator branch per spec
Lists load the worldQuery service / read modelFlat DTO queryFast, paginatedSecond read path
Domain depends on EloquentOption 2 or 3OrderRecord + mapperPure domainMapping code
Stale cacheDecorator with invalidationSnapshot cache, invalidate on SaveFaster readsComplexity
Ghost or lost eventsOutbox row in SaveSame transactionAt-least-once publishRelay process

Moving from a table gateway to a repository, step by step ​

text
     Refactor: OrderDao (CRUD per table) -> OrderRepository (one per aggregate)
1    List the use cases that touch orders and order_lines; draw the aggregate boundary on the wall
2    Write the repository interface from the use cases' needs only (Get, Save, one finder)
3    Move validation out of services into Order methods; make Order fields private
4    Add Snapshot and Reconstitute; write the contract test against the OLD code via an adapter
5    Implement the Postgres/Eloquent repository; run the contract test until green
6    Switch use cases one at a time to the interface; delete the DAO methods they stop using
7    Move list and report queries to a query service; delete Paginate/Where from the repository
8    Add the version column (expand/contract), then enable the check
BeforeAfter
OrderDao.UpdateStatus(id, "paid")order.MarkPaid() then orders.Save(order)
LineDao.SetQty(id, sku, 5)order.AddLine(sku, 5, price)
OrderDao.Search(filters)OrderQueries.ListFor(customer, cursor)
repo.Query().Where(...) in a controllerNamed finder or specification
Service calls tx.Commit() after each DAOOne UnitOfWork.Do per use case

Choosing ​

SituationRecommendationExtra techniqueReason
Core domain, rich invariantsPersistence-oriented repository, mapped (Laravel option 2, Go snapshot)Contract test, version columnRules run on every change
Generic or CRUD context (Catalog admin, settings)Eloquent as the aggregate, or no repository$fillable = []A repository would add no protection
Go serviceInterface in domain, pgx or sqlc implementationFake + contract testsNo change tracking, explicit SQL
Team on Hibernate, Doctrine or EFCollection-oriented over the ORM's unit of workStill one repository per rootThe ORM already tracks
Hot read pathQuery service with a flat DTOCache, keyset paginationAggregates are for commands
Hot write row (stock counter)lockForUpdate or atomic UPDATE inside the repositoryVersion column fallbackOptimistic retries thrash on one row
Event-sourced aggregateRepository loads events and rebuildsSnapshotsState is the event stream
Reporting across contextsRead model or warehouseCDCNever a cross-context repository
Large aggregate (hundreds of children)Reconsider the boundarySmaller aggregates, reference by idWhole-aggregate load does not scale
Legacy table schemaOption 3 or a persistence modelView, mapperDomain stays clean

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

The everyday example is the online shop's checkout. PlaceOrderHandler opens DB::transaction, the repository loads the Order, the domain places it, the repository saves the order, its lines and an outbox row in the same transaction. Repositories are in-process objects; Get and Save are single-digit-millisecond queries on one PostgreSQL. Concurrency conflicts are rare and handled by a three-attempt loop. Everything in the database chapters (isolation, locks, connection pools) applies directly: see Connection Pooling.

Modular monolith and multiple databases ​

Each bounded context (Sales, Fulfilment, Billing, Catalog, Identity) owns its repositories and its tables, usually in its own schema (sales.orders, fulfilment.shipments) with a database role per module. The rules:

RuleExampleWhy
One repository per aggregate root, inside its contextsales.OrderRepository, fulfilment.ShipmentRepositoryOwnership is visible in imports
No repository crosses a contextFulfilment never calls sales.OrderRepositoryCross-context data via a published API or event
No joins across schemas in repositoriesFulfilment keeps order_id as an id, not a foreign key into salesContexts can be split later
Cross-context reads use a query interfacecatalog.PriceLookupContract, not tables
Architecture testsPest arch(), Go go list import testRules enforced in CI

See Modular Monolith and Data Ownership. The fake repository per context makes module tests independent.

Microservices: one repository per aggregate inside the service ​

When Sales and Fulfilment become services, repositories do not move; they stay inside their service, and the other side is reached by API or event (Service Communication, Service Boundaries).

text
     Production example: order placed -> shipment created (two services, two databases)
1    Sales: POST /orders/42/placement
2    Sales: BEGIN; orders.Get(42); order.Place(); orders.Save(order)  -- orders + lines + outbox row
3    Sales: COMMIT
4    Sales relay: outbox row -> broker  topic sales.order.placed.v1
5    Fulfilment consumer: inbox dedup on event id
6    Fulfilment: BEGIN; shipment := NewShipment(orderID); shipments.Save(shipment); COMMIT
7    Fulfilment never touches sales.orders; it keeps order_id and the lines it needs from the event
Cross-service needWrongRight
Fulfilment wants order linesQuery Sales' table through a shared repositoryEvent carries lines, or Sales offers GET /orders/{id}
Billing wants the totalImport sales.OrderRepositoryEvent carries total; Billing stores its own invoice
Sales wants stockJoin inventory.stockInventory API or a local read copy
Atomic multi-service changeDistributed transaction in SaveSaga (Saga Pattern)

Distributed data: replicas, caches and multi-region ​

SituationEffect on repositoriesMitigation
Read replicasGet from a replica may be stale, then Save conflicts on versionCommand path reads the primary; list queries use replicas (Replication & Failover)
Cache in front of GetStale aggregateSnapshot cache + invalidate + version check
Sharded databaseAn aggregate must not span shardsShard key = aggregate id or tenant id (Partitioning & Sharding)
Multi-region active-activeSame aggregate written in two regionsRoute writes for one aggregate to one region, or use CRDT/merge in the model
Outbox relay duplicatesConsumers see an event twiceIdempotent consumers with an inbox
FailoverLast committed write may be older on the new primaryHandle ErrConcurrentModification and re-run commands; commands must be idempotent

Scaling path: 1x, 10x, 100x ​

LoadRepository shapeWhat changes
1xMapped repository, replace-children Save, no cacheNothing special
10xDiff children instead of replace, indexed finders, read models for lists, replica for queriesQuery service appears
100xSnapshot cache decorator on hot aggregates, partitioned tables, per-tenant shards, outbox via CDCAggregate boundaries re-examined; hot rows get atomic UPDATE or pessimistic lock
BeyondEvent-sourced aggregates for the busiest, snapshots every N eventsDifferent repository implementation behind the same interface

Lab: one contract, three implementations ​

Expected, not run: the Postgres steps need a database; the in-memory steps were run.

text
     Setup
1    cd docs/snippets/ddd/repositories/go
2    go vet ./... && go test ./...
     ok  academy/repositories/memory    ... contract passes against the in-memory repository
     ok  academy/repositories/style     ... collection-oriented machinery
3    createdb repos_lab && psql repos_lab -f postgres/schema.sql
4    DATABASE_URL=postgres://localhost/repos_lab go test ./postgres -run Contract -v
     expected: the same seven sub-tests pass against Postgres
text
     Experiments
1    Break the fake on purpose: make memory.Save skip the version check.
     expected: "stale save fails with ErrConcurrentModification" fails; the contract caught the drift
2    Run two psql sessions: both BEGIN, both SELECT version FROM orders WHERE id='o-3' (4); A updates WHERE version=4 and commits; B updates WHERE version=4
     expected: B reports UPDATE 0
3    Remove the outbox insert from Save. Run the app test.
     expected: TestPlaceOrderSavesAndRecordsEvent fails: stored events = 0
4    Add a new spec (PlacedAfter) without a translator branch and call FindSatisfying on Postgres
     expected: ErrUnsupportedSpec, not a full table scan
5    Wrap with cache.Wrap and run the contract
     expected: pass; then comment out the invalidation in Save: TestSaveInvalidatesCache fails
sql
-- Experiment 2 (two psql sessions)
-- A: BEGIN; SELECT version FROM orders WHERE id = 'o-3';          -- 4
-- B: BEGIN; SELECT version FROM orders WHERE id = 'o-3';          -- 4
-- A: UPDATE orders SET status='paid', version=version+1 WHERE id='o-3' AND version=4;  -- UPDATE 1
-- A: COMMIT;
-- B: UPDATE orders SET status='cancelled', version=version+1 WHERE id='o-3' AND version=4;  -- UPDATE 0
-- B: ROLLBACK;  -- application reloads and retries

For Laravel: php artisan migrate, then php artisan test --filter=OrderRepositoryTest; the in-memory, Eloquent and query-builder test classes share one trait (expected, not run here).

Common misconceptions ​

BeliefReality
"A repository is a DAO with a nicer name"A DAO is per table with CRUD; a repository is per aggregate root with domain finders
"Every entity needs a repository"Only aggregate roots; lines are reached through the root
"The repository has no Save in DDD"That is the collection-oriented style, which needs change tracking; Go and Eloquent use Save
"Save should commit"The application service owns the transaction; the repository joins it
"Repositories exist to swap databases"They exist to keep persistence out of the model; swapping is a side effect
"A generic Repository<T> saves code"It erases aggregate semantics and invites Where/Raw leaks
"Return Eloquent models from the repository, that is fine"Then save() and relations are public; it is option 1, with option 1's costs
"Mocks are as good as fakes"A fake with a contract test catches behavioural drift; mocks check only calls
"A transaction prevents lost updates"Not under READ COMMITTED; use a version column or lock
"Pagination belongs in the repository"Lists are a query concern; use a query service
"Cache the aggregate object"Cache a snapshot and return fresh instances
"Publish events from Save"Store them in the outbox in the same transaction; publish later

Cheat sheet ​

TopicWhat to remember
ScopeOne repository per aggregate root, whole aggregates in and out
Interface homeDomain package; implementations in infrastructure
Minimum methodsGet, Save, Remove (if needed), one or two domain finders
StylePersistence-oriented in Go and Eloquent; collection-oriented only with a real unit of work
Not in itLists, pagination, reports, Where, Raw, Builder
TransactionsApplication service begins and commits; repository joins
Concurrencyversion column; UPDATE ... WHERE version = $loaded; 0 rows is a conflict
ReconstitutionSeparate from the factory; no commands, no events
SpecificationNamed, composable; translate known specs, reject unknown
LaravelOption 1 for CRUD, option 2 for core, option 3 for hot paths
TestingFake plus one shared contract test
EventsAggregate records; Save stores in outbox; relay publishes
CacheSnapshot decorator, invalidate on write, keep the version check
Context ruleNo repository crosses a bounded context

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why is there no OrderLineRepository? Must-know ​

Answer

Answer: Lines are inside the Order aggregate. Saving or loading them alone would bypass the root's invariants (line limits, totals, state checks). Only the root has a door.

2 — What is the difference between a collection-oriented and a persistence-oriented repository, and which fits Go? Important ​

Answer

Answer: Collection-oriented offers Add/Remove and relies on a unit of work to notice changes; persistence-oriented offers Save and the caller must call it. Go has no persistence context, so persistence-oriented (or a hand-built unit of work) fits.

3 — Why should Save not commit? Must-know ​

Answer

Answer: The use case may save several rows or aggregates plus an outbox row; committing inside Save breaks atomicity. The application service owns the unit of work.

4 — How does Save detect a concurrent change? Important ​

Answer

Answer: The aggregate carries a version. UPDATE ... WHERE id = $1 AND version = $loaded affects zero rows if another transaction saved first; the repository returns ErrConcurrentModification.

5 — Does DB::transaction($cb, attempts: 3) retry a version conflict? Important ​

Answer

Answer: No. The Laravel docs describe attempts as the retry count when a deadlock occurs. A ConcurrentModification from your repository needs an explicit retry loop around the transaction.

6 — Why use a separate Reconstitute instead of the constructor? Important ​

Answer

Answer: Creation rules and creation events must not run when loading stored state. Reconstitution trusts the stored state, validates only what corruption could break, and records no events.

7 — When is Eloquent-as-the-aggregate acceptable? Good to know ​

Answer

Answer: In a generic or CRUD-heavy context with few invariants, where a mapped repository would add code but no protection. Keep $fillable empty and add domain methods.

8 — Why a fake plus a contract test rather than a mock? Important ​

Answer

Answer: A fake has real behaviour (versions, copies, errors); the contract test runs the same cases against fake and real repositories so the fake cannot drift. A mock only verifies scripted calls.

9 — Where does "page 3 of the order list" belong? Must-know ​

Answer

Answer: In a query service or read model returning flat DTOs with keyset pagination, not in the repository.

10 — Why must a repository never call another context's repository? Must-know ​

Answer

Answer: It couples contexts through each other's models and tables, blocking later extraction. Use a published API, an event, or a local read copy.

11 — How does an event recorded by the aggregate reach a broker safely? Must-know ​

Answer

Answer: Save inserts an outbox row in the same transaction; a relay publishes after commit; consumers deduplicate with an inbox.

Glossary ​

TermMeaning
RepositoryA collection-like interface for loading and storing whole aggregates of one root type
Aggregate rootThe entity through which an aggregate is reached and changed
Collection-oriented repositoryRepository with Add/Remove and no save; relies on change tracking
Persistence-oriented repositoryRepository with an explicit Save
Unit of workThe set of changes committed together; owned by the application service
Identity mapA per-session cache ensuring one instance per identity
Change trackingDetecting modified objects by comparing snapshots, done by Hibernate, Doctrine, EF Core
SpecificationA named domain rule with IsSatisfiedBy, composable with And, Or, Not
SubsumptionComparing specifications to see whether one implies another
ReconstitutionRebuilding an aggregate from stored state without running commands
Snapshot / mementoA flat copy of aggregate state crossing the persistence boundary
Optimistic concurrencyDetecting competing writes with a version check instead of locks
Version columnInteger incremented on each save, used in the WHERE clause
Lost updateA write silently overwriting a concurrent write
Read modelA query-only data shape built for a screen or report
Query serviceA class that runs SQL and returns flat DTOs, outside the repository
DAOData access object: per-table CRUD, not aggregate-shaped
Active RecordA model that is also its own row and persistence API (Eloquent)
Data MapperA mapper that moves data between domain objects and rows
FakeA lightweight working implementation used in tests
Contract testOne test suite run against every implementation of an interface
OutboxA table written in the same transaction as the state, relayed to a broker
sqlcA tool that generates type-safe Go from SQL queries
pgxThe PostgreSQL driver and toolkit for Go
DBTXThe interface satisfied by both a pool and a transaction
SavepointA nested transaction marker; Laravel uses it for nested DB::transaction
ErrConcurrentModificationThe sentinel error for a stale-version save

References ​

Built by Morteza Negahi