📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is Vertical Slice Architecture? Explain feature folders and one handler per use case, how cross-cutting concerns and shared code are handled, and the trade-offs compared with Clean Architecture.

Explains Vertical Slice Architecture: organising by feature with one handler per request, handling cross-cutting concerns and shared domain logic, and comparing its trade-offs with Clean Architecture.

Mid-Level Theory Intermediate architecture clean-architecture cqrs feature-folders minimal-apis vertical-slice

🎯 Key points

  • Organise by feature (use case), not by technical layer — the style Jimmy Bogard popularised and that maps naturally onto Minimal API route groups
  • Each slice owns its request, validator, handler, data access and response; minimise coupling between slices, maximise coupling within one
  • Slices can choose their own approach: EF Core for one, Dapper or raw SQL for another
  • Cross-cutting concerns via a pipeline: endpoint filters on route groups, middleware, decorators or mediator behaviours — not base handlers
  • Share only real domain logic (rich entities, value objects, domain services); no generic repositories, no slice calling another slice
  • Fits CQRS naturally: commands and queries as separate slices
  • Trade-off vs Clean: less ceremony and faster feature work, but rules can be duplicated unless the domain model stays rich
  • A mediator is optional; MediatR v13+ is commercially licensed (Lucky Penny Software), so choose direct handlers, a source-generated mediator or a paid licence deliberately

⏱ 30-second answer

Vertical Slice Architecture organises code by feature, not by layer: each use case — PlaceOrder, GetOrderSummary — is a slice containing its request, validator, handler, data access and response, often in one folder or file.

  • Minimise coupling between slices, maximise coupling within a slice; each slice can pick its own data approach (EF Core, Dapper).
  • Cross-cutting concerns (validation, logging, transactions, authorisation) go in a pipeline: endpoint filters, middleware or decorators/behaviours.
  • Shared code is limited to genuine domain logic, not generic repositories.

Compared with Clean Architecture, a feature change touches one folder instead of four projects. The trade-off: less shared structure, so without a rich domain model, rules can be duplicated across slices.

🗣 Full answer (senior)

How I would answer this in an interview

"Vertical Slice Architecture organises code around use cases instead of technical layers. Instead of a Controllers folder, a Services folder and a Repositories folder, I have Features/Orders/PlaceOrder containing the request record, the validator, the handler that does the work, and the endpoint mapping. The guiding rule, as Jimmy Bogard put it, is to minimise coupling between slices and maximise coupling within a slice. A new feature is a new folder; changing a feature touches one place, not four projects.

Each slice can take the simplest approach that works. A query slice might be one EF Core projection or a Dapper query straight to a DTO; a command slice might load an aggregate and call a method on it. Cross-cutting concerns — validation, logging, transactions, authorisation — go into a pipeline rather than into every handler: endpoint filters for Minimal APIs, decorators, or pipeline behaviours if you use a mediator. What's shared is real domain logic: entities that enforce invariants, value objects, domain services. For example, on [an internal case-management API] we moved from a layered design to slices and [the average PR for a new feature went from touching ~9 files across 4 projects to ~3 files in one folder].

The mistake I see is treating vertical slice as 'no rules': every handler pokes entity setters, the same discount rule gets copied into three slices, and you've rebuilt an anaemic model with less structure. Slices work best when there's still a rich domain model underneath. I'd say vertical slices optimise for change per feature; Clean optimises for protecting a shared core — and many good systems use both."


Layered/Clean vs Vertical Slice

Layered / Clean Vertical Slice
Organised by Technical concern Use case / feature
A new feature touches Several projects or folders One folder
Shared abstractions Many (repositories, services) Few, mostly domain logic
Data access One approach everywhere Per slice: EF Core, Dapper, SQL
Main risk Ceremony, sinkhole layers Duplicated rules, inconsistent slices

Handling cross-cutting concerns

Concern .NET mechanism
Validation Endpoint filter calling FluentValidation, or a pipeline behaviour
Authorisation RequireAuthorization("Policy") on the endpoint group
Transactions A filter/behaviour around commands, or the handler's own SaveChangesAsync
Logging and tracing Middleware, ActivitySource, a logging decorator
Errors IExceptionHandler + ProblemDetails

Decision table

Factor Vertical slice fits Clean core fits better
Feature independence Features rarely share rules Many features share complex rules
Team size Several devs working on separate features —
Domain complexity Low to medium per feature High, central invariants
Read vs write Read-heavy, many query shapes Write-heavy with rich invariants

Production example

A permit-management API had 140 endpoints in a three-layer design where 70% of service methods were pass-throughs. Moving to slices with a rich Permit aggregate shared underneath removed about 9,000 lines of mapping and pass-through code, and median lead time for a feature dropped from 6 days to 3.

🔍 What the interviewer is checking

Checks that the candidate understands organising by feature, how cross-cutting concerns and shared logic are handled, and the honest trade-offs against Clean Architecture.

Green flags

  • Explains "minimise coupling between slices, maximise within"
  • Names concrete pipeline mechanisms for cross-cutting concerns (endpoint filters, behaviours, decorators)
  • Keeps domain rules in entities to avoid duplication
  • Knows a mediator is optional and mentions MediatR's licence change

Red flags

  • "Vertical slice means no architecture"
  • Shares a generic repository across all slices
  • Has slices calling each other's handlers

📚 Learn in depth

1. The picture

            Layered                                Vertical slices
+------------------------------+        +--------+--------+--------+
| Controllers                  |        | Place  | Cancel | Get    |
+------------------------------+        | Order  | Order  | Order  |
| Services                     |        |        |        | Summary|
+------------------------------+        | req    | req    | query  |
| Repositories                 |        | valid. | valid. | handler|
+------------------------------+        | handler| handler| (Dapper|
| Database                     |        | (EF)   | (EF)   |  SQL)  |
+------------------------------+        +--------+--------+--------+
                                        |  shared domain model     |
                                        +--------------------------+

2. Anatomy of a slice

A typical slice has:

  1. Request: a record (PlaceOrder.Command).
  2. Validator: input rules (FluentValidation or a simple method).
  3. Handler: the use case logic, calling the domain.
  4. Response: a record shaped for this one caller.
  5. Endpoint: MapPost in a static Map method or an IEndpoint implementation discovered at start-up.

Putting them in one file (nested types) or one folder makes the feature readable top to bottom.

3. Why per-slice data access is OK

In layers, everything goes through the same repository, so every query pays for the most general abstraction. In slices, a dashboard query can be hand-written SQL with Dapper returning exactly the columns it needs, while a command uses EF Core change tracking on an aggregate. This is CQRS at the code level without separate databases.

4. Mediator or not?

Vertical slice is often associated with MediatR, but it doesn't require it. Options as of November 2026:

  • Direct handlers: endpoints inject the handler class; filters handle cross-cutting concerns. Simplest, no package.
  • MediatR: pipeline behaviours give cross-cutting concerns; since version 13 (2025) it is commercially licensed for larger organisations, which has pushed teams to evaluate alternatives.
  • Source-generated mediators (for example the Mediator package by Martin Othamar) or Wolverine: similar shape, different licensing and performance.

The architecture is the slices; a mediator is an implementation detail.

5. Keeping the domain rich

The failure mode is handlers that set properties directly. Counter it by putting invariants on entities (order.Cancel(reason, clock)), and let handlers orchestrate: load, call a domain method, save. Shared rules then live once, in the domain.

6. When slices get big

When a slice grows past a few hundred lines, extract domain logic into the model, or split the use case. When many slices need the same query, that's a signal for a shared read model or a domain service — not a generic repository.

Try it yourself

  1. Convert one controller action and its service and repository methods into a single slice file; count lines before and after.
  2. Add a validation endpoint filter to a MapGroup so every command slice in the group gets validated.
  3. Write one query slice with Dapper and one command slice with EF Core in the same project.
  4. Find a rule duplicated in two slices and move it onto the entity; write a unit test for it.
  5. Add an architecture test that slices in Features.Orders do not reference types in Features.Billing internals.

💻 Code

One slice in one file: request, validation, handler and endpoint, using Minimal APIs without a mediator.

// Features/Orders/CancelOrder.cs
namespace Shop.Features.Orders;

using Microsoft.EntityFrameworkCore;
using Shop.Domain;

public static class CancelOrder
{
    public sealed record Command(Guid OrderId, string Reason);

    public static RouteGroupBuilder MapCancelOrder(this RouteGroupBuilder group)
    {
        group.MapPost("/{orderId:guid}/cancel", async (Guid orderId, Command body, Handler handler, CancellationToken ct) =>
            await handler.HandleAsync(body with { OrderId = orderId }, ct));
        return group;
    }

    public sealed class Handler(ShopDbContext db, TimeProvider clock)
    {
        public async Task<IResult> HandleAsync(Command cmd, CancellationToken ct)
        {
            if (string.IsNullOrWhiteSpace(cmd.Reason))
                return Results.ValidationProblem(new Dictionary<string, string[]> { ["reason"] = ["A reason is required."] });

            var order = await db.Orders.SingleOrDefaultAsync(o => o.Id == cmd.OrderId, ct);
            if (order is null) return Results.NotFound();

            // The rule ("can't cancel after dispatch") lives on the entity, so every slice shares it.
            var outcome = order.Cancel(cmd.Reason, clock.GetUtcNow());
            if (!outcome.Succeeded) return Results.Conflict(new { error = outcome.Error });

            await db.SaveChangesAsync(ct);
            return Results.NoContent();
        }
    }
}
// Features/Orders/GetOrderSummary.cs — a query slice can use the simplest data access that works
namespace Shop.Features.Orders;

using Microsoft.EntityFrameworkCore;

public static class GetOrderSummary
{
    public sealed record Response(Guid Id, string Status, decimal Total, int Lines);

    public static RouteGroupBuilder MapGetOrderSummary(this RouteGroupBuilder group)
    {
        group.MapGet("/{orderId:guid}", async (Guid orderId, ShopDbContext db, CancellationToken ct) =>
            await db.Orders.AsNoTracking()
                .Where(o => o.Id == orderId)
                .Select(o => new Response(o.Id, o.Status.ToString(), o.Lines.Sum(l => l.UnitPrice * l.Quantity), o.Lines.Count))
                .SingleOrDefaultAsync(ct) is { } r ? Results.Ok(r) : Results.NotFound());
        return group;
    }
}
// Program.cs — the group applies cross-cutting concerns to every slice in it
using Shop.Features.Orders;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddScoped<CancelOrder.Handler>();
// ... AddDbContext, authentication, ProblemDetails

var app = builder.Build();
var orders = app.MapGroup("/orders").RequireAuthorization();
orders.MapCancelOrder().MapGetOrderSummary();
app.Run();

⚠ Common mistakes

  • Mistake: Treating vertical slice as permission to put all logic in handlers. Why it is wrong: rules get copied between slices and drift apart. Instead: keep invariants on entities and value objects; handlers orchestrate.
  • Mistake: Re-creating a generic repository and base handler shared by every slice. Why it is wrong: it reintroduces the layer coupling slices are meant to remove. Instead: let each slice use DbContext or Dapper directly, and share only domain logic.
  • Mistake: Slices calling other slices' handlers. Why it is wrong: it creates hidden coupling and transaction confusion. Instead: extract shared logic into the domain, or publish a domain event.
  • Mistake: Assuming vertical slice requires MediatR. Why it is wrong: the mediator is an implementation detail, and since 2025 MediatR is commercially licensed for larger organisations. Instead: choose direct handlers, a source-generated mediator or MediatR deliberately.
  • Mistake: Repeating validation, logging and transaction code in every handler. Why it is wrong: duplication and inconsistent behaviour. Instead: use endpoint filters, middleware or pipeline behaviours on a route group.
  • Mistake: No conventions at all. Why it is wrong: every slice looks different and onboarding slows. Instead: agree a slice template (request, validator, handler, endpoint) and enforce folder rules with architecture tests.

🏛 Senior insight: trade-offs

Vertical slices optimise for the unit of change, which is almost always a feature. That's why they cut lead time. But they don't remove the need for a domain model: the moment rules are shared, they must live in one place. My default for a business API is slices on the outside and a rich domain model inside — effectively Clean Architecture's core with slices replacing the Application layer's service classes. I'm explicit that slices may differ in data access, and equally explicit that domain rules may not be duplicated.

When shared rules get complex, I escalate in steps rather than reintroducing layers: first move the rule onto the entity or a value object; if it spans several entities, a domain service; if many slices need the same data shape, a shared read model or query object; if slices need to react to each other, domain events rather than calling each other. Each step keeps the coupling in the domain, where it belongs, instead of in a generic repository or base handler.

Option When it fits Cost When not to
Pure vertical slices Many independent features, simple rules each Possible duplication Complex shared invariants
Slices + rich domain core Most business APIs Discipline to keep handlers thin Trivial CRUD (just use slices)
Clean layers with services Heavily shared rules, large central domain Ceremony, cross-project changes Read-heavy apps with many query shapes

Measure files and projects touched per feature PR, and how often a bug fix has to be applied in more than one slice.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says commands and queries become separate slices. Why: Checks whether they understand CQRS levels and when separate read models are overkill.
    How to answer

    CQRS splits the model that changes state (commands) from the model that reads it (queries). It grows out of Meyer's CQS (a method either changes state or returns data), applied to whole models.

    • Write side: aggregates with invariants, loaded through repositories, committed by the unit of work.
    • Read side: flat DTOs shaped per screen, projected with Select/AsNoTracking or Dapper.

    There are levels. Separate handlers on one database is cheap and often enough. Denormalised read tables updated in the same transaction stay consistent. A separate read store fed by events scales reads but is eventually consistent, so the UI needs read-your-writes or "processing" states.

    CQRS doesn't need MediatR or event sourcing. It's overkill for CRUD where reads and writes have the same shape. The trade-off is optimised, simple models on each side against more moving parts and, at the top level, stale reads.

  2. When: Candidate accepts some duplication between slices. Why: Checks whether they can judge when duplication is acceptable and when it hides a shared rule.
    How to answer

    Duplication is acceptable when the copies are coincidentally similar but represent different knowledge, so they may change independently. Merging them creates the wrong abstraction: a shared helper that gains a flag for each caller. I also accept duplication across bounded contexts and microservices, where a shared model would couple teams and deployments, and in tests, where readable, self-contained cases beat clever shared setup. In review I justify it with three facts: who owns each copy, whether they change for the same reason, and what coupling a shared version would add.

  3. When: Candidate compares slices with Clean Architecture layers. Why: Checks whether they understand what Clean's layers protect and what slices give up.
    How to answer

    Clean Architecture (Robert C. Martin, 2012) arranges code in concentric layers with one rule: source code dependencies point inwards.

    • Domain (centre): entities, value objects, domain events and business rules — no EF Core, no ASP.NET Core.
    • Application: use cases (commands, queries, handlers) plus the interfaces they need, such as IOrderRepository or IEmailSender.
    • Infrastructure: implements those interfaces with EF Core, Azure Service Bus, Blob Storage.
    • Presentation: endpoints and the composition root that wires implementations to interfaces.

    The key move is dependency inversion: the database depends on the domain, not the other way round. The trade-off: testable, technology-independent rules in exchange for more projects, interfaces and mapping — overkill for simple CRUD.

🛠 Real-world problems: how you handle them

Discount rule drifts between three slices
Situation
An [e-commerce] API organised as vertical slices, [5] developers, [~90] endpoints. Finance reported that customers were sometimes charged the full price after applying a valid loyalty discount.
Signals
Support tickets about wrong totals ([~1.2%] of orders); totals on the basket page differed from the invoice; Application Insights traces showed the discount applied in `GetBasket` but not in `PlaceOrder`.
Investigation
Searched for the discount calculation and found three copies (basket view, place order, invoice) with different rounding and expiry checks. `git blame` showed one copy updated for a new tier, the others not. Wrote failing unit tests reproducing each case.
Resolution
Immediately: patched `PlaceOrder` to match and refunded affected orders. Then: moved the rule into a `LoyaltyDiscount` domain service and a `Money` value object with one rounding rule; all three slices call it.
Prevention
Unit tests on the domain service with edge cases; a code review checklist item ('is this a business rule? put it in the domain'); an architecture test that slices don't reference each other; a monthly check of duplicated code with an analyser report.

How to tell it (STAR)

**S:** On [our e-commerce API], about [1.2%] of orders were charged without a valid loyalty discount. **T:** I picked up the investigation and needed to stop the loss and stop it recurring. **A:** I traced it to three copies of the discount rule in three slices that had drifted. I patched the order path, then moved the rule into a domain service with a `Money` value object, wrote edge-case tests, and proposed in our architecture notes that business rules always live in the domain while slices stay thin. **R:** Wrong totals dropped to [zero] in the next [quarter], and the next discount change was a [one-file] edit.

↩ Usually asked after

More in Application Architectures

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me