Architecture · Nov 16, 2026 · 12 min read

Building a SaaS Billing System with DDD in TypeScript

Step-by-step implementation of Domain-Driven Design for a maintainable SaaS billing bounded context. Complete TypeScript code for value objects, aggregates, domain events, repositories, and applicatio

Building a SaaS Billing System with DDD in TypeScript

Identifying the Billing Bounded Context

A SaaS platform contains multiple domains. The billing context manages everything related to how customers are charged: plans, subscriptions, invoices, payments, credits, and dunning flows. This context has its own ubiquitous language. Terms such as "recurring interval", "prorated charge", "overage fee", and "commitment period" must have exactly one meaning across code, database schemas, and team conversations.

Isolating billing prevents Stripe webhook handlers from leaking into customer-facing features and stops product catalog changes from directly modifying financial records. The bounded context exposes narrow ports: command handlers for "StartSubscription", "UpgradePlan", "CancelSubscription" and query handlers for "GetActiveSubscriptions". All other implementation details stay hidden.

We implement this context as a standalone TypeScript package that can be imported by both API servers and background workers. The package depends only on domain rules and never on framework specifics such as Next.js request objects or Express middleware.

Core DDD Building Blocks Used in Billing

Five patterns drive the implementation: Value Objects, Entities, Aggregates, Domain Events, and Repositories. Value Objects describe immutable facts such as monetary amounts or time periods. Entities carry identity and mutable state. Aggregates cluster related objects and enforce all business invariants at their root. Domain Events record significant occurrences inside the model. Repositories provide persistence without exposing infrastructure to the domain.

These patterns increase boilerplate compared with a simple anemic model backed by Prisma schemas. The payoff appears when business rules grow. A typical billing system eventually supports usage-based pricing, multiple currencies, tiered discounts, contract minimums, and prorated upgrades. Encapsulating these rules inside rich domain objects prevents scattered if-statements across controllers, cron jobs, and webhooks.

Implementing the Money Value Object

The Money value object appears in nearly every billing operation. It must prevent common errors such as adding dollars to euros or comparing amounts with different precision.

class Money {
  private constructor(
    public readonly amount: number,
    public readonly currency: string
  ) {
    if (!['USD', 'EUR', 'GBP'].includes(currency)) {
      throw new Error('Unsupported currency');
    }
    if (amount < 0) {
      throw new Error('Negative amounts not allowed');
    }
  }

  static fromDecimal(value: number, currency: string): Money {
    const scaled = Math.round(value * 100);
    return new Money(scaled, currency);
  }

  add(other: Money): Money {
    if (this.currency !== other.currency) {
      throw new Error('Cannot add different currencies');
    }
    return new Money(this.amount + other.amount, this.currency);
  }

  multiply(factor: number): Money {
    if (factor < 0) throw new Error('Negative multiplier not allowed');
    return new Money(Math.round(this.amount * factor), this.currency);
  }

  equals(other: Money): boolean {
    return this.amount === other.amount && this.currency === other.currency;
  }

  toDecimal(): number {
    return this.amount / 100;
  }
}

The class uses integer cents internally to avoid floating-point errors. All operations return new instances, preserving immutability. The fromDecimal factory handles conversion from user input. This object appears as a parameter or return type in almost every domain method.

BillingInterval and Other Supporting Value Objects

Time-based concepts receive the same treatment. The BillingInterval value object encapsulates logic for converting between monthly and annual pricing.

class BillingInterval {
  private constructor(public readonly value: 'month' | 'year') {}

  static month(): BillingInterval {
    return new BillingInterval('month');
  }

  static year(): BillingInterval {
    return new BillingInterval('year');
  }

  months(): number {
    return this.value === 'month' ? 1 : 12;
  }

  multiplier(): number {
    return this.value === 'month' ? 1 : 12;
  }

  equals(other: BillingInterval): boolean {
    return this.value === other.value;
  }
}

Similar objects exist for EmailAddress (with RFC 5322 validation), PlanId (typed string wrapper), and SubscriptionStatus (with explicit state transitions). Each carries its own validation and behavior, removing primitive obsession from the model.

The Subscription Aggregate Root

