English

Artykuł · Architektura pionowych wycinków · CQRS

Architektura pionowych wycinków: kod według funkcji, nie według warstw

Vertical Slice Architecture Jimmy'ego Bogarda: każda funkcja systemu to osobny wycinek od endpointu po bazę. Struktura i kompletny wycinek w C#, TypeScript, Javie, Go i Pythonie, połączenie z CQRS i heksagonem oraz ryzyka duplikacji.

Autor · · 10 min czytania

W pierogarni Haliny prośba „dodajcie anulowanie zamówienia” oznaczała zmiany w pięciu miejscach: kontroler, serwis, interfejs serwisu, repozytorium i DTO – w czterech różnych folderach. Recenzent musiał skakać po całym repozytorium, żeby zrozumieć jedną funkcję. Architektura pionowych wycinków (ang. Vertical Slice Architecture) odwraca ten układ: kod grupuje się według funkcji, a nie według warstw technicznych.

2018
wpis Jimmy'ego Bogarda – „Vertical Slice Architecture”
1
katalog na funkcję – zamiast 4–5 warstw na każdą zmianę
0
wspólnych serwisów „na wszelki wypadek” – współdzielenie dopiero, gdy pojawi się duplikacja

Kontekst i siły

  • Zmiany przychodzą jako funkcje – biznes prosi o „anulowanie”, „historię zamówień”, „wycenę cateringu”, a nie o „zmianę w warstwie serwisów”.
  • Różne funkcje mają różną złożoność – lista menu to jedno zapytanie, a złożenie zamówienia to reguły, magazyn i płatność.
  • Warstwy wymuszają ceremonię – każda funkcja musi przejść przez wszystkie warstwy, nawet gdy nic w nich nie robi.
  • Konflikty w zespole – wspólne klasy OrderService i OrderRepository zmienia każdy, więc każdy się o nie kłóci.

Jimmy Bogard, autor MediatR i AutoMappera, opisał to podejście w 2018 roku jako uogólnienie tego, co robił od lat w projektach z CQRS: każde żądanie to osobny obiekt z osobnym handlerem, więc naturalnie grupuje się kod wokół żądań.

Struktura

Diagram: Warstwy poziomo, wycinki pionowo
ElementRola
Wycinek (feature)Wszystko, czego potrzebuje jedna funkcja: wejście, logika, dane, wyjście
Żądanie i handlerKomenda lub zapytanie i klasa, która je obsługuje (często MediatR, Wolverine lub zwykła metoda)
Potok (pipeline)Zachowania przekrojowe: logowanie, walidacja, transakcje – raz, dla wszystkich wycinków
Wspólna domenaTylko to, co naprawdę współdzielą wycinki: agregaty, reguły, obiekty wartości

Jak to wygląda w kodzie

Układ według funkcji w pięciu stosach

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

Kompletny wycinek „anuluj zamówienie”. Zauważ, że warianty celowo różnią się podejściem: w C# i Javie reguła siedzi w agregacie Order, bo używają jej też inne wycinki, a w Go, TypeScripcie i Pythonie wystarcza warunkowy UPDATE. W architekturze wycinków to dozwolone – każdy wycinek dobiera narzędzie do problemu.

Wycinek CancelOrder

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()

Dalsza część artykułu dla zalogowanych

Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:

  • Jak radzić sobie z duplikacją
  • Wycinki, CQRS i heksagon
  • Kompromisy
  • Ścieżka migracji z warstw
  • W praktyce
  • Antywzorce
  • Powiązane tematy
  • Sprawdź się

Załóż darmowe konto · Zaloguj się