Cloud & ArchitectureComplete guide

Vertical Slice Architecture

Vertical Slice Architecture organises an application around features rather than technical layers, so each feature contains its own endpoint, handler, validation, and data access in one place.

Overview

Instead of grouping all controllers together, all repositories together, and all services together, Vertical Slice Architecture puts everything a single use case needs into one folder or file. Changes to one feature touch only that slice, reducing the risk of breaking unrelated features. MediatR is a common companion because it lets each slice define its own command or query and handler without a shared service class.

What you will learn

  • Organize behavior by use case instead of technical role.
  • Design explicit command and query contracts with validation and authorization.
  • Choose deliberately between slice-local behavior and stable shared infrastructure.
  • Use purpose-built projections and mutations without leaking persistence models.
  • Apply cross-cutting policies consistently around handler execution.
  • Test each slice through its observable behavior boundary.

Prerequisites

  • ASP.NET Core, dependency injection, async C#, and automated testing.
  • Commands, queries, persistence, validation, authorization, and transaction basics.
  • Understanding of cohesion, coupling, and feature ownership.

When to use Vertical Slice Architecture

Good fit

  • Layered folders scatter each feature across technical roles.
  • Commands and queries need tailored contracts and data access.
  • Teams own capabilities end to end.

Choose another approach when

  • A rich shared domain model would be duplicated.
  • Slices would copy volatile policy.
  • The application is too small to benefit.

Key concepts

Feature folders

All code for one feature—endpoint, handler, validator, response type—lives in one folder, making the feature easy to find, change, and delete.

Minimal coupling between slices

Slices share as little as possible. Common infrastructure like database access is shared, but business logic stays inside the slice that owns it.

Each slice owns its contract

A slice defines the request and response types it needs, rather than reusing shared DTOs that accumulate properties for many callers.

Contrast with layered architecture

Layers separate concerns horizontally across the whole application; vertical slices separate concerns vertically per feature, favouring cohesion over uniform abstraction.

Behavior boundary

A command or query defines one capability with explicit input, output, validation, authorization, and side effects.

Slice-local data access

Each behavior uses the projection or mutation it needs rather than a universal repository contract.

Cross-cutting pipeline

Validation, tracing, transactions, and idempotency wrap handlers without moving feature rules into middleware.

Independent evolution

High cohesion makes a feature easier to understand, optimize, replace, test, or delete as one unit.

Architecture

Each feature is a self-contained vertical slice from HTTP endpoint to data access; shared infrastructure sits below all slices but no slice depends on another.

HTTP endpoints
Feature slices
Shared infrastructure
Database

Conceptual architecture · Adapt to your system context

Implementation walkthrough

The support-ticket sample gives create and get behaviors their own request, result, rules, and handler while reusing only stable state infrastructure.

  1. 01
    Inventory use cases

    Name commands and queries, actors, outcomes, and failures.

  2. 02
    Create one slice

    Co-locate entry point, contract, handler, mapping, and validation.

  3. 03
    Design data access

    Use focused projections and explicit mutations.

  4. 04
    Secure behavior

    Apply identity, resource authorization, tenancy, and non-disclosure.

  5. 05
    Add policies

    Wrap validation, tracing, transactions, and idempotency.

  6. 06
    Test behavior

    Exercise valid, invalid, missing, unauthorized, and rollback paths.

  7. 07
    Control sharing

    Extract stable semantics and enforce dependency rules.

Code example

A single file contains the endpoint, command, handler, and response for the Place Order feature—nothing is shared with other features unless it truly belongs to shared infrastructure.

PlaceOrder/
// Features/Orders/PlaceOrder.cs

public static class PlaceOrder
{
    public sealed record Command(Guid CustomerId, IReadOnlyList<OrderLine> Lines)
        : IRequest<Guid>;

    public sealed class Validator : AbstractValidator<Command>
    {
        public Validator()
        {
            RuleFor(x => x.CustomerId).NotEmpty();
            RuleFor(x => x.Lines).NotEmpty();
        }
    }

    public sealed class Handler(AppDbContext db) : IRequestHandler<Command, Guid>
    {
        public async Task<Guid> Handle(Command command, CancellationToken ct)
        {
            var order = new Order(command.CustomerId, command.Lines);
            db.Orders.Add(order);
            await db.SaveChangesAsync(ct);
            return order.Id;
        }
    }

    public static void MapEndpoint(IEndpointRouteBuilder app) =>
        app.MapPost("/api/orders", async (Command command, IMediator mediator, CancellationToken ct) =>
        {
            var id = await mediator.Send(command, ct);
            return Results.Created($"/api/orders/{id}", new { id });
        }).RequireAuthorization();
}

Testing strategy

Test observable feature behavior.

  • Test valid, invalid, missing, and unauthorized inputs.
  • Verify endpoint contracts.
  • Test real-provider translation and transactions.
  • Prove failures do not mutate state.
  • Test idempotent retries.
  • Keep fixtures feature-focused.

Security considerations

Each slice owns resource security.

  • Derive actor and tenant from verified claims.
  • Authorize resources inside handlers.
  • Use non-disclosing outcomes.
  • Bound input and work.
  • Audit without sensitive content.

Performance and scalability

Tailored data access makes work visible.

  • Project needed fields only.
  • Avoid unnecessary aggregate loading.
  • Measure queries and latency per slice.
  • Use pagination and cancellation.
  • Optimize hot slices independently.

Deployment and operations

Slices deploy together, so evolve contracts safely.

  • Use expand-contract migrations.
  • Version contracts deliberately.
  • Trace by slice and outcome.
  • Smoke-test critical behaviors.
  • Define rollback and flags.

Common problems and fixes

Slices call other handlers.

Likely cause: Ownership is unclear.

Fix: Use a domain or module contract.

Identity code repeats.

Likely cause: Stable policy is not shared.

Fix: Centralize identity, not resource rules.

Shared DTO churns.

Likely cause: Behaviors are coupled.

Fix: Use slice-owned contracts.

Handlers grow large.

Likely cause: Several behaviors accumulated.

Fix: Split use cases and extract invariants.

Tests need everything.

Likely cause: The seam is unclear.

Fix: Test the public slice boundary.

Queries cause round trips.

Likely cause: Generic repositories hide work.

Fix: Use a tailored projection.

Best practices

  • Co-locate the endpoint, handler, validator, and response type in a single file or folder per feature.
  • Share only what is genuinely shared—database context, auth helpers, base types—not business logic.
  • Let each slice define the exact request and response shape it needs instead of inheriting a bloated shared DTO.
  • Use integration tests per slice to verify the full path from HTTP to database without shared test setup getting in the way.
  • Keep resource authorization and non-disclosure inside the owning slice.
  • Prefer purpose-built projections and mutations over universal repositories.
  • Centralize stable execution policies without centralizing feature rules.
  • Enforce feature dependency rules automatically.

Production checklist

  • Slices represent named commands or queries.
  • Contracts are slice-owned.
  • Security, idempotency, and transactions are defined.
  • Shared code has stable semantics.
  • Data work is bounded and observable.
  • Dependency rules fail builds.
  • Contracts evolve safely.
  • Runbooks identify slice failures.

Common interview questions

What is the main advantage of Vertical Slice Architecture over a traditional layered approach?

Changes to one feature touch only that slice, reducing the risk of breaking unrelated features and making it easier to reason about what a change affects. Layered architectures spread one feature across many layers, so a change ripples horizontally.

Does Vertical Slice Architecture replace Clean Architecture?

Not necessarily—they answer different questions. Clean Architecture defines where dependencies point; Vertical Slice Architecture defines how to organise code within a project. You can use feature folders inside a clean architecture structure.

When is Vertical Slice Architecture a poor fit?

When features share significant business logic or domain rules that would be duplicated across slices, a richer shared domain model may be a better fit than pure vertical isolation.

Does it require MediatR?

No. A mediator is an optional dispatch and pipeline mechanism; endpoints may call focused handlers directly.

What should slices share?

Stable infrastructure and genuinely shared domain semantics, not contracts created merely to reduce file count.

Can slices access a database directly?

Yes, when they respect ownership, authorization, transaction, observability, and testing requirements.

How should duplication be handled?

Accept small local duplication and extract only repeated semantics that have proven stable across behaviors.

Dedicated GitHub sample

Clone, run, test, and modify the focused implementation created for this guide.

Verified sample

Vertical Slice Support

A .NET 10 support workflow demonstrating feature-owned commands, queries, validation, mapping, customer-scoped disclosure, and behavior-focused tests.

.NET 10Vertical Slice ArchitectureCQRSxUnit
dedicated-samplefeature-folderscommand-querynegative-testing
Run
dotnet run --project src/VerticalSliceSupport
Test
dotnet test VerticalSliceSupport.slnx