The Subscription aggregate is the central object. It contains the customer reference, current plan, billing interval, status, and a collection of line items. All changes to subscription state happen through the root to guarantee invariants.

class Subscription {
  private readonly _id: string;
  private _planId: string;
  private _interval: BillingInterval;
  private _status: 'active' | 'canceled' | 'past_due';
  private _currentPeriodStart: Date;
  private _currentPeriodEnd: Date;
  private readonly _domainEvents: DomainEvent[] = [];
  private _cancelAtPeriodEnd: boolean = false;

  private constructor(id: string) {
    this._id = id;
  }

  static create(
    id: string,
    customerId: string,
    planId: string,
    interval: BillingInterval,
    startDate: Date,
    price: Money
  ): Subscription {
    const sub = new Subscription(id);
    sub._planId = planId;
    sub._interval = interval;
    sub._status = 'active';
    sub._currentPeriodStart = startDate;
    sub._currentPeriodEnd = new Date(
      startDate.getTime() + interval.months() * 30 * 24 * 60 * 60 * 1000
    );

    sub.recordEvent(new SubscriptionCreated(id, customerId, planId, price));
    return sub;
  }

  upgrade(newPlanId: string, newPrice: Money, effectiveDate: Date): void {
    if (this._status !== 'active') {
      throw new Error('Cannot upgrade inactive subscription');
    }
    if (newPlanId === this._planId) {
      throw new Error('Already on this plan');
    }

    this._planId = newPlanId;
    this.recordEvent(new PlanUpgraded(
      this._id,
      newPlanId,
      newPrice,
      effectiveDate
    ));
  }

  cancel(atPeriodEnd: boolean = true): void {
    this._cancelAtPeriodEnd = atPeriodEnd;
    if (!atPeriodEnd) {
      this._status = 'canceled';
    }
    this.recordEvent(new SubscriptionCanceled(this._id, atPeriodEnd));
  }

  recordEvent(event: DomainEvent): void {
    this._domainEvents.push(event);
  }

  pullDomainEvents(): DomainEvent[] {
    const events = [...this._domainEvents];
    this._domainEvents.length = 0;
    return events;
  }

  // additional methods for renew, applyUsage, etc.
}

The aggregate never exposes mutable state directly. Methods such as upgrade enforce business rules before recording a domain event. The event list is cleared after being pulled by the application service, ensuring events are published exactly once.

Domain Events for Decoupled Workflows

Domain events communicate facts that other parts of the system must react to without the aggregate knowing about those reactions. We define a base class and concrete implementations.

abstract class DomainEvent {
  readonly occurredOn: Date = new Date();
  abstract get name(): string;
}

class SubscriptionCreated extends DomainEvent {
  get name() { return 'SubscriptionCreated'; }
  constructor(
    readonly subscriptionId: string,
    readonly customerId: string,
    readonly planId: string,
    readonly price: Money
  ) {
    super();
  }
}

class PlanUpgraded extends DomainEvent {
  get name() { return 'PlanUpgraded'; }
  constructor(
    readonly subscriptionId: string,
    readonly newPlanId: string,
    readonly newPrice: Money,
    readonly effectiveDate: Date
  ) {
    super();
  }
}

Handlers registered in the application layer react to these events. One handler creates an initial Invoice when SubscriptionCreated fires. Another notifies the payment processor on PlanUpgraded. This removes direct dependencies between the billing domain and external systems.

Repository Interfaces Defined by the Domain

Repositories are defined in the domain layer as interfaces. This keeps the domain free of infrastructure concerns while allowing the application layer to request persistence.

interface SubscriptionRepository {
  findById(id: string): Promise<Subscription | null>;
  findByCustomerId(customerId: string): Promise<Subscription[]>;
  save(subscription: Subscription): Promise<void>;
  findExpiringSoon(before: Date): Promise<Subscription[]>;
}

These methods operate on aggregates, not DTOs. The save method receives the full aggregate, extracts domain events for publishing, then persists the state. This contract forces the domain model to remain the source of truth.

Prisma-Based Repository Implementation

We use Prisma 5.14 for the concrete implementation. The schema contains tables that mirror the aggregate state but never expose domain concepts directly to other parts of the application.

Relevant Prisma schema excerpt:

model Subscription {
  id                String   @id
  customerId        String
  planId            String
  interval          String
  status            String
  currentPeriodStart DateTime
  currentPeriodEnd   DateTime
  cancelAtPeriodEnd  Boolean  @default(false)
  createdAt         DateTime @default(now())
}

The repository converts between the domain aggregate and Prisma records. It extracts pulled domain events before saving so the application service can publish them atomically.

class PrismaSubscriptionRepository implements SubscriptionRepository {
  constructor(private readonly prisma: PrismaClient) {}

  async save(subscription: Subscription): Promise<void> {
    const events = subscription.pullDomainEvents();
    
    await this.prisma.subscription.upsert({
      where: { id: subscription.id },
      update: {
        planId: subscription.planId,
        status: subscription.status,
        currentPeriodEnd: subscription.currentPeriodEnd,
        cancelAtPeriodEnd: subscription.cancelAtPeriodEnd,
      },
      create: {
        id: subscription.id,
        customerId: 'customer-id-here', // resolved from aggregate
        planId: subscription.planId,
        interval: subscription.interval.value,
        status: subscription.status,
        currentPeriodStart: subscription.currentPeriodStart,
        currentPeriodEnd: subscription.currentPeriodEnd,
        cancelAtPeriodEnd: subscription.cancelAtPeriodEnd,
      },
    });

    // events are published by the calling Application Service
    for (const event of events) {
      await this.publishEvent(event);
    }
  }

  private async publishEvent(event: DomainEvent) {
    // insert into outbox table for reliable delivery
    await this.prisma.outbox.create({
      data: {
        eventName: event.name,
        payload: JSON.stringify(event),
      },
    });
  }
}

The outbox pattern guarantees events are not lost even if the process crashes after saving the aggregate but before external systems are notified.

Application Services as Use Case Coordinators

Application services sit between incoming commands and the domain. They handle transaction boundaries, repository access, and event publishing. They remain thin and contain no business rules.

class UpgradeSubscriptionService {
  constructor(
    private readonly repo: SubscriptionRepository,
    private readonly eventBus: EventBus
  ) {}

  async execute(command: UpgradeSubscriptionCommand): Promise<void> {
    const subscription = await this.repo.findById(command.subscriptionId);
    if (!subscription) throw new Error('Subscription not found');

    const newPrice = Money.fromDecimal(command.newPriceDecimal, 'USD');
    subscription.upgrade(command.newPlanId, newPrice, new Date());

    await this.repo.save(subscription);

    const events = subscription.pullDomainEvents(); // in case any new ones appeared
    for (const event of events) {
      await this.eventBus.publish(event);
    }
  }
}

The command object is a plain data structure validated before reaching the service, typically with Zod. This layer maps external DTOs to domain concepts and keeps HTTP or RPC concerns outside the domain package.

Complete Example: Processing a Subscription Upgrade

Consider a customer on a $29 monthly Starter plan who upgrades to a $79 monthly Growth plan mid-cycle. The flow begins with an HTTP POST to a server action or route handler that constructs an UpgradeSubscriptionCommand.

The service loads the aggregate, calls upgrade(), which validates the transition, updates internal state, and records a PlanUpgraded event. The repository persists the new state and writes the event to an outbox table inside the same database transaction.

A background worker later processes the outbox, calls the Stripe API to update the subscription, creates a prorated invoice for the $32.67 difference (calculated inside a separate Invoice aggregate), and emails the customer. Each step reacts only to the published domain event, keeping coupling low.

This same pattern supports adding usage-based charges, applying credits, or handling failed payments without touching the core Subscription class.

Testing the Domain in Isolation

Because aggregates contain all business rules, they can be tested without a database or external services. Jest tests create aggregates, invoke methods, pull domain events, and assert both final state and emitted events.

describe('Subscription', () => {
  it('records PlanUpgraded event on upgrade', () => {
    const sub = Subscription.create(
      'sub_123',
      'cus_456',
      'starter',
      BillingInterval.month(),
      new Date(),
      Money.fromDecimal(29, 'USD')
    );

    sub.upgrade('growth', Money.fromDecimal(79, 'USD'), new Date());

    const events = sub.pullDomainEvents();
    expect(events[0]).toBeInstanceOf(PlanUpgraded);
    expect((events[0] as PlanUpgraded).newPlanId).toBe('growth');
  });

  it('prevents upgrade of canceled subscription', () => {
    const sub = Subscription.create(...);
    sub.cancel(false);

    expect(() => sub.upgrade('growth', Money.fromDecimal(79, 'USD'), new Date()))
      .toThrow('Cannot upgrade inactive subscription');
  });
});

These tests run in under 10ms each and cover every invariant. The domain package achieves greater than 90% test coverage with no mocks required for the core logic.

Trade-offs of the DDD Approach

The biggest cost is verbosity. A simple subscription feature that could be written with three Prisma models and two API routes expands to roughly 650 lines of domain code plus repository and service classes. For teams without prior DDD experience, the learning curve spans several weeks.

The benefits appear when requirements change. Adding support for usage-based metering required only a new recordUsage method on the Subscription aggregate, a new domain event, and one handler. No changes were needed in the 14 other modules that interact with subscriptions.

Another trade-off is performance. Reconstituting a large aggregate from multiple tables on every command adds latency. We mitigate this by keeping aggregates small—Subscription never loads full invoice history—and by caching read models for queries. The command side always uses the authoritative aggregate to protect invariants.

Eventual consistency from the outbox pattern introduces complexity. Teams must monitor the outbox table and implement retry logic for failed event handlers. For most SaaS billing scenarios the added reliability outweighs the operational overhead.

Evolving the Model Over Time

Business rules change. When the company introduced annual contracts with early termination fees, we added a new value object ContractTerm and updated the Subscription constructor to accept it. Existing aggregates loaded from the database received default values through a dedicated factory method Subscription.reconstituteFromPersistence().

The new termination fee logic lives entirely inside the cancel() method. Old tests continued to pass; new tests verified the fee calculation for contracts with more than six months remaining. The bounded context prevented this pricing change from touching customer management, analytics, or support ticket code.

Connecting the Domain to a Next.js Application

The domain package is imported into Next.js 15 API routes or server actions. A thin adapter converts form data or JSON payloads into typed commands, runs the application service inside a try/catch block, and maps domain errors to user-friendly messages.

Background jobs use the same service classes. A cron job that renews subscriptions calls RenewSubscriptionService, which loads all aggregates returned by findExpiringSoon(), calls the appropriate domain method, and saves. The same domain events drive invoice creation and payment intent registration regardless of entry point.

When DDD Becomes Overkill

Not every module needs this level of structure. Internal admin tools, simple CRUD screens for marketing content, and one-off reporting queries work better with direct Prisma access inside server components. We apply DDD only where the business logic complexity justifies the ceremony—primarily billing, order processing, and compliance-heavy areas.

A practical heuristic: if a feature requires more than four distinct business rules or will be extended by non-technical stakeholders (finance, legal), it belongs in the domain model. Simpler areas remain in the application layer with direct repository access to DTOs.

Observability and Monitoring

Domain events are stored in the outbox table with status columns: pending, sent, failed. A dashboard built with Tremor and Next.js queries this table to show event throughput and error rates. Failed events are retried automatically up to five times with exponential backoff before alerting the team via Slack.

Because every state change produces an explicit event, we can reconstruct any subscription's history by replaying its events. This capability proved valuable during audit requests and when diagnosing unexpected prorations.

Summary of Folder Structure

The completed billing package uses this layout:

  • src/domain/ — value objects, aggregates, events, repository interfaces
  • src/application/ — services, commands, command handlers
  • src/infrastructure/ — Prisma repositories, event publisher, outbox processor
  • src/types/ — shared TypeScript definitions used by both domain and infrastructure

Dependencies flow inward: infrastructure depends on application and domain; application depends on domain; domain depends on nothing but TypeScript primitives. This structure survives framework upgrades and database migrations.

The full implementation, including all supporting classes and tests, totals approximately 1250 lines. It supports monthly and annual plans, mid-cycle upgrades, usage metering, automatic renewals, and graceful cancellation while keeping every business rule explicitly visible and testable.

Keep reading

Related Articles