ArchitectureIntermediate

Repository, Unit of Work & CQRS: Spring, NestJS, FastAPI

DeveloperHat Team
23 min read

TL;DR

Repository, Unit of Work and CQRS in Spring Boot, NestJS and FastAPI — real code, the framework built-ins, and when each pattern earns its keep.

Three patterns show up in almost every backend that outgrows its first CRUD endpoints, and they are constantly confused with each other because they all sit between the service layer and the database. They solve three different problems. The Repository hides how data is stored, so the domain talks to a collection instead of SQL. The Unit of Work makes several writes land together or not at all, so a half-finished order can never exist. CQRS splits reads from writes, so a list screen can have its own shape without warping the write model. All three come from Martin Fowler's Patterns of Enterprise Application Architecture (Addison-Wesley, 2002) — Repository and Unit of Work as catalogued patterns — and CQRS from Greg Young's formulation, described in Fowler's CQRS bliki.

This article builds the same order-placement example three times — placing an order that reserves stock — in Spring Boot, in NestJS with TypeORM, and in FastAPI with SQLAlchemy 2.0. Same shape, different idioms. The short version up front: adopt Repository plus Unit of Work as soon as a use case writes more than one aggregate; adopt CQRS-lite — split read and write models on the same store — when the read shape diverges from the write shape; and reserve full CQRS, with separate stores and eventual consistency, for the day reads and writes genuinely need to scale apart. Most services never reach that day.

WRITE SIDE — COMMANDS Command handler one handler per use case Repository a collection of aggregates Unit of Work one transaction, one commit READ SIDE — QUERIES Query handler one handler per question Read model shaped for the screen, not the table Denormalised view fast reads, rebuilt from events CQRS splits the paths; Repository and Unit of Work keep the write side honest.

Repository: hide the database behind a collection

A Repository, in Fowler's definition, mediates between the domain and the data-mapping layers using a collection-like interface for accessing domain objects. The caller adds, removes, and queries objects as if they were already in memory; the repository decides how that maps to tables, queries, and indexes. The test for whether you have a repository or a thin wrapper around SQL is simple: can the service code be read without knowing which database is underneath? If the answer is yes, the boundary is doing its job.

One discipline matters more than any framework choice: one repository per aggregate, not one per table. An order and its lines are one aggregate — they change together, they are saved together, and nobody outside the order should reach into its lines directly. A repository per table collapses into a data-access layer with a fancier name, and the aggregate boundary it was supposed to protect disappears.

Repository in Spring Boot: Spring Data JPA writes it for you

Spring Data JPA is the built-in version of the pattern, and it is the strongest argument for it in the Java world: you declare an interface, and the framework supplies the implementation, the query derivation, and the transaction participation. The Spring Data JPA reference documents the full contract.

// Spring Data JPA: the interface IS the repository.
// Spring generates the implementation, including the derived query.
public interface OrderRepository extends JpaRepository<Order, Long> {
    List<Order> findByCustomerIdAndCompleteTrue(Long customerId);
}

JpaRepository already supplies save(), findById(), delete(), and paging; the derived query findByCustomerIdAndCompleteTrue is generated from the method name, so there is no SQL string anywhere in the service. The service depends on the interface, which is exactly the seam the pattern wants: the domain never sees a query, and the repository can be swapped for a fake in tests by implementing the same interface. The cost is the magic — derived queries fail at startup with an exception if the name is wrong, and a complex query still needs an explicit @Query annotation, which is SQL living one layer up from where it belongs. That is an acceptable trade: the magic is checked at startup, not at runtime, and @Query is still confined to the repository.

Repository in NestJS: TypeORM's repository, injected

NestJS has no repository of its own; the pattern arrives through TypeORM, wired by @nestjs/typeorm. The NestJS database techniques guide shows the standard shape: inject Repository with @InjectRepository, and the service gets the same collection-like interface Spring developers get.

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Order } from './order.entity';

@Injectable()
export class OrdersService {
  constructor(
    @InjectRepository(Order)
    private readonly orders: Repository<Order>,
  ) {}

