Vertical Slice Architecture

Vertical Slice Architecture (VSA) structures an application around business capabilities and individual user use cases ("slices") rather than technical horizontal layers (controllers/, services/, repositories/, dtos/). Each vertical slice owns its entire execution path end-to-end—from HTTP/RPC input schema validation and authorization policy check to persistence query, domain rules, outbox emission, and test suite—inside one cohesive directory or file module.

For human teams and especially autonomous coding agents operating under bounded context windows, horizontal layered architectures impose high cognitive tax: adding a single field to an enterprise form requires hunting across 8 files in 5 directories while wading through shared OrderService.ts files bloated to 2,500 lines with speculative abstractions. Vertical slices localize change along the true axis of feature evolution. For complementary architecture and domain patterns, consult Architecture Hub, Design Patterns Hub, Software Architecture Patterns, and CQRS Pattern.


1. Horizontal Layers vs. Vertical Feature Slices

Classic N-tier and overly strict Clean/Onion layouts force every incoming request through uniform abstract layers, even when one slice is a simple SQL projection read and another is a complex multi-step approval mutation. Vertical Slice Architecture keeps the boundary between slices decoupled while freeing each slice to pick the exact implementation complexity its use case demands:

graph TD
    Req["HTTP / Queue Request"] --> Dispatch["Thin Router / Mediator Pipeline"]
    Dispatch --> Behaviors["Shared Cross-Cutting Behaviors (AuthN, Telemetry, Idempotency)"]
    Behaviors --> SliceA["Slice 1: ApprovePurchaseOrder (Write + Rich Domain + Outbox)"]
    Behaviors --> SliceB["Slice 2: SearchInvoices (Direct Read SQL Projection)"]
    Behaviors --> SliceC["Slice 3: ExportComplianceCsv (Streaming Cursor Query)"]
    SliceA --> DB[("Shared Database / Module Schema")]
    SliceB --> DB
    SliceC --> DB

    click Dispatch "/wiki/ApiDesignBestPractices" "API Design Best Practices"
    click Behaviors "/wiki/IdempotencyPatterns" "Idempotency Patterns"
    click SliceA "/wiki/DomainDrivenDesign" "Domain-Driven Design"
    click SliceB "/wiki/CqrsPattern" "CQRS Pattern"
Architectural DimensionTraditional Horizontal Layered ArchitectureClean / Hexagonal (Heavy Abstractions)Vertical Slice Architecture (VSA)
Axis of changeTechnical layer (controllers, services, repos)Concentric rings (domain, application, infra)Business feature / use case (features/invoices/approve/)
Files touched per new feature6–10 directories across the entire codebase8–12 files (ports, use-case, mappers, adapters)1 feature folder (handler, schema, test, optional SQL)
Read vs. Write flexibilityForces reads through heavy ORM domain entitiesUsually mirrors write repositories onto readsNatural CQRS Pattern: complex writes use domain invariants; reads use lean SQL
Codebase navigability for coding agentsPoor; bloated shared Service & Repository classesModerate; deep indirection across ports/implsExceptional; entire feature context fits inside 1–2 files
Risk of over-DRY couplingVery high (UserService used by 19 unrelated endpoints)Moderate (shared ApplicationDTO reuse)Low; slices stay independent until genuine domain concepts emerge

Notice that VSA is not "no architecture" or "raw SQL inside controllers." Shared Domain Entities/Aggregates (such as Invoice state transition methods or Money arithmetic) still belong in a shared domain/ module when two or more write slices enforce the exact same invariant. What disappears is the artificial horizontal InvoiceService god-class and speculative generic IRepository<T> pass-through wrappers (Repository Pattern).


2. Quantifying Blast Radius and Agent Context Locality

The quantitative advantage of Vertical Slice Architecture appears in change localization, merge conflict frequency, and AI coding-agent retrieval density.

Consider a modular backend with F = 60 endpoints implemented across a horizontal layered layout versus vertical slices. Let:

P_{\text{side\_effect\_layered}} = 1 - (1 - p)^k = 1 - (0.96)^5 \approx 1 - 0.815 = 18.5\% \text{ unplanned regression risk per PR}

