Polski

Article · Vertical Slice Architecture · CQRS

Vertical slice architecture: code by feature, not by layer

Jimmy Bogard's Vertical Slice Architecture: every feature of the system is a separate slice from the endpoint to the database. Structure and a complete slice in C#, TypeScript, Java, Go and Python, how it combines with CQRS and the hexagon, and the risks of duplication.

By · · 11 min read

At Halina's pierogi place, the request "add order cancellation" meant changes in five places: the controller, the service, the service interface, the repository and a DTO – in four different folders. A reviewer had to jump all over the repository to understand one feature. Vertical Slice Architecture flips this layout: code is grouped by feature, not by technical layer.

2018
Jimmy Bogard's post – "Vertical Slice Architecture"
1
folder per feature – instead of 4–5 layers for every change
0
shared services "just in case" – share only once duplication appears

Context and forces

  • Changes arrive as features – the business asks for "cancellation", "order history", "catering quote", not for "a change in the service layer".
  • Different features have different complexity – the menu list is one query, while placing an order involves rules, stock and payment.
  • Layers force ceremony – every feature has to pass through all the layers, even when nothing happens in them.
  • Team conflicts – everyone changes the shared OrderService and OrderRepository classes, so everyone fights over them.

Jimmy Bogard, the author of MediatR and AutoMapper, described this approach in 2018 as a generalisation of what he had been doing for years in CQRS projects: every request is a separate object with a separate handler, so code naturally gathers around requests.

Structure

Diagram: Layers horizontally, slices vertically
ElementRole
Slice (feature)Everything one feature needs: input, logic, data, output
Request and handlerA command or query and the class that handles it (often MediatR, Wolverine or a plain method)
PipelineCross-cutting behaviours: logging, validation, transactions – once, for all slices
Shared domainOnly what slices genuinely share: aggregates, rules, value objects

What it looks like in code

Feature-based layout in five stacks

dotnet/project-tree.txt
Pierogarnia.Api/
├── Features/
│   ├── Orders/
│   │   ├── PlaceOrder.cs          ← endpoint + command + validator + handler in ONE file
│   │   ├── CancelOrder.cs
│   │   └── GetOrderHistory.cs     ← a read slice: Dapper + SQL, no domain model needed
│   ├── Menu/
│   │   └── GetMenu.cs
│   └── Catering/
│       └── RequestQuote.cs
├── Domain/                        ← only what slices genuinely share: Order, rules, value objects
├── Infrastructure/                ← DbContext, pipeline behaviours (logging, validation, transactions)
└── Program.cs                     ← app.MapFeatureEndpoints()
java/package-tree.txt
pl.pierogarnia
├── orders/
│   ├── placeorder/                ← PlaceOrderController, PlaceOrderCommand, PlaceOrderHandler
│   ├── cancelorder/
│   └── orderhistory/              ← JdbcClient query + response record
├── menu/getmenu/
└── shared/                        ← Order aggregate, common value objects
node/src-tree.txt
src/
├── features/
│   ├── orders/
│   │   ├── place-order.ts         ← route + zod schema + handler
│   │   ├── cancel-order.ts
│   │   └── order-history.ts
│   └── menu/get-menu.ts
├── domain/                        ← shared Order logic (only when duplication appears)
└── app.ts                         ← registers every feature router
go/module-tree.txt
pierogarnia/
├── internal/
│   ├── orders/
│   │   ├── placeorder/            ← package placeorder: Handler, request, response, SQL
│   │   ├── cancelorder/
│   │   └── history/
│   ├── menu/getmenu/
│   └── platform/                  ← db, middleware (logging, auth)
└── cmd/api/main.go                ← mux.Handle per feature
python/package-tree.txt
pierogarnia/
├── features/
│   ├── orders/
│   │   ├── place_order.py         ← APIRouter + pydantic models + handler
│   │   ├── cancel_order.py
│   │   └── order_history.py
│   └── menu/get_menu.py
├── domain/                        ← shared rules
└── main.py                        ← app.include_router(...) for each feature

A complete "cancel an order" slice. Notice that the variants deliberately take different approaches: in C# and Java the rule lives in the Order aggregate because other slices use it too, while in Go, TypeScript and Python a conditional UPDATE is enough. In vertical slice architecture that's allowed – each slice picks the tool for its problem.

The CancelOrder slice

Features/Orders/CancelOrder.cs
namespace Pierogarnia.Api.Features.Orders;

// Everything about "cancel an order" lives here: endpoint, request, rules, data access.
public static class CancelOrder
{
    public sealed record Command(Guid OrderId, string Reason) : IRequest<Result>;

    public sealed class Validator : AbstractValidator<Command>       // FluentValidation
    {
        public Validator() => RuleFor(c => c.Reason).NotEmpty().MaximumLength(200);
    }

    internal sealed class Handler(PierogarniaDb db, TimeProvider clock) : IRequestHandler<Command, Result>
    {
        public async Task<Result> Handle(Command cmd, CancellationToken ct)
        {
            var order = await db.Orders.FindAsync([cmd.OrderId], ct);
            if (order is null) return Result.NotFound();

            // The rule lives in the domain because PlaceOrder and the kitchen use it too.
            var cancelled = order.Cancel(cmd.Reason, clock.GetUtcNow());
            if (!cancelled) return Result.Conflict("The kitchen has already started cooking.");

            await db.SaveChangesAsync(ct);
            return Result.Ok();
        }
    }

    public static void Map(IEndpointRouteBuilder app) =>
        app.MapPost("/orders/{id:guid}/cancel", async (Guid id, CancelBody body, ISender sender) =>
            (await sender.Send(new Command(id, body.Reason))).ToHttp());

    public sealed record CancelBody(string Reason);
}
features/orders/cancel-order.ts
import { Router } from "express";
import { z } from "zod";
import { db } from "../../platform/db";

// Everything about "cancel an order" lives here: route, input schema, rules, data access.
const Body = z.object({ reason: z.string().min(1).max(200) });

export async function cancelOrder(orderId: string, reason: string): Promise<"ok" | "not-found" | "too-late"> {
  return db.$transaction(async (tx) => {
    const order = await tx.order.findUnique({ where: { id: orderId } });
    if (!order) return "not-found";
    if (order.status !== "PLACED") return "too-late"; // the kitchen has already started cooking

    await tx.order.update({
      where: { id: orderId },
      data: { status: "CANCELLED", cancelReason: reason, cancelledAt: new Date() },
    });
    return "ok";
  });
}

export const cancelOrderRouter = Router().post("/orders/:id/cancel", async (req, res) => {
  const body = Body.safeParse(req.body);
  if (!body.success) return res.status(400).json(body.error.flatten());

  const result = await cancelOrder(req.params.id, body.data.reason);
  const status = { ok: 204, "not-found": 404, "too-late": 409 }[result];
  res.status(status).end();
});
orders/cancelorder/CancelOrder.java
package pl.pierogarnia.orders.cancelorder;

// Everything about "cancel an order" lives in this package; nothing else imports it.
@RestController
class CancelOrderController {
    private final CancelOrderHandler handler;
    CancelOrderController(CancelOrderHandler handler) { this.handler = handler; }

    record CancelBody(@NotBlank @Size(max = 200) String reason) {}

    @PostMapping("/orders/{id}/cancel")
    ResponseEntity<Void> cancel(@PathVariable UUID id, @Valid @RequestBody CancelBody body) {
        return switch (handler.handle(id, body.reason())) {
            case OK -> ResponseEntity.noContent().build();
            case NOT_FOUND -> ResponseEntity.notFound().build();
            case TOO_LATE -> ResponseEntity.status(HttpStatus.CONFLICT).build();
        };
    }
}

@Service
class CancelOrderHandler {
    enum Outcome { OK, NOT_FOUND, TOO_LATE }

    private final OrderRepository orders; // shared aggregate repository from pl.pierogarnia.shared
    private final Clock clock;
    CancelOrderHandler(OrderRepository orders, Clock clock) { this.orders = orders; this.clock = clock; }

    @Transactional
    Outcome handle(UUID id, String reason) {
        return orders.findById(id)
            .map(order -> order.cancel(reason, Instant.now(clock)) ? Outcome.OK : Outcome.TOO_LATE)
            .orElse(Outcome.NOT_FOUND);
    }
}
internal/orders/cancelorder/cancelorder.go
// Package cancelorder contains the whole "cancel an order" feature.
package cancelorder

import (
	"database/sql"
	"encoding/json"
	"net/http"
	"time"
)

type Handler struct{ DB *sql.DB }

type request struct {
	Reason string `json:"reason"`
}

func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	var req request
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Reason == "" || len(req.Reason) > 200 {
		http.Error(w, "reason is required (max 200 chars)", http.StatusBadRequest)
		return
	}
	res, err := h.DB.ExecContext(r.Context(),
		`UPDATE orders SET status = 'CANCELLED', cancel_reason = $1, cancelled_at = $2
		 WHERE id = $3 AND status = 'PLACED'`, // only before the kitchen starts cooking
		req.Reason, time.Now().UTC(), r.PathValue("id"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if n, _ := res.RowsAffected(); n == 0 {
		http.Error(w, "order not found or already in the kitchen", http.StatusConflict)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

// main.go: mux.Handle("POST /orders/{id}/cancel", cancelorder.Handler{DB: db})
pierogarnia/features/orders/cancel_order.py
from datetime import datetime, timezone

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
from sqlalchemy import update
from sqlalchemy.orm import Session

from pierogarnia.platform.db import get_session
from pierogarnia.domain.orders import Order, OrderStatus

# Everything about "cancel an order" lives in this module.
router = APIRouter()


class CancelBody(BaseModel):
    reason: str = Field(min_length=1, max_length=200)


@router.post("/orders/{order_id}/cancel", status_code=204)
def cancel_order(order_id: str, body: CancelBody, session: Session = Depends(get_session)) -> None:
    result = session.execute(
        update(Order)
        .where(Order.id == order_id, Order.status == OrderStatus.PLACED)  # only before cooking starts
        .values(status=OrderStatus.CANCELLED, cancel_reason=body.reason,
                cancelled_at=datetime.now(timezone.utc))
    )
    if result.rowcount == 0:
        raise HTTPException(409, "Order not found or the kitchen has already started cooking.")
    session.commit()

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • How to deal with duplication
  • Slices, CQRS and the hexagon
  • Trade-offs
  • Migration path from layers
  • In practice
  • Anti-patterns
  • Related topics
  • Test yourself

Create a free account · Sign in