← BACK_TO_LOGS

TypeScript Design Patterns for Production Apps

•10 min read•KANAT NAZAROV
TypeScript Design Patterns for Production Apps

TypeScript Design Patterns for Production Apps: From Domain Boundaries to Failure-Tolerant Systems

TypeScript makes application code easier to refactor, but it does not automatically make an architecture reliable. A production system can compile successfully while still mixing authorization with presentation logic, allowing invalid state transitions, coupling business rules to an ORM, or producing inconsistent data across API, cache, and client state.

The core problem is not a lack of patterns. It is the absence of enforceable boundaries. In a small application, a controller can call an ORM directly and return a database record. In a production application, that shortcut becomes an architectural liability: schema changes leak into clients, retries create duplicate side effects, transactions are applied at the wrong layer, and teams cannot determine where a business invariant is enforced.

This article presents a practical set of TypeScript enterprise design patterns for production apps. The examples use Node.js, a type-safe ORM, React, and Next.js 15, but the principles apply equally to modular monoliths and microservices. The objective is not maximal abstraction. It is controlled coupling, explicit state transitions, predictable failure behavior, and measurable operational performance.

1. Establish the Domain Boundary Before Choosing the Pattern

The most important boundary is between business policy and technical implementation. Domain Driven Design in Node.js and TypeScript is useful when it is applied to real business language and invariants, not when every table receives a class with an elaborate name.

A domain module should own rules such as:

  • An order cannot be shipped before payment is captured.
  • A subscription cannot transition directly from trialing to canceled without recording a reason.
  • A tenant can access only resources belonging to its organization.
  • A refund cannot exceed the settled amount.

These rules should not depend on React, HTTP, Prisma, Drizzle, PostgreSQL, or a message broker. The domain layer should receive meaningful values and return meaningful outcomes. Infrastructure is responsible for persistence, network calls, and serialization.

A practical module structure looks like this:

src/
  modules/
    orders/
      domain/
        Order.ts
        OrderRepository.ts
        OrderErrors.ts
      application/
        CreateOrder.ts
        CapturePayment.ts
      infrastructure/
        PostgresOrderRepository.ts
        StripePaymentGateway.ts
      interface/
        http.ts
        schemas.ts
  shared/
    domain/
    infrastructure/

The dependency direction is deliberate:

HTTP or React adapter -> application use case -> domain policy
                                      -> ports
                         infrastructure implements ports

The application layer orchestrates work. It loads aggregates, invokes domain behavior, coordinates transactions, and publishes events. It should not contain SQL details. The domain layer enforces invariants. Infrastructure implements ports defined by the inner layers.

A lightweight aggregate is often enough:

export type OrderStatus = 'pending' | 'paid' | 'shipped' | 'canceled';

export class Order {
  private constructor(
    readonly id: string,
    private status: OrderStatus,
    readonly totalCents: number,
  ) {}

  static create(id: string, totalCents: number): Order {
    if (!Number.isInteger(totalCents) || totalCents <= 0) {
      throw new Error('Order total must be a positive integer');
    }
    return new Order(id, 'pending', totalCents);
  }

  markPaid(): void {
    if (this.status !== 'pending') {
      throw new Error(`Cannot pay an order in ${this.status} state`);
    }
    this.status = 'paid';
  }

  ship(): void {
    if (this.status !== 'paid') {
      throw new Error('Only paid orders can be shipped');
    }
    this.status = 'shipped';
  }
}

This is more robust than exposing a mutable database record because invalid transitions become impossible through the public API. The aggregate also creates a natural transaction boundary: all changes needed to preserve its invariants should commit atomically.

Do not turn every value into a class. Value objects are justified when they validate or normalize a concept that appears repeatedly, such as Money, EmailAddress, TenantId, or Percentage. Primitive obsession is a problem when primitives allow invalid states to travel through the system.

2. Use Ports and Adapters to Control Infrastructure Coupling

Type-safe ORM TypeScript web development is valuable because compile-time types catch mismatched fields, invalid query shapes, and unsafe result handling. However, ORM types are not domain types. A generated User row may contain nullable columns, implementation-specific relation shapes, and persistence metadata that should never become part of a public API.

Define a repository port in the domain or application layer:

export interface OrderRepository {
  findById(id: string): Promise<Order | null>;
  save(order: Order): Promise<void>;
}

Then adapt the ORM at the boundary:

export class PostgresOrderRepository implements OrderRepository {
  constructor(private readonly db: DatabaseClient) {}

  async findById(id: string): Promise<Order | null> {
    const row = await this.db.order.findUnique({ where: { id } });
    if (!row) return null;

    const order = Order.create(row.id, row.totalCents);
    if (row.status === 'paid') order.markPaid();
    if (row.status === 'shipped') {
      order.markPaid();
      order.ship();
    }
    return order;
  }