  findOpen(customerId: number): Promise<Order[]> {
    return this.orders.find({
      where: { customerId, complete: false },
    });
  }

  place(order: Order): Promise<Order> {
    return this.orders.save(order);
  }
}

TypeORM's Repository is the framework built-in, and it is honest about what it is: find, save, remove, and a query builder for the cases the finder methods cannot express. The injection is the part worth copying — the service never constructs a repository, never imports a connection, and never sees a table name. The anti-pattern to avoid here is reaching past the repository into the query builder from the service layer: the moment a controller calls createQueryBuilder, the boundary is gone, and the service is writing SQL again with extra steps.

Repository in FastAPI: a plain class over a SQLAlchemy session

Python has no repository framework to lean on, so the pattern is a plain class — and that is a feature, not a gap. SQLAlchemy 2.0's Session is already the unit-of-work object (more on that below); the repository is a thin, explicit wrapper that names the queries the domain actually needs. The SQLAlchemy session basics document the session contract the repository wraps.

from sqlalchemy import select
from sqlalchemy.orm import Session

class OrderRepository:
    """A collection of orders. The service never sees a table or a query."""

    def __init__(self, session: Session):
        self.session = session

    def save(self, order: Order) -> Order:
        self.session.add(order)
        return order

    def find_open(self, customer_id: int) -> list[Order]:
        stmt = select(Order).where(
            Order.customer_id == customer_id,
            Order.complete.is_(False),
        )
        return list(self.session.scalars(stmt))

Two properties make this worth copying despite having no framework magic. First, the repository is the only place that knows the query shape — select(Order).where(...) appears once, and every caller goes through find_open. Second, the repository takes the session in its constructor, so the same repository works inside a request, inside a test with an in-memory database, and inside a background job. The anti-pattern here is the generic repository — BaseRepository[T] with get_all, get_by_id, create, update, delete for every entity. It looks like reuse and behaves like a leak: every aggregate gets the same five methods whether they make sense or not, and the domain-specific queries end up in the service anyway, because the generic interface has nowhere to put them.

Unit of Work: one transaction, one commit

If the Repository answers "how do I get the data", the Unit of Work answers "how do several changes land together". Fowler's definition: a Unit of Work maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems. Placing an order touches two aggregates — the order is created and the stock is decremented — and either both happen or neither does. Without a unit of work, the order can be saved while the stock decrement fails, and the system now believes it sold something it still shows as in stock.

Every stack in this article already ships a unit of work; the pattern is recognising it and drawing the boundary in the right place. The boundary belongs around the use case — one HTTP request, one command, one transaction — never around a single repository call, and never around a whole HTTP session.

Unit of Work in Spring Boot: @Transactional on the service method

Spring's built-in is @Transactional, and the rule is one annotation on the service method that owns the use case. The Spring transaction reference documents the semantics: the method runs inside a single transaction, and an unchecked exception rolls everything back.

@Service
public class OrderService {
    private final OrderRepository orders;
    private final StockRepository stock;

    public OrderService(OrderRepository orders, StockRepository stock) {
        this.orders = orders;
        this.stock = stock;
    }

    @Transactional
    public Order placeOrder(Long customerId, List<OrderLine> lines) {
        Order order = new Order(customerId, lines);
        stock.reserve(lines);       // throws if stock is short
        return orders.save(order);  // one commit, or nothing at all
    }
}

The annotation is doing the whole pattern: it opens the transaction, tracks the changes both repositories make, and commits once at the end — or rolls back when reserve throws. Two failure modes to know. First, @Transactional on a private method does nothing: Spring applies it through a proxy, and self-invocation inside the class bypasses the proxy, so the annotation must sit on a public method called from outside the bean. Second, catching the exception inside the method and returning normally commits a partial result — the rollback only happens if the exception escapes. Both are the same lesson: the transaction boundary is a contract with the framework, and it only works when the method's exit path is honest about failure.

Unit of Work in NestJS: one DataSource.transaction block