When each feature slice defines its own Request Schema, Response Schema, Policy Check, and Query/Command Handler (k = 0 shared UI/controller DTOs; shared code limited to strict immutable domain invariants and cross-cutting pipeline middleware), the unplanned coupling probability from changing an endpoint field drops toward zero.

Equally important for AI agent context efficiency: assume an agent reads all directly relevant files to implement a change safely. In a layered repo where OrderService.ts (1{,}800 lines), OrderRepository.ts (950 lines), and OrderController.ts (700 lines) bundle 12 endpoints together, an agent pays ~3,450 lines (~35,000 tokens) to safely modify one endpoint. In a vertical slice directory (features/orders/cancel-order.ts + cancel-order.test.ts + domain/order-aggregate.ts), the entire working set fits in ~350 lines (~3,500 tokens)—a 10x context reduction with sharper semantic boundaries for MCP retrieval tools.


3. Slice Anatomy, Cross-Cutting Pipeline, and Domain Promotion Rule

A well-structured slice handles four responsibilities cleanly in one cohesive boundary, delegating cross-cutting boilerplate (authentication, tenant context binding via Multi-Tenant Isolation Pattern, idempotency via Idempotency Patterns, and structured tracing via Structured Logging) to a deterministic wrapper or middleware pipeline.

When to Keep Code Inside a Slice vs. Promote to Shared Domain

Apply the Rule of Three / Invariant Ownership Test before extracting shared code:

// features/purchase-orders/approve/approve-po.slice.ts
// One self-contained vertical slice: schema + auth + transaction + invariant + outbox + response
import { z } from "zod";
import type { PoolClient } from "pg";
import { authorizeOrThrow } from "../../../shared/auth/pep";
import { withTenantTransaction, type VerifiedTenantContext } from "../../../shared/db/tenant-tx";
import { enqueueOutboxEvent } from "../../../shared/outbox/outbox";
import { transitionPoToApproved } from "../../../domain/purchase-order/po-invariants";

export const ApprovePurchaseOrderInput = z.object({
  purchaseOrderId: z.string().uuid(),
  approvalNote: z.string().trim().max(500).optional(),
  expectedVersion: z.number().int().positive(),
});

export type ApprovePurchaseOrderCommand = z.infer<typeof ApprovePurchaseOrderInput>;

export interface ApprovePurchaseOrderResult {
  readonly purchaseOrderId: string;
  readonly status: "APPROVED";
  readonly newVersion: number;
  readonly approvedAtIso: string;
}

export async function handleApprovePurchaseOrder(
  ctx: VerifiedTenantContext,
  rawInput: unknown,
  deps: { dbPool: Parameters<typeof withTenantTransaction>[0]; now: () => Date }
): Promise<ApprovePurchaseOrderResult> {
  // 1. Strict slice-owned input validation
  const cmd = ApprovePurchaseOrderInput.parse(rawInput);

  return withTenantTransaction(deps.dbPool, ctx, async (tx: PoolClient) => {
    // 2. Load only the fields needed for policy + optimistic concurrency check
    const { rows } = await tx.query<{
      id: string;
      tenant_id: string;
      requester_id: string;
      department_id: string;
      amount_cents: string;
      status: string;
      version: number;
    }>(
      `SELECT id, tenant_id, requester_id, department_id, amount_cents, status, version
         FROM purchase_orders
        WHERE id = $1
          FOR UPDATE`,
      [cmd.purchaseOrderId]
    );

    const row = rows[0];
    if (!row) {
      throw Object.assign(new Error("Purchase order not found"), { statusCode: 404, code: "PO_NOT_FOUND" });
    }

    // 3. Authoritative Fine-Grained Authorization Check (SoD + spend limit + MFA freshness)
    await authorizeOrThrow(ctx, "po:approve", {
      id: row.id,
      tenantId: row.tenant_id,
      ownerUserId: row.requester_id,
      departmentId: row.department_id,
      amountCents: Number(row.amount_cents),
      status: row.status,
    });

    // 4. Shared domain invariant + optimistic locking check
    if (row.version !== cmd.expectedVersion) {
      throw Object.assign(new Error("Stale version"), { statusCode: 409, code: "VERSION_CONFLICT" });
    }
    const approvedAt = deps.now();
    const nextState = transitionPoToApproved(row.status, approvedAt);

    // 5. Persist update + transactional outbox event atomically
    await tx.query(
      `UPDATE purchase_orders
          SET status = $1, approved_by = $2, approved_at = $3, approval_note = $4, version = version + 1
        WHERE id = $5 AND version = $6`,
      [nextState.status, ctx.actorId, approvedAt.toISOString(), cmd.approvalNote ?? null, row.id, cmd.expectedVersion]
    );

    await enqueueOutboxEvent(tx, {
      tenantId: ctx.tenantId,
      aggregateType: "PurchaseOrder",
      aggregateId: row.id,
      eventType: "PurchaseOrderApproved.v1",
      payload: {
        purchaseOrderId: row.id,
        approvedBy: ctx.actorId,
        amountCents: Number(row.amount_cents),
        approvedAtIso: approvedAt.toISOString(),
      },
    });

    return {
      purchaseOrderId: row.id,
      status: "APPROVED",
      newVersion: row.version + 1,
      approvedAtIso: approvedAt.toISOString(),
    };
  });
}