  async save(order: Order): Promise<void> {
    await this.db.order.update({
      where: { id: order.id },
      data: { status: order.status },
    });
  }
}

The mapping code may appear repetitive, but it buys isolation. A migration from one ORM to another affects an adapter rather than every use case. More importantly, the domain cannot accidentally depend on lazy-loading behavior, database-specific null semantics, or an ORM transaction object.

For read-heavy systems, use separate query models rather than forcing aggregates to serve every screen. This is a pragmatic form of CQRS:

  • Commands load domain objects and enforce invariants.
  • Queries return optimized projections for lists, dashboards, and search.
  • Query projections can be denormalized and cached without weakening command correctness.

A type-safe query should still be mapped to an API DTO:

export type OrderSummary = {
  id: string;
  status: OrderStatus;
  totalCents: number;
  createdAt: string;
};

export async function listOrderSummaries(tenantId: string): Promise<OrderSummary[]> {
  const rows = await db.order.findMany({
    where: { tenantId },
    select: { id: true, status: true, totalCents: true, createdAt: true },
    orderBy: { createdAt: 'desc' },
    take: 50,
  });

  return rows.map((row) => ({
    ...row,
    createdAt: row.createdAt.toISOString(),
  }));
}

The tenant predicate is not a cosmetic filter. In multi-tenant systems, tenant scope must be part of the repository contract, authorization policy, and database strategy. PostgreSQL row-level security can provide a second enforcement layer, but it should not replace application-level authorization tests and explicit tenant context.

3. Make Application Workflows Idempotent and Transactional

Most production failures occur at the boundary between a local transaction and an external effect. A payment can succeed while the process crashes before the order is updated. A webhook can be delivered three times. A client can retry a request after a timeout even though the server committed it.

The command handler must therefore model idempotency explicitly. A reliable workflow commonly uses:

  1. An idempotency key supplied by the client or derived from an external event ID.
  2. A unique database constraint for that key and operation scope.
  3. A database transaction for local state changes.
  4. An outbox record committed in the same transaction.
  5. A worker that publishes or executes external effects with retries.

Example schema concepts:

model IdempotencyKey {
  tenantId   String
  key        String
  requestHash String
  responseJson Json?
  createdAt  DateTime @default(now())

  @@unique([tenantId, key])
}

model OutboxMessage {
  id          String   @id
  aggregateId String
  eventType   String
  payload     Json
  publishedAt DateTime?
  attempts    Int      @default(0)
  createdAt   DateTime @default(now())
}

The application service then becomes an explicit consistency boundary:

export async function capturePayment(input: CapturePaymentInput) {
  return db.$transaction(async (tx) => {
    const existing = await tx.idempotencyKey.findUnique({
      where: { tenantId_key: { tenantId: input.tenantId, key: input.key } },
    });

    if (existing?.responseJson) return existing.responseJson;

    const order = await orderRepository.withClient(tx).findById(input.orderId);
    if (!order) throw new NotFoundError('Order');

    order.markPaid();
    await orderRepository.withClient(tx).save(order);

    const response = { orderId: order.id, status: 'paid' };
    await tx.idempotencyKey.create({
      data: {
        tenantId: input.tenantId,
        key: input.key,
        requestHash: input.requestHash,
        responseJson: response,
      },
    });

    await tx.outboxMessage.create({
      data: {
        id: crypto.randomUUID(),
        aggregateId: order.id,
        eventType: 'OrderPaid',
        payload: response,
      },
    });

    return response;
  });
}

The outbox does not make a remote payment provider transactional. It makes the local intent durable. The worker still requires retry policy, exponential backoff, a dead-letter path, and provider-specific idempotency keys. Never hold a database transaction open while calling a slow remote service unless the business case is exceptionally strong; this increases lock duration and reduces throughput under failure.

For microservices, prefer at-least-once delivery with idempotent consumers over attempting global transactions. Include event versioning, correlation IDs, causation IDs, and a stable event identity. Consumers should store processed event IDs when duplicate effects would be harmful.

4. Apply Clean Architecture Principles Across React and Next.js 15

Clean Architecture principles in React are primarily about preventing UI components from becoming application services. A component should render state and emit user intent. It should not know how authorization, retries, database writes, or payment orchestration work.

In Next.js 15, separate server-only code from client code aggressively. Server components and route handlers can access application services, but client components should receive serializable DTOs and call a narrow interface. Do not import an ORM client into a client bundle, and do not rely on TypeScript types as runtime validation.

Use a runtime schema at every untrusted boundary:

import { z } from 'zod';

export const CreateOrderSchema = z.object({
  tenantId: z.string().uuid(),
  totalCents: z.number().int().positive(),
});

