Course contents

10. Software Architecture Lesson 4 of 10

Vertical Slice Architecture

Reorganise an order service from horizontal layers into feature slices and watch a feature change shrink from three shared files to one folder.

13 minIntermediate9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Vertical slices group code by feature: endpoint, request, validation, handler and data access in one place.
  • Requests stay inside their slice; coupling is high within a slice and low between slices.
  • Feature changes, the most common kind, stay local instead of touching shared layer classes.
  • Each slice picks its own data access, which pairs naturally with separating commands and queries.
  • Share domain rules and infrastructure deliberately; avoid slices calling slices; tolerate small duplication.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Vertical slice architecture organises an application by feature instead of by technical layer. Each slice holds everything one request needs, from the endpoint to the database: the request and response types, validation, the handler with its logic and its data access. The term was popularised by Jimmy Bogard around 2018.

Features/
  PlaceOrder/     PlaceOrderEndpoint.cs  PlaceOrderRequest.cs  PlaceOrderValidator.cs  PlaceOrderHandler.cs
  CancelOrder/    ...
  OrderHistory/   OrderHistoryEndpoint.cs  OrderHistoryQuery.cs  OrderRow.cs
Domain/           Order.cs
Infrastructure/   AppDbContext.cs

The guiding principle: minimise coupling between slices and accept, even embrace, coupling within a slice.

Why it exists

Requirements arrive as features ("show the item count in the order history"), but layered code is cut horizontally. Every feature change touches the controller, the service and the repository, classes shared by every other feature, which grow without limit and become merge-conflict hot spots. Layers also impose the same abstractions on every request, whether it is a complex command or a one-line read. Slicing by feature aligns the code with the way it changes.

How it works

One request, one slice. A minimal-API endpoint maps the HTTP request to a request object and calls its handler. The handler validates, does the work and returns a response. In .NET this is often wired with a mediator library or with plain classes registered in DI; neither is required.

public static class OrderHistory
{
    public sealed record OrderRow(Guid Id, DateTime PlacedAt, decimal Total, int ItemCount);

    public static async Task<IReadOnlyList<OrderRow>> Handle(Guid customerId, IDbConnection db) =>
        (await db.QueryAsync<OrderRow>(
            """
            SELECT o.Id, o.PlacedAt, o.Total, COUNT(l.Id) AS ItemCount
            FROM Orders o JOIN OrderLines l ON l.OrderId = o.Id
            WHERE o.CustomerId = @customerId
            GROUP BY o.Id, o.PlacedAt, o.Total
            """, new { customerId })).AsList();
}

Each slice chooses its tools. A command that enforces business rules loads the Order aggregate with EF Core and saves it in a transaction. A read projects straight from SQL into its response type. This is a natural fit for CQRS-style separation.

Shared code is deliberate. Slices share the domain model where real business rules live, infrastructure such as the DbContext, and cross-cutting behaviour (logging, validation, authorisation) through pipeline behaviours or middleware. They do not call each other's handlers.

When to use it

  • Applications whose changes are mostly feature additions and modifications: typical web APIs and line-of-business systems.
  • Teams where several people work on different features at once.
  • Codebases where reads and writes need very different data access.
  • Inside the modules of a modular monolith, as the structure of each module.

When not to

  • Rich domains with complex invariants shared by many features, unless combined with a solid domain model that slices use.
  • Teams without agreed conventions: each slice may grow its own style.
  • Very small services where a single file per endpoint is already the whole application.

Trade-offs

Choice You gain You pay
Group by feature Changes stay local; easy to find and delete a feature Technical concerns spread across folders
Slice-specific data access Simplest fit per request Several data access styles to know
Tolerating duplication Independent slices Some repeated mapping and validation
Small shared kernel Rules exist once A shared part that must be guarded from growth

Alternatives

  • Layered architecture: uniform and familiar, but feature changes cut across shared layers.
  • Clean / hexagonal architecture: protects a rich domain behind ports; often combined with slices for the use cases ("slices on top of a clean core").
  • Modular monolith: slices organise code inside a module; modules organise slices by business capability.

Failure modes

  • Slices calling slices: one handler invoking another, often through the mediator, recreates hidden coupling.
  • Shared kernel creep: everything "might be reused", so the shared folder becomes the old service layer under a new name.
  • Logic scattered in handlers: business rules duplicated across slices instead of living once in the domain.
  • Inconsistent slices: without conventions, each slice handles errors, validation and logging differently.

In production

Agree on a slice template (endpoint, request, validator, handler, response) and on what may be shared. Put cross-cutting concerns in middleware or pipeline behaviours so slices stay small. Test slices through their endpoint or handler with a real database where data access is slice-specific. Architecture tests can forbid references between Features.* namespaces.

Common misconceptions

  • "Vertical slices mean no layers at all." Each slice still separates HTTP, logic and data concerns inside itself; it just does not share layer classes with other features.
  • "You need a mediator library." Slices are about code organisation. Plain handler classes work.
  • "Duplication is always a smell." Between slices, a little duplication is often cheaper than coupling.
  • "Slices are microservices." They live in one application and one deployment.

Interview angle

Explain the axis change: layers group by technical role, slices by feature, so the most common change touches one place. Mention per-slice data access and the link to CQRS, then show maturity about the downsides: how you keep shared code small, avoid slices calling slices, and keep conventions consistent. Combining slices with a domain model for rich rules is a strong closing point.

Model assumptions

This lesson is a scripted illustration, not a simulation: the engine models running components, not how code is organised in folders. Every packet is placed by hand. Request packets show which classes a request passes through; change pulses show which files a change edits; the error packet marks the coupling created by a cross-slice call. Packets are slowed to 30–45 ms per hop so they can be followed; in-process calls take microseconds. Folder and class names are examples.

The lesson as textEvery step of the simulation, written out.
  1. 1. Three features, one stack of shared classes

    The shop has three order features: place an order, cancel one, and show the order history. The dashed columns mark them. The code, though, is organised by layer on the left: one OrdersController, one OrderService, one OrderRepository.

    Watch three requests arrive. Every one of them passes through the same three classes, so each class holds a little of every feature and grows with each new one.

    Scene: Three requests (place, cancel, history) all travel from the shoppers through the same OrdersController, OrderService and OrderRepository on the left to SQL Server and back. The three feature columns are still empty.

    Key idea: Layers group code by technical role, so every class collects pieces of every feature.

  2. 2. One feature change, three shared files

    Product asks for the item count on each row of the order history. In the layered code that means editing the history query in OrderRepository, the DTO mapping in OrderService and the action in OrdersController.

    Three files, and each one is shared by all three features. The change is small, but the review has to check that place and cancel still work, and two developers on different features will collide in the same files.

    Scene: Change pulses run from OrderRepository to OrderService to OrdersController: all three shared classes are edited for one history change.

    Key idea: In a layered codebase a feature change cuts across every layer and lands in shared files.

  3. 3. Cut the code by feature instead

    Vertical slice architecture moves each feature’s code into its own folder: Features/PlaceOrder/ holds the endpoint, the request and response types, the validator and the handler. A request no longer travels through shared layers; it enters its slice and stays there.

    What the slices do share sits below them: the AppDbContext and the Order entity. Here is a new order going through its slice.

    Scene: The layered stack is gone. Each feature column now holds an endpoint and a handler. A new order travels from the shoppers into the PlaceOrder endpoint, its handler, the shared DbContext and SQL Server, and back.

    Key idea: A slice holds everything one feature needs, from endpoint to data access.

  4. 4. Each request stays in its own column

    Now the same three requests as before. Each one goes down its own column: place through the PlaceOrder slice, cancel through CancelOrder, history through OrderHistory. No endpoint or handler is used by two features.

    To understand a feature you open one folder. To delete a feature you delete one folder.

    Scene: Three requests travel in parallel, each down its own feature column: place and cancel through their handlers to the shared DbContext and SQL Server, history through its query straight to SQL Server.

    Key idea: Coupling inside a slice is high on purpose; coupling between slices is minimal.

  5. 5. The same change stays in one slice

    The item-count request again. This time it touches OrderHistory.Query (the SQL gets a COUNT) and the response record next to the endpoint, two files in one folder.

    PlaceOrder and CancelOrder are not touched, so there is nothing to retest there and nobody else’s work to collide with. Changes that follow features stay local when the code follows features.

    Scene: A single change pulse runs from OrderHistory.Query to the history endpoint. The PlaceOrder and CancelOrder columns stay dim and are labelled untouched.

    Key idea: When code is organised like the requirements, a feature change is a local change.

  6. 6. Each slice picks its own data access

    Slices do not have to share one way of reaching the database. PlaceOrder loads and saves the Order aggregate with EF Core, inside a transaction, because it enforces rules. OrderHistory is a read: it runs one SQL projection with Dapper straight into its response rows, no change tracking and no domain model.

    Each slice uses the simplest tool that fits it. This is also where vertical slices meet CQRS: commands and queries are separate slices that can be optimised separately.

    Scene: The PlaceOrder handler reaches SQL Server through the shared EF Core DbContext; the OrderHistory query goes straight to SQL Server with a single projection.

    Key idea: Slices choose their own data access: a rich model for commands, a lean projection for reads.

  7. 7. Temptation: call another slice’s handler

    Cancelling needs the same stock rule PlaceOrder applies, in reverse. The quick fix: have CancelOrder.Handler call PlaceOrder.Handler, or send its command through MediatR.

    Now the slices are coupled through each other’s request types and side effects. A change to PlaceOrder can break cancelling, and the call chain is hidden behind a mediator. Slices calling slices rebuild the tangle that slicing removed.

    Scene: A new arrow runs from the CancelOrder handler to the PlaceOrder handler. A call goes across and an error comes back, showing how a change in one slice now breaks the other.

    Key idea: Slices should not call each other’s handlers; that recreates hidden coupling.

  8. 8. Share on purpose: push rules into the domain

    Remove the cross-slice call. The stock rule belongs to the domain, not to a feature: Order.Cancel() releases the reserved stock, and both slices use the shared Order entity. Each slice stays independent; the rule exists once.

    For everything else, accept a little duplication. Two slices with similar mapping code is cheaper than an abstraction that couples them. Extract shared code when the third copy shows a real pattern, not before.

    Scene: The arrow between the two handlers is gone. A cancel request travels down the CancelOrder column to the shared Order entity and SQL Server and back; the rule is shown on the shared node.

    Key idea: Share domain rules and infrastructure deliberately; tolerate small duplication between slices.

  9. 9. Organise by what changes together

    Vertical slices organise code the way requirements arrive: by feature. Changes stay inside one folder, each slice picks its own data access, and only real domain rules and infrastructure are shared.

    The price: duplication between slices, more discipline about what goes into the shared part, and no layer that forces structure on a team that has not agreed on conventions. It suits feature-driven applications; rich domains often combine slices with a clean domain core.

    Scene: Three feature columns, each with its own endpoint and handler, above a small shared DbContext and Order entity and SQL Server.

    Key idea: Group code by feature so it changes in one place; share only what is truly common.