Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Vertical Slice Architecture

Intent

Organize code by feature slice — each slice owns its request, handler, and persistence for one capability — instead of spreading every feature across shared technical layers.

When It Helps

  • Features evolve independently and rarely share logic (e.g. checkout vs. reporting vs. notifications).
  • Teams want small, deletable units: removing a feature means removing one folder, not edits across layers.
  • High-churn product where minimizing cross-feature coupling matters more than maximizing code reuse.

Structure

flowchart LR
  subgraph App["Application"]
    S1["Slice: Place order<br/>(request + handler + store)"]
    S2["Slice: Add review<br/>(request + handler + store)"]
    S3["Slice: Send receipt<br/>(request + handler + mailer)"]
  end
  S1 --> DB1[("Orders table")]
  S2 --> DB2[("Reviews table")]
  S3 --> MTA["Mail service"]
  SHARED["Shared kernel<br/>(only true common code)"] -.-> S1
  SHARED -.-> S2
  SHARED -.-> S3

Rules

  1. Each slice contains everything its feature needs (input model, handler, validation, persistence) and is importable by nothing else.
  2. Slices never call each other directly; shared behavior goes through explicit messages/events or a tiny shared kernel.
  3. Cross-cutting code (auth, logging, pipelines) is composed around slices, not placed inside them.
  4. New features start as new slices; resist adding a shared abstraction until the third duplication.

Illustrative Snippet

Illustrative pseudocode — not runnable.

# sketch of one self-contained slice

slice PlaceOrder:                  # everything for this feature, together
  request PlaceOrder(items, address)
  handler execute(request):
    validate(request)              # validation lives in the slice
    total = price(request.items)
    id = database.insert("orders", {request, total})
    publish_event("order_placed", id)

slice AddReview:                   # a second slice, independent
  request AddReview(order_id, stars, note)
  handler execute(request):
    validate(request)
    database.insert("reviews", request)
# note: neither slice imports the other

Basic Recap

Vertical slice architecture groups a feature’s request, validation, handler, and infrastructure choices in one place. Slices may use different implementation styles because their internal decisions are private. Shared code is reserved for genuinely stable concepts rather than anticipated reuse. This optimizes for feature-level change and deletion instead of uniform technical layers.

Complex Scenario

A media platform has slices for uploading footage, requesting transcription, publishing an episode, and generating audiograms. Upload uses direct object storage, publishing uses relational transactions, and audiograms invoke a rendering worker. A developer notices that publishing and billing both format account entitlements, so publishing imports the billing handler instead of extracting a neutral contract. The shortcut creates a cross-slice dependency just as rendering load rises.

flowchart LR
  UploadAPI["Upload request"] --> Upload["Slice: Upload"]
  Upload --> Objects[("Object storage")]
  Upload --> Events[("Media event queue")]
  Events --> Transcribe["Slice: Transcribe"]
  Events --> Audiogram["Slice: Audiogram"]
  Audiogram --> Workers["Rendering workers"]
  PublishAPI["Publish request"] --> Publish["Slice: Publish"]
  Publish --> PublishDB[("Publishing tables")]
  Publish -. "unintended handler import" .-> Billing["Slice: Billing"]
  Kernel["Small shared kernel: IDs and clock"] -.-> Publish
  Kernel -.-> Billing

Failure walkthrough. Billing later imports publication status to decide entitlement renewal, completing a circular dependency between slices. A tenfold audiogram burst also saturates the shared worker client, delaying publishing because its connection pool has no workload limit. Mitigate the cycle with a versioned entitlement contract owned by billing and a publication event consumed by billing; isolate rendering behind a queue and give publishing its own bounded client resources.

Edge cases — concurrent publication attempts need version checks, queue retries need idempotent render keys, and partial failure needs a durable render_pending state. Ordering matters when an episode is unpublished while an older render completion arrives.

Sketch (illustrative pseudocode, not runnable):

slice PublishEpisode:
  input: {episode_id, expected_version, actor}
  handler:
    authorize(actor)
    publish_with_version(input)
    emit EpisodePublished{episode_id, publication_version}
  resources: {db_pool: 8, timeout: 1s}

slice Audiogram:
  trigger: AudiogramRequested
  concurrency: 12
  idempotency_key: episode_id + render_revision

boundary_test:
  forbid: slice_a imports slice_b.handler
  allow: versioned contracts and tiny shared value types

Trade-offs

  • Benefit: features stay cohesive and evolvable — changes land in one place and dead features delete cleanly.
  • Cost: some duplication across slices, and without discipline the shared kernel either starves or swells.

When to Use / When Not to Use

Use when:

  • Features evolve independently and cross-layer changes dominate.

Avoid when:

  • Shared domain rules must stay uniform across slices — add a shared kernel or switch to Layered.

Anti-pattern / Failure Mode

  • Misuse: Slices duplicating the same domain logic with drift.
  • Review signal: No shared contracts where consistency matters.

Failure Modes / Trade-offs

  • Shared-kernel gravity: entitlement rules, UI formatting, persistence, and transport types accumulate in common. Every slice then ships in lockstep and deletion becomes risky.
  • Copy-paste divergence: duplicated authorization or money logic drifts across slices. Promote the third proven repetition to a contract with one policy owner, not a helper full of options.
  • Accidental distributed monolith: handlers directly invoke other handlers until a feature change triggers a broad build. Import checks and consumer-driven contract tests expose the coupling.
  • Change trade-off: local choices and clean feature deletion speed delivery, but inconsistent slice idioms can make cross-feature maintenance and platform governance harder.

Ownership review. A slice should have a named feature owner and a reason to change; utility folders with callers from every slice belong to a platform contract or need splitting.

Contract review. Events and public queries crossing slices need compatibility tests just as network APIs do, even when current calls remain in-process.

Resource review. Measure each slice’s database, queue, and downstream usage separately so a convenient shared client does not erase backpressure boundaries.

  • Duplication trade-off: copying a tiny formatting rule can be safer than sharing a volatile helper, but copying regulated decisions creates unacceptable drift.
  • Discovery trade-off: feature folders make behavior easy to locate, while global policies become harder to inventory without a registry of cross-cutting composition.
  • Deletion trade-off: clean deletion works only when database migrations, events, schedules, and dashboards are also owned and retired with the slice.

Constraint-based use / avoid

ConstraintRecommendation
Several feature teams with mostly independent requirementsUse slices and automated import boundaries to reduce cross-team edits.
Tight delivery budget and high feature churnUse simple per-slice implementations instead of building reusable layers up front.
Strong enterprise mandate for identical persistence and workflow styleAvoid unrestricted slice-by-slice technology choices; standardize a thin composition root.
Compliance-sensitive authorization or money rulesUse cautiously: centralize those policies under explicit owners rather than accepting independent duplicates.
  • Layered — the technical-layer organization that slices replace; compare before choosing.
  • Clean — can be combined per-slice (each slice with its own mini use case) when rules need rigor.
  • Hexagonal — slices can each expose their own ports if swappable infrastructure matters.
  • Small Batch — slices ship independently.
  • Multi-Tenant SaaS — slices isolate tenants.