export async function POST(request: Request) {
  const body = CreateOrderSchema.parse(await request.json());
  const result = await createOrder(body);

  return Response.json(result, { status: 201 });
}

TypeScript verifies code during compilation; it does not validate JSON arriving from a browser, queue, webhook, or another service. Treat parsing as a security and reliability boundary.

A React client should model asynchronous state explicitly. Avoid a collection of loosely related booleans such as isLoading, isSaving, and hasError when the state machine has mutually exclusive phases. A discriminated union prevents impossible UI states:

type OrderViewState =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'ready'; order: OrderSummary }
  | { status: 'error'; message: string; retryable: boolean };

For shared server state, use a query library or a carefully designed cache rather than duplicating fetched data across local component state. Define cache keys with tenant and authorization scope. Invalidate or update them after mutations. Optimistic updates should be used only when rollback is deterministic and the server conflict policy is clear.

Next.js 15 applications also need an explicit decision about rendering and caching. A low-latency API is not automatically low latency if server rendering repeatedly performs uncached database queries. Measure time to first byte, server render duration, database query latency, cache hit ratio, and hydration cost separately. Use request-level deduplication for repeated reads, stable cache tags for invalidation, and bounded revalidation periods for data that tolerates staleness.

Production Protocols and Implementation Workflow

Use the following workflow when introducing a new feature or module:

  • Write the invariant and state transitions in domain language before creating database tables.
  • Define command inputs and query DTOs separately from ORM-generated types.
  • Add runtime validation for HTTP, environment variables, queue messages, and webhook payloads.
  • Create repository and gateway ports only where they protect a meaningful boundary.
  • Implement the use case with an explicit transaction scope.
  • Add an idempotency strategy for every retried command or external event.
  • Use an outbox for events that must not be lost after a committed write.
  • Add contract tests for adapters and invariant tests for aggregates.
  • Test authorization with cross-tenant fixtures, not only happy-path ownership cases.
  • Instrument every use case with correlation ID, tenant ID, operation name, and outcome.

Recommended TypeScript compiler settings should make unsafe boundaries visible:

{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "noImplicitOverride": true,
    "useUnknownInCatchVariables": true,
    "verbatimModuleSyntax": true
  }
}

Compiler strictness is necessary but insufficient. Add lint rules against importing infrastructure into domain modules, enforce dependency direction in CI, and use architectural tests to reject forbidden imports. A monorepo can encode boundaries with packages such as domain, application, adapters, and web, but package separation is useful only if the dependency graph is enforced.

Operationally, monitor these metrics:

  • P50, P95, and P99 latency by endpoint and use case.
  • Database pool saturation, lock wait time, slow-query count, and replica lag.
  • Cache hit ratio and stale-read frequency.
  • Outbox age, retry count, and dead-letter volume.
  • Idempotency conflict rate and duplicate event suppression.
  • Error rate segmented by validation, authorization, dependency timeout, and internal failure.
  • Queue lag and consumer processing duration.
  • React hydration errors, client error rate, and server-render duration.

Set explicit timeouts on HTTP clients, database queries, and queue operations. Apply bounded retries only to transient failures. A retry budget is essential: three layers each retrying three times can create nine downstream attempts from one user action. Use circuit breakers or load shedding when a dependency is degraded, and return a clear retryable error rather than allowing requests to consume every worker.

Conclusion

The strongest TypeScript architectures are not defined by the number of classes, decorators, or framework abstractions. They are defined by invariants that remain enforceable when traffic increases, dependencies fail, schemas evolve, and requests are retried.

Use Domain Driven Design to identify meaningful boundaries, ports and adapters to isolate infrastructure, type-safe ORM access to reduce query errors without leaking persistence models, and Clean Architecture principles to keep React and Next.js 15 interfaces independent from business policy. Combine aggregates with transaction boundaries, idempotency keys, outbox delivery, runtime validation, and explicit observability.

The architectural test is straightforward: can the system reject invalid state, safely repeat a command, recover from a dependency failure, and explain its latency and error behavior in production? If the answer is yes, the patterns are doing useful work. If not, additional abstraction will not solve the problem; clearer boundaries and stronger operational protocols will.

Leave a comment

Kanat Nazarov

Kanat Nazarov

Systems & Full-Stack Engineer
Kanat Nazarov is a product-minded Full-Stack Engineer. He is the co-founder of GetFusionChat, an enterprise-grade multi-tenant communication SaaS platform. Beyond architecting low-latency infrastructures and advanced AI systems, Kanat is a dedicated student of peak performance—optimizing his lifestyle through rigorous fitness, precise nutrition, and creative production in music. He operates on the core philosophy that breakthrough technical results stem from a high-functioning, deeply disciplined life.