Real-World Problem: The Creep of the Anemic Domain Model
During an audit of an e-commerce platform processing 15,000 orders a day on Node.js and TypeScript, I found the engineering team constantly fighting regressions. Every sprint brought fresh headaches. Orders shifted into ‘shipped’ before payment gateways confirmed transactions. Worse, race conditions silently pushed inventory counts down to negative numbers.
The culprit became obvious once we opened the codebase: the service layer passed raw database models around with zero encapsulation. Here is the pattern that caused the chaos:
// Typical anemic service logic
async function updateOrder(orderId: string, newItems: OrderItemDto[]) {
const order = await db.orders.findById(orderId);
// Business rules scattered everywhere
if (order.status === 'SHIPPED') {
throw new Error('Cannot modify a shipped order');
}
let total = 0;
for (const item of newItems) {
if (item.quantity <= 0) throw new Error('Invalid quantity');
total += item.price * item.quantity;
}
order.items = newItems;
order.totalAmount = total;
await db.orders.update(orderId, order);
}
This snippet looks innocent enough in a pet project. In production, business rules quickly sprawl. Soon, identical checks get copy-pasted across controllers, background queues, and one-off CLI scripts. The moment an engineer forgets a guard check in a new admin endpoint, corrupted data lands in PostgreSQL.
Root Cause Analysis: Why Anemic Models Fail at Scale
This breakdown happens because of three architectural pitfalls:
- Primitive Obsession: Passing bare strings and numbers for currencies, emails, and identifiers. Raw primitives cannot validate themselves. TypeScript compiles
order.email = "not-an-email"without a single warning. - Anemic Domain Models: Using objects as passive data holders while external services manage all business logic. When entities do not enforce their own rules, code outside inevitably corrupts their state.
- Leaky Persistence Boundaries: Coupling ORM schemas directly to core business logic. If database column changes dictate your domain definitions, any database migration risks breaking validation everywhere.
Moving past these pitfalls requires separating your data structures from your business rules.
Solutions Compared: Structuring Enterprise Business Logic
Most backend teams evaluate three common strategies when scaling TypeScript services:
| Approach | Pros | Cons | Best Fit |
|---|---|---|---|
| Transaction Scripts (Active Record) | Rapid prototyping; minimal boilerplate; direct queries. | Business logic fragments quickly; high risk of invalid state; hard to unit test without database. | Small CRUD apps, internal admin dashboards, proof-of-concepts. |
| Service-Layered Architecture | Separates HTTP handlers from database queries; familiar structure. | Services balloon into 2,000+ line God classes; entity validation remains scattered across services. | Medium applications with moderate logic and limited state transitions. |
| Domain-Driven Design (DDD) Tactical Patterns | Guaranteed domain invariants; high testability without database mocks; models reflect exact business rules. | Higher upfront design investment; requires strict mapping between domain and persistence layers. | Complex domains, core workflows, and long-lived enterprise applications. |
The Solution: Tactical DDD with TypeScript
Tactical DDD protects your domain by building around four core patterns: Value Objects, Entities, Aggregate Roots, and Repositories.
1. Value Objects: Eliminating Primitive Obsession
A Value Object has no distinct identity. Its attributes define it completely, and it remains strictly immutable. Two instances holding identical attributes are structurally equal.
// Money Value Object
export class Money {
private readonly amount: number;
private readonly currency: string;
constructor(amount: number, currency: string) {
if (amount < 0) {
throw new Error('Money amount cannot be negative');
}
if (!['USD', 'EUR', 'VND'].includes(currency)) {
throw new Error(`Unsupported currency: ${currency}`);
}
// Round to 2 decimal places to avoid IEEE 754 floating-point drift
this.amount = Math.round(amount * 100) / 100;
this.currency = currency;
}
public getAmount(): number { return this.amount; }
public getCurrency(): string { return this.currency; }
public add(other: Money): Money {
if (this.currency !== other.currency) {
throw new Error(`Cannot add ${other.currency} to ${this.currency}`);
}
return new Money(this.amount + other.amount, this.currency);
}
public equals(other: Money): boolean {
return this.amount === other.amount && this.currency === other.currency;
}
}
2. Entities: Identity Over State
An Entity possesses a persistent identity across its lifecycle, even when attributes change. Two entities sharing the same data with different IDs represent distinct records.
// OrderItem Entity
export class OrderItem {
constructor(
public readonly id: string,
public readonly productId: string,
private quantity: number,
public readonly unitPrice: Money
) {
if (quantity <= 0) {
throw new Error('Quantity must be greater than zero');
}
}
public getQuantity(): number { return this.quantity; }
public calculateSubtotal(): Money {
return new Money(this.unitPrice.getAmount() * this.quantity, this.unitPrice.getCurrency());
}
}
3. Aggregates and Aggregate Roots: Enforcing Consistency Boundaries
An Aggregate wraps Entities and Value Objects within an explicit consistency boundary. Outside code interacts only through the Aggregate Root, guaranteeing that every state change preserves business rules.
export type OrderStatus = 'PENDING' | 'PAID' | 'SHIPPED' | 'CANCELLED';
export class Order {
private items: OrderItem[] = [];
private status: OrderStatus = 'PENDING';
constructor(public readonly id: string, public readonly customerId: string) {}
public addItem(item: OrderItem): void {
if (this.status !== 'PENDING') {
throw new Error('Cannot add items to a finalized or active order');
}
this.items.push(item);
}
public calculateTotal(): Money {
if (this.items.length === 0) {
return new Money(0, 'USD');
}
return this.items.reduce(
(accum, item) => accum.add(item.calculateSubtotal()),
new Money(0, this.items[0].unitPrice.getCurrency())
);
}
public markAsPaid(): void {
if (this.status !== 'PENDING') {
throw new Error('Only pending orders can be marked as paid');
}
if (this.items.length === 0) {
throw new Error('Cannot pay for an empty order');
}
this.status = 'PAID';
}
public getStatus(): OrderStatus { return this.status; }
public getItems(): ReadonlyArray<OrderItem> { return [...this.items]; }
}
4. Repository Pattern: Isolating Domain from Database
Repositories present an in-memory collection interface for Aggregate Roots. Your domain defines the contract; infrastructure details stay encapsulated behind concrete ORM or SQL drivers.
// Domain layer: Repository Interface
export interface OrderRepository {
findById(id: string): Promise<Order | null>;
save(order: Order): Promise<void>;
}
// Infrastructure layer: Prisma or TypeORM concrete implementation
export class PrismaOrderRepository implements OrderRepository {
async findById(id: string): Promise<Order | null> {
// 1. Fetch raw rows from database
// 2. Map database schema to Order Aggregate Root
// 3. Return Domain instance
return null; // Database details stay out of the domain
}
async save(order: Order): Promise<void> {
// Persist domain state back to database tables
}
}
5. Application Service: Orchestrating the Use Case
With domain logic locked inside the Aggregate Root, application services become lean orchestrators:
export class FinalizeOrderUseCase {
constructor(private readonly orderRepo: OrderRepository) {}
async execute(orderId: string): Promise<void> {
const order = await this.orderRepo.findById(orderId);
if (!order) {
throw new Error(`Order ${orderId} not found`);
}
// The aggregate validates its own state transition
order.markAsPaid();
await this.orderRepo.save(order);
}
}
The use case is straightforward. It fetches the aggregate, invokes a business method, and saves the result. If someone tries to pay for an empty or already-shipped order, the Aggregate Root rejects it immediately before any database query executes.