NestJS has no @Transactional of its own, so the unit of work is explicit: DataSource.transaction() runs a callback inside one transaction and hands it an EntityManager whose repositories all share that transaction. Every repository call inside the callback is part of the same commit.

import { Injectable } from '@nestjs/common';
import { DataSource, In } from 'typeorm';
import { Order } from './order.entity';
import { Stock } from './stock.entity';

@Injectable()
export class PlaceOrderService {
  constructor(private readonly dataSource: DataSource) {}

  place(customerId: number, lines: OrderLine[]): Promise<Order> {
    return this.dataSource.transaction(async (manager) => {
      const order = await manager.save(Order, new Order(customerId, lines));
      // Same transaction: if this throws, the order save rolls back too.
      await manager.decrement(
        Stock,
        { sku: In(lines.map((l) => l.sku)) },
        'quantity',
        1,
      );
      return order;
    });
  }
}

The critical detail is manager.getRepository — or, as here, manager.save and manager.decrement — rather than the injected repositories. An injected Repository is bound to the default connection, not to this transaction; using it inside the callback silently writes outside the transaction, and the "atomic" order placement is atomic in name only. That is the single most common NestJS transaction bug, and it is invisible in tests that never force a failure mid-transaction. The TypeORM documentation covers both the DataSource.transaction form and the lower-level QueryRunner form; prefer the callback form unless you need to hold a transaction across several await boundaries the callback cannot express.

Unit of Work in FastAPI: the session is the unit of work

SQLAlchemy's Session is a unit of work by design — it tracks every object you touch and writes the changes out on commit(). The FastAPI idiom is a dependency that yields a session per request, commits on success, and rolls back on failure, so the request boundary and the transaction boundary are the same line.

from fastapi import Depends, FastAPI
from sqlalchemy.orm import Session, sessionmaker

app = FastAPI()

def get_session():
    session = SessionLocal()
    try:
        yield session
        session.commit()      # one commit for the whole request
    except Exception:
        session.rollback()    # or nothing at all
        raise
    finally:
        session.close()

@app.post("/orders")
def place_order(payload: OrderCreate, session: Session = Depends(get_session)):
    orders = OrderRepository(session)
    stock = StockRepository(session)
    order = Order(customer_id=payload.customer_id, lines=payload.lines)
    stock.reserve(payload.lines)   # throws if stock is short
    return orders.save(order)

The repositories share the session, so both writes are tracked by the same unit of work and committed once by the dependency. The failure mode is a long-lived session: a session held across requests, or across a slow external call inside a request, holds database locks and grows a stale identity map. Keep the session to one request, never store it on a global, and never call an external API between the first write and the commit.

One request, five layers — SQL lives at the bottom only API / Controllers — the request enters here, nothing else Command & Query handlers — one handler per use case Unit of Work — the transaction boundary, one commit Repositories — one per aggregate, a collection, not SQL Database — the only layer that knows the tables exist Each layer depends only on the one below it — SQL never leaks above the repository.

CQRS: split the reads from the writes

CQRS — Command Query Responsibility Segregation — is the observation that the model that is good for writing is rarely the model that is good for reading. The write model enforces invariants: an order cannot be placed with no lines, stock cannot go negative. The read model answers questions: show me this customer's open orders with totals, sorted by date. Forcing one model to do both jobs produces either a write model polluted with reporting fields, or read queries that join six tables to assemble one screen. CQRS splits them: commands go through the write model, queries go through a read model shaped for the screen, and the two models are allowed to diverge.

The honest version of this pattern has three levels, and most teams should stop at the first. CQRS-lite: same database, separate read and write code paths — the read side runs its own queries and returns its own shapes. CQRS with separate stores: the write store and the read store are different databases, kept in sync by events, and reads are eventually consistent. CQRS with event sourcing: the write side stores events, not current state, and the read model is a projection rebuilt from the event log. Each level costs roughly an order of magnitude more than the one before it, and the article's recommendation is explicit about which level to pick.

CQRS in Spring Boot: split the models by hand, reach for Axon only at level three

Spring has no CQRS framework in the core, and that is fine for levels one and two: the split is a package boundary, not a library. A command package owns the write model and its repositories; a query package owns read models and their queries; the two packages never import each other. The write side is the @Transactional service from the previous section; the read side is a plain repository over a denormalised view.

// Query side: a read model shaped for the screen, not the aggregate.
public record OrderSummary(Long orderId, String customerName,
                           BigDecimal total, int lineCount) {}

public interface OrderSummaryRepository extends JpaRepository<OrderSummary, Long> {
    List<OrderSummary> findByCustomerName(String customerName);
}

When the split needs events — level two and three — the Spring ecosystem option is Axon Framework, which supplies the command bus, the event bus, and the event store, so aggregates handle commands and emit events while projectors rebuild read models. Axon is the right tool when the team has already committed to event sourcing; it is the wrong tool for a first CQRS experiment, because it imports the whole event-sourcing model — event stores, upcasters, saga management — at the same time as the split. Start with the package boundary; the framework can arrive later, and the command and query packages will not need to change when it does.

CQRS in NestJS: @nestjs/cqrs is the built-in

NestJS is the one stack of the three with a first-party CQRS package, and it is the cleanest demonstration of the pattern's shape. @nestjs/cqrs — current release 12.1.3, checked against the npm registry on November 23, 2026 — supplies a CommandBus, a QueryBus, and an EventBus, with decorators that register handlers. The NestJS CQRS recipe documents the full contract.

import { CommandHandler, ICommandHandler, EventBus } from '@nestjs/cqrs';

// The command is data, not behaviour — just the intent to place an order.
export class PlaceOrderCommand {
  constructor(
    public readonly customerId: number,
    public readonly lines: OrderLine[],
  ) {}
}

@CommandHandler(PlaceOrderCommand)
export class PlaceOrderHandler implements ICommandHandler<PlaceOrderCommand> {
  constructor(
    private readonly dataSource: DataSource,
    private readonly eventBus: EventBus,
  ) {}

  async execute(command: PlaceOrderCommand): Promise<Order> {
    const order = await this.dataSource.transaction(async (manager) => {
      const saved = await manager.save(Order, new Order(command.customerId, command.lines));
      await manager.decrement(Stock, { sku: In(command.lines.map((l) => l.sku)) }, 'quantity', 1);
      return saved;
    });
    // The write is committed; now tell the read side.
    this.eventBus.publish(new OrderPlacedEvent(order.id));
    return order;
  }
}

The query side is a separate handler that reads from the read model and never touches the write repositories:

import { IQueryHandler, QueryHandler } from '@nestjs/cqrs';

export class GetOrderSummaryQuery {
  constructor(public readonly orderId: number) {}
}

@QueryHandler(GetOrderSummaryQuery)
export class GetOrderSummaryHandler implements IQueryHandler<GetOrderSummaryQuery> {
  constructor(
    @InjectRepository(OrderSummary)
    private readonly summaries: Repository<OrderSummary>,
  ) {}

  execute(query: GetOrderSummaryQuery): Promise<OrderSummary | null> {
    return this.summaries.findOne({ where: { orderId: query.orderId } });
  }
}

Dispatch is one line on each side — commandBus.execute(new PlaceOrderCommand(...)) for writes, queryBus.execute(new GetOrderSummaryQuery(...)) for reads — and the module registers everything by importing CqrsModule. The event published after the commit is what keeps the read model fresh: a projector listens for OrderPlacedEvent and upserts the OrderSummary row. The discipline is the same as in Spring: the command handler owns the transaction, the query handler owns the read, and neither imports the other.

CQRS in FastAPI: CQRS-lite is the whole pattern

FastAPI has no CQRS package, and for most Python services it does not need one. CQRS-lite is a routing decision: write endpoints use the write repositories and return the aggregate; read endpoints run their own select() and return a Pydantic read schema that is shaped for the screen. The two sides share a database and a session factory, and nothing else.

from pydantic import BaseModel

class OrderSummary(BaseModel):
    order_id: int
    customer_name: str
    total: float
    line_count: int

@app.get("/orders/{order_id}/summary", response_model=OrderSummary)
def order_summary(order_id: int, session: Session = Depends(get_session)):
    stmt = (
        select(Order.id, Customer.name, Order.total, func.count(OrderLine.id))
        .join(Customer, Customer.id == Order.customer_id)
        .join(OrderLine, OrderLine.order_id == Order.id)
        .where(Order.id == order_id)
        .group_by(Order.id, Customer.name, Order.total)
    )
    row = session.execute(stmt).one_or_none()
    if row is None:
        raise HTTPException(status_code=404, detail="Order not found")
    return OrderSummary(order_id=row[0], customer_name=row[1],
                        total=row[2], line_count=row[3])

The read endpoint joins three tables and returns exactly the four fields the screen needs — no aggregate, no lazy loading, no serialiser walking an object graph. If the read shape later needs its own store, this endpoint is the seam: the query moves to a projector and the endpoint reads the projected table, while the write endpoint never changes. That is the point of CQRS-lite — it buys the option to split the stores later without paying for the split today.

Head-to-head: Repository vs Unit of Work vs CQRS

RepositoryUnit of WorkCQRS
Problem it solvesSQL scattered through services; no seam to test or swap persistenceSeveral writes that must land together or not at allOne model forced to serve both writes and reads
Adopt whenA second query for the same aggregate appearsA use case writes two aggregates in one requestRead shapes diverge from the write model, or reads need their own scale
What it costsOne interface + one class per aggregate; framework magic in Spring/NestJSA transaction boundary to reason about; lock contention if held too longTwo models to maintain; eventual consistency at levels two and three
Built-in versionSpring Data JPA; TypeORM Repository; plain class over a SQLAlchemy sessionSpring @Transactional; DataSource.transaction(); the SQLAlchemy SessionNestJS @nestjs/cqrs; package split in Spring; routing split in FastAPI
Failure modeRepository per table; query builder leaking into services; generic base repositoryTransaction per repository call; @Transactional on a private method; long-held locksFull CQRS + event sourcing for a CRUD app; two stores before one read model proves its worth
Stop signalOne aggregate, one query, no tests — a function is enoughOne aggregate per request — the repository's save() is already atomicReads and writes share one shape and one scale — the split is overhead

The table hides the dependency between the three rows, and it is worth stating plainly: Repository and Unit of Work compose, and CQRS depends on both. A command handler that writes through repositories inside a unit of work is the write side of CQRS; a query handler that reads a read model is the read side. Adopting CQRS without the other two is building the split on top of scattered SQL and partial commits — the new architecture inherits the old problems, now in two models instead of one.

Add a pattern when a real pain appears — never on a guess What hurts right now? start from the pain, not the pattern SQL scattered in handlers queries in every controller Half-committed writes order saved, stock not reserved Reads and writes diverge list screens need a new shape Repository one per aggregate Unit of Work one transaction, one commit CQRS split the models, maybe the store Most services stop at Repository plus Unit of Work — CQRS earns its keep only later.

Architecture decision: Repository, Unit of Work, and CQRS in this codebase

  • Decision: Adopt Repository plus Unit of Work as the default for any service that writes more than one aggregate in a request. Adopt CQRS-lite — split read and write models on the same store — when a read shape diverges from the write model. Adopt full CQRS with separate stores only when reads and writes need to scale apart or need different consistency, and adopt event sourcing only as a separate, later decision.
  • Context: A multi-stack codebase (Spring Boot services, NestJS services, FastAPI services) where order placement and similar multi-aggregate use cases recur, and where read screens keep needing shapes the write model does not naturally produce. The decision applies to new services and to files already being touched.
  • Options considered: (a) The three patterns as described, in that order, with CQRS-lite as the default CQRS level. (b) No patterns — services call the database directly, with SQL in handlers and one commit per repository call. (c) Full CQRS with event sourcing from the start, using Axon in Spring and @nestjs/cqrs with an event store everywhere.
  • Why this one: Option (b) is the cheapest to write and the most expensive to extend: every new query touches every handler, a failed second write leaves a half-committed order, and the read screens either join six tables or warp the write model. Option (c) pays for two stores, eventual consistency, and event-store operations before any read has proven it needs them — the complexity arrives years before the problem. Option (a) buys the seams in the order the pain arrives: the repository hides the database, the unit of work makes multi-aggregate writes safe, and CQRS-lite buys the option to split stores later without paying for the split today.
  • What it costs you: One interface and one class per aggregate; a transaction boundary per use case that the team must reason about; and, at CQRS-lite, two models for the same data, which means two places to update when a field changes. Code review has to catch the three failure modes: a repository per table, a transaction per repository call, and a full CQRS adoption for a CRUD app.
  • When to reverse it: If a service turns out to write one aggregate per request and serve one read shape, delete the read model and call the repository directly — the split was overhead. If the read model never diverges from the write model after six months, merge it back. If separate stores are adopted and the read side never needs its own scale, collapse them into one store and keep the code split. Revisit whenever a second aggregate joins a use case, or a second read shape appears: the first of either never justifies the pattern, the second one does.
  • Recommendation

    For a new service in any of the three stacks, adopt three rules and enforce them in review. First, no SQL outside a repository — if a handler or controller contains a query, a query builder, or a table name, it moves into a repository method named for the question it answers. Second, one transaction per use case — the service method, the command handler, or the request dependency owns the boundary, and every repository call inside it shares that transaction. Third, split the read model the moment a screen needs a shape the aggregate does not have — a dedicated read query and a dedicated read schema, on the same store, with no framework and no second database. For the companion patterns, our Hexagonal and Clean Architecture guide shows where the repository sits as a port — the domain owns the interface, the adapter implements it — and our modular monolith vs microservices guide is the decision to make before any of these patterns matter at all.

    For an existing service, the migration is incremental and safe. Replace one scattered query at a time: extract it into a repository method, inject the repository, and delete the SQL from the handler. Wrap one multi-write use case at a time in a unit of work: move the two repository calls inside a single transaction and add a test that forces the second write to fail, proving the first rolls back. Split one read at a time: give the busiest list screen its own read query and its own response shape, and leave the write side untouched. Each replacement is a small, testable change, and the design gets visibly simpler with every one — which is the same incremental approach our event-driven vs request-driven guide recommends for the day the read model needs events to stay fresh.

    When NOT to use these patterns

  • Don't build a Repository for a single query. If a service reads one aggregate by id and nothing else, a repository interface is indirection with no decision behind it — call the framework's finder directly and add the repository when the second query arrives.
  • Don't build a generic repository. BaseRepository[T] with the same five methods for every entity is not the pattern; it is a data-access layer wearing the pattern's name. Repositories are per aggregate, with methods named for the questions the domain asks.
  • Don't put a transaction around a single write. One aggregate, one save(), one commit — the repository already gives you atomicity. A unit of work earns its keep at two aggregates, not one.
  • Don't adopt full CQRS for a CRUD app. Two stores, an event bus, eventual consistency, and a UI that has to explain "your order will appear shortly" — all for a read shape that a single select() could have answered. CQRS-lite on one store is the answer until the reads prove otherwise.
  • Don't let the read model write. A query handler that mutates state has defeated the split and hidden the fact. Reads return data; commands change it; the bus enforces the direction, and review enforces the rest.
  • Don't share a transaction across an external call. A unit of work that holds database locks while waiting on a payment gateway or an email API turns a slow dependency into a database outage. Commit first, then call out — or use the outbox pattern, and let the event carry the work.
  • Repository, Unit of Work, and CQRS survive because they name the three ways persistence goes wrong — scattered queries, partial writes, and one model serving two masters — and naming the failure is what lets a team fix it in the order the pain arrives. The patterns are small — an interface, a transaction boundary, a split — and their value is entirely in the discipline around them: SQL lives in exactly one place, a use case commits exactly once, and the read model is allowed to be shaped for the screen. For the companion patterns in this series, our creational patterns in Spring Boot guide covers the factories that register repositories, and our Strategy and Template Method guide covers the patterns that vary behaviour inside the handlers these three patterns protect.

    Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.