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.
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 Dimension | Traditional Horizontal Layered Architecture | Clean / Hexagonal (Heavy Abstractions) | Vertical Slice Architecture (VSA) |
|---|---|---|---|
| Axis of change | Technical layer (controllers, services, repos) | Concentric rings (domain, application, infra) | Business feature / use case (features/invoices/approve/) |
| Files touched per new feature | 6–10 directories across the entire codebase | 8–12 files (ports, use-case, mappers, adapters) | 1 feature folder (handler, schema, test, optional SQL) |
| Read vs. Write flexibility | Forces reads through heavy ORM domain entities | Usually mirrors write repositories onto reads | Natural CQRS Pattern: complex writes use domain invariants; reads use lean SQL |
| Codebase navigability for coding agents | Poor; bloated shared Service & Repository classes | Moderate; deep indirection across ports/impls | Exceptional; entire feature context fits inside 1–2 files |
| Risk of over-DRY coupling | Very 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).
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:
Service or DTO file in a layered codebase: say 6 features share OrderService.ts and order.dto.ts.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.
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.
Apply the Rule of Three / Invariant Ownership Test before extracting shared code:
shared/domain/: Core state machines and monetary/compliance invariants that must never diverge across write slices (e.g., an Invoice cannot transition from VOID to PAID, regardless of whether the transition is triggered by PayInvoiceSlice, ReconcileWebhookSlice, or ImportBatchSlice).shared/pipeline/: Transport-level cross-cutting behaviors (RLS transaction wrapper, fine-grained PEP guard via Fine-Grained Authorization Pattern, outbox publisher via Outbox Pattern).// 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(),
};
});
}
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/
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.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.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.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.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:
modules/<context>/features/<verb-noun>/ rather than appending methods to existing multi-feature *Service or *Repository files.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).domain/ invariants, persist optimistically, and emit outbox events cleanly.Every slice PR must deliver a self-contained <slice>.test.ts validating:
400/422 validation errors (Form Handling and Validation).expectedVersion returns 409 Conflict, while happy path commits state mutation and outbox record atomically.