Physical Repository Layout

Group slices by Bounded Context / Capability, never by technical type:

src/
  modules/
    procurement/
      domain/               # Shared state machines & value objects ONLY
      features/
        submit-po/          # submit-po.slice.ts, submit-po.test.ts
        approve-po/         # approve-po.slice.ts, approve-po.test.ts
        list-pending-pos/   # list-pending-pos.slice.ts, list-pending-pos.test.ts
      routes.ts             # Thin HTTP bindings mapping paths -> slices
  shared/
    auth/ db/ outbox/ errors/

4. Production Failure Modes and Architectural Drift

  1. Cross-slice imports (import { helper } from "../other-slice/..."): Allowing Slice A to directly invoke Slice B's handler or import Slice B's input DTO creates a hidden tangled graph across features. Enforce an ESLint / dependency-cruiser / architecture test rule: slices may import from shared/ and their own module's domain/, never from sibling features/* directories. If two slices need to coordinate, extract a shared domain helper or emit an asynchronous domain event via Outbox Pattern.
  2. Duplicate divergent business rules across write slices: Copying the "calculate tax + validate credit limit" block verbatim into both CreateOrderSlice and CloneOrderSlice guarantees subtle billing bugs six months later. Duplicate query SQL and view DTOs freely, but never duplicate state-transition or financial calculation invariants.
  3. Anemic micro-file explosion: Creating 10 tiny 8-line files inside every slice folder (command.ts, validator.ts, handler.ts, mapper.ts, errors.ts, index.ts) recreates horizontal-layer ceremony inside each feature folder. Start every slice in one clean file + one test file, splitting only when the file organically crosses ~300 lines.
  4. Inconsistent error envelopes and auth hooks: When every slice writes its own try/catch HTTP serialization or manually extracts headers, authorization checks and error formats drift (Error Handling Strategies). Centralize request context resolution, error-to-HTTP mapping, and idempotency in the thin transport dispatcher wrapping all slices.

5. Agent Implementation & Output Contract

When an automated coding agent adds a feature, endpoint, or background command to a VSA codebase (or scaffolds a new modular monolith), adhere strictly to these constraints:

Required Structural Decisions

  1. Locate or create one slice directory: Place new use-case code under modules/<context>/features/<verb-noun>/ rather than appending methods to existing multi-feature *Service or *Repository files.
  2. Enforce strict inward dependencies: Verify the slice imports only from shared/* and its bounded context's domain/*. Zero cross-feature imports and zero direct external SDK imports (wrap external vendors inside an Anti-Corruption Layer Pattern).
  3. Separate read vs. write strategies explicitly: Query slices execute concise projection queries returning slice-owned DTOs directly; command slices load minimal locking state, call Fine-Grained Authorization Pattern, validate domain/ invariants, persist optimistically, and emit outbox events cleanly.

Mandatory Co-Located Test Suite per Slice

Every slice PR must deliver a self-contained <slice>.test.ts validating:

  1. Input validation boundary: Invalid field shapes return structured 400/422 validation errors (Form Handling and Validation).
  2. Authorization & tenant boundary: Unauthorized actor or cross-tenant call fails closed without mutating DB state.
  3. Domain invariant & optimistic concurrency: Stale expectedVersion returns 409 Conflict, while happy path commits state mutation and outbox record atomically.