πŸ—οΈ Architecture

Vertical Slice Architecture

Vertical Slice Architecture

An architecture that vertically splits code by feature

πŸ“– Detailed Explanation

Vertical Slice Architecture is a software architecture pattern proposed by Jimmy Bogard and is an alternative to the traditional Layered Architecture. While layered architecture splits code horizontally by technical concerns such as Controller, Service, and Repository, Vertical Slice splits it vertically by business feature (Feature) units such as "product list retrieval," "order creation," and "payment processing." Each slice includes all the layers required for that feature (UI, business logic, data access).

The core principle of this architecture is "lower coupling and higher cohesion." In a traditional layered approach, modifying a single feature requires changing files across multiple layers, such as Controller, Service, Repository, and DTO. In Vertical Slice, by contrast, all related code lives in a single folder (or file), so the scope of a change is clear and does not affect other features. This is similar in spirit to pursuing independence between services in microservices.

Vertical Slice combines naturally with the CQRS (Command Query Responsibility Segregation) pattern. Separating each slice into a Command (write operation) and a Query (read operation) allows each to be optimized individually. For example, a Query can query the DB directly with Entity Framework and return a DTO, while a Command can pass through the domain model to validate business rules. In the .NET ecosystem, the MediatR library helps implement this structure easily through the Request/Handler pattern.

Vertical Slice Architecture can be seen as complementing, rather than replacing, Clean Architecture or Onion Architecture. The core domain logic is still kept pure, while the Use Case organization of the application layer is reorganized around Features. Especially in startups or MVP development, it is effective to implement features quickly without excessive abstraction and to gradually extract common logic as needed. However, as common logic between slices grows, duplicate code can arise, so appropriate refactoring is needed.

πŸ’» Code Example

Project Folder Structure (Feature-Based)

# 전톡적인 κ³„μΈ΅ν˜• ꡬ쑰 (Horizontal Layers)
src/
β”œβ”€β”€ Controllers/
β”‚   β”œβ”€β”€ ProductsController.cs
β”‚   β”œβ”€β”€ OrdersController.cs
β”‚   └── UsersController.cs
β”œβ”€β”€ Services/
β”‚   β”œβ”€β”€ ProductService.cs
β”‚   β”œβ”€β”€ OrderService.cs
β”‚   └── UserService.cs
β”œβ”€β”€ Repositories/
β”‚   β”œβ”€β”€ ProductRepository.cs
β”‚   β”œβ”€β”€ OrderRepository.cs
β”‚   └── UserRepository.cs
└── Models/
    β”œβ”€β”€ Product.cs
    β”œβ”€β”€ Order.cs
    └── User.cs

# Vertical Slice ꡬ쑰 (Feature 기반)
src/
β”œβ”€β”€ Features/
β”‚   β”œβ”€β”€ Products/
β”‚   β”‚   β”œβ”€β”€ GetProductList/
β”‚   β”‚   β”‚   β”œβ”€β”€ GetProductListQuery.cs
β”‚   β”‚   β”‚   β”œβ”€β”€ GetProductListHandler.cs
β”‚   β”‚   β”‚   └── ProductListDto.cs
β”‚   β”‚   β”œβ”€β”€ GetProductDetail/
β”‚   β”‚   β”‚   β”œβ”€β”€ GetProductDetailQuery.cs
β”‚   β”‚   β”‚   └── GetProductDetailHandler.cs
β”‚   β”‚   └── CreateProduct/
β”‚   β”‚       β”œβ”€β”€ CreateProductCommand.cs
β”‚   β”‚       β”œβ”€β”€ CreateProductHandler.cs
β”‚   β”‚       └── CreateProductValidator.cs
β”‚   β”œβ”€β”€ Orders/
β”‚   β”‚   β”œβ”€β”€ CreateOrder/
β”‚   β”‚   β”‚   β”œβ”€β”€ CreateOrderCommand.cs
β”‚   β”‚   β”‚   β”œβ”€β”€ CreateOrderHandler.cs
β”‚   β”‚   β”‚   └── OrderCreatedEvent.cs
β”‚   β”‚   └── GetOrderHistory/
β”‚   β”‚       β”œβ”€β”€ GetOrderHistoryQuery.cs
β”‚   β”‚       └── GetOrderHistoryHandler.cs
β”‚   └── Users/
β”‚       β”œβ”€β”€ RegisterUser/
β”‚       └── GetUserProfile/
β”œβ”€β”€ Domain/
β”‚   β”œβ”€β”€ Product.cs
β”‚   β”œβ”€β”€ Order.cs
β”‚   └── User.cs
└── Infrastructure/
    β”œβ”€β”€ AppDbContext.cs
    └── DependencyInjection.cs

Implementing Vertical Slice with C# + MediatR

// Features/Products/GetProductList/GetProductListQuery.cs
using MediatR;

namespace MyApp.Features.Products.GetProductList;

// Query: μš”μ²­ μ •μ˜
public record GetProductListQuery(
    string? Category,
    int Page = 1,
    int PageSize = 20
) : IRequest<GetProductListResult>;

// Result: 응닡 μ •μ˜
public record GetProductListResult(
    List<ProductListItem> Products,
    int TotalCount,
    int TotalPages
);

public record ProductListItem(
    int Id,
    string Name,
    decimal Price,
    string Category,
    int StockCount
);

// Features/Products/GetProductList/GetProductListHandler.cs
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace MyApp.Features.Products.GetProductList;

public class GetProductListHandler
    : IRequestHandler<GetProductListQuery, GetProductListResult>
{
    private readonly AppDbContext _db;

    public GetProductListHandler(AppDbContext db)
    {
        _db = db;
    }

    public async Task<GetProductListResult> Handle(
        GetProductListQuery request,
        CancellationToken cancellationToken)
    {
        var query = _db.Products.AsQueryable();

        // 필터링
        if (!string.IsNullOrEmpty(request.Category))
        {
            query = query.Where(p => p.Category == request.Category);
        }

        // 총 개수
        var totalCount = await query.CountAsync(cancellationToken);
        var totalPages = (int)Math.Ceiling(totalCount / (double)request.PageSize);

        // νŽ˜μ΄μ§• 및 λ§€ν•‘ (Entity β†’ DTO 직접 λ³€ν™˜)
        var products = await query
            .OrderBy(p => p.Name)
            .Skip((request.Page - 1) * request.PageSize)
            .Take(request.PageSize)
            .Select(p => new ProductListItem(
                p.Id,
                p.Name,
                p.Price,
                p.Category,
                p.Stock
            ))
            .ToListAsync(cancellationToken);

        return new GetProductListResult(products, totalCount, totalPages);
    }
}

// Features/Products/CreateProduct/CreateProductCommand.cs
using FluentValidation;
using MediatR;

namespace MyApp.Features.Products.CreateProduct;

public record CreateProductCommand(
    string Name,
    string Description,
    decimal Price,
    string Category,
    int InitialStock
) : IRequest<CreateProductResult>;

public record CreateProductResult(int ProductId, bool Success, string? Error);

// Validator (FluentValidation)
public class CreateProductValidator : AbstractValidator<CreateProductCommand>
{
    public CreateProductValidator()
    {
        RuleFor(x => x.Name)
            .NotEmpty().WithMessage("μƒν’ˆλͺ…은 ν•„μˆ˜μž…λ‹ˆλ‹€")
            .MaximumLength(100);

        RuleFor(x => x.Price)
            .GreaterThan(0).WithMessage("가격은 0보닀 컀야 ν•©λ‹ˆλ‹€");

        RuleFor(x => x.InitialStock)
            .GreaterThanOrEqualTo(0);
    }
}

// Features/Products/CreateProduct/CreateProductHandler.cs
using MediatR;

namespace MyApp.Features.Products.CreateProduct;

public class CreateProductHandler
    : IRequestHandler<CreateProductCommand, CreateProductResult>
{
    private readonly AppDbContext _db;
    private readonly IPublisher _publisher;

    public CreateProductHandler(AppDbContext db, IPublisher publisher)
    {
        _db = db;
        _publisher = publisher;
    }

    public async Task<CreateProductResult> Handle(
        CreateProductCommand request,
        CancellationToken cancellationToken)
    {
        // 도메인 μ—”ν‹°ν‹° 생성 (λΉ„μ¦ˆλ‹ˆμŠ€ κ·œμΉ™ 적용)
        var product = new Product(
            request.Name,
            request.Description,
            request.Price,
            request.Category
        );

        product.AddStock(request.InitialStock);

        _db.Products.Add(product);
        await _db.SaveChangesAsync(cancellationToken);

        // 이벀트 λ°œν–‰ (ν•„μš”μ‹œ)
        await _publisher.Publish(
            new ProductCreatedEvent(product.Id, product.Name),
            cancellationToken
        );

        return new CreateProductResult(product.Id, true, null);
    }
}

// API Endpoint (Minimal API μŠ€νƒ€μΌ)
// Program.cs λ˜λŠ” Features/Products/ProductEndpoints.cs
app.MapGet("/api/products", async (
    [AsParameters] GetProductListQuery query,
    IMediator mediator) =>
{
    var result = await mediator.Send(query);
    return Results.Ok(result);
});

app.MapPost("/api/products", async (
    CreateProductCommand command,
    IMediator mediator) =>
{
    var result = await mediator.Send(command);
    return result.Success
        ? Results.Created($"/api/products/{result.ProductId}", result)
        : Results.BadRequest(result.Error);
});

TypeScript (Node.js/NestJS Style) Vertical Slice

// src/features/orders/create-order/index.ts
// ν•˜λ‚˜μ˜ νŒŒμΌμ— λͺ¨λ“  κ΄€λ ¨ μ½”λ“œλ₯Ό 포함

import { z } from 'zod';
import { prisma } from '@/infrastructure/database';
import { EventBus } from '@/infrastructure/events';

// 1. μž…λ ₯ μŠ€ν‚€λ§ˆ (Validation)
export const CreateOrderSchema = z.object({
  customerId: z.string().uuid(),
  items: z.array(z.object({
    productId: z.string().uuid(),
    quantity: z.number().int().positive(),
  })).min(1, 'μ΅œμ†Œ 1개 μƒν’ˆμ΄ ν•„μš”ν•©λ‹ˆλ‹€'),
  shippingAddress: z.object({
    street: z.string(),
    city: z.string(),
    zipCode: z.string(),
  }),
});

export type CreateOrderInput = z.infer<typeof CreateOrderSchema>;

// 2. 좜λ ₯ νƒ€μž…
export interface CreateOrderResult {
  orderId: string;
  totalAmount: number;
  status: string;
  createdAt: Date;
}

// 3. λΉ„μ¦ˆλ‹ˆμŠ€ 둜직 (Handler)
export async function createOrder(input: CreateOrderInput): Promise<CreateOrderResult> {
  // μƒν’ˆ 쑰회 및 재고 확인
  const productIds = input.items.map(item => item.productId);
  const products = await prisma.product.findMany({
    where: { id: { in: productIds } },
  });

  // 가격 계산
  let totalAmount = 0;
  const orderItems = input.items.map(item => {
    const product = products.find(p => p.id === item.productId);
    if (!product) {
      throw new Error(`μƒν’ˆμ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€: ${item.productId}`);
    }
    if (product.stock < item.quantity) {
      throw new Error(`재고 λΆ€μ‘±: ${product.name}`);
    }

    const subtotal = product.price * item.quantity;
    totalAmount += subtotal;

    return {
      productId: product.id,
      productName: product.name,
      unitPrice: product.price,
      quantity: item.quantity,
      subtotal,
    };
  });

  // νŠΈλžœμž­μ…˜μœΌλ‘œ μ£Όλ¬Έ 생성 + 재고 차감
  const order = await prisma.$transaction(async (tx) => {
    // μ£Όλ¬Έ 생성
    const createdOrder = await tx.order.create({
      data: {
        customerId: input.customerId,
        totalAmount,
        status: 'PENDING',
        shippingAddress: input.shippingAddress,
        items: {
          create: orderItems,
        },
      },
    });

    // 재고 차감
    for (const item of input.items) {
      await tx.product.update({
        where: { id: item.productId },
        data: { stock: { decrement: item.quantity } },
      });
    }

    return createdOrder;
  });

  // 이벀트 λ°œν–‰
  await EventBus.publish('order.created', {
    orderId: order.id,
    customerId: order.customerId,
    totalAmount: order.totalAmount,
  });

  return {
    orderId: order.id,
    totalAmount: order.totalAmount,
    status: order.status,
    createdAt: order.createdAt,
  };
}

// 4. HTTP Handler (Express/Fastify 라우트)
import { Router } from 'express';

const router = Router();

router.post('/orders', async (req, res, next) => {
  try {
    const input = CreateOrderSchema.parse(req.body);
    const result = await createOrder(input);
    res.status(201).json(result);
  } catch (error) {
    next(error);
  }
});

export { router as createOrderRoute };

πŸ—£οΈ How It's Said in Practice

  • "Since we set it up with Vertical Slice, when modifying the order feature I only need to look at the Orders folder. No worry about touching other domains."
  • "When adding a new feature, just create one Feature folder and put in Query/Command/Handler, and you're done. You don't have to touch existing code."
  • "Since we use the Request/Handler pattern with MediatR, each slice is completely independent. Testing can be done per slice too."
  • "If we use CQRS together with Vertical Slice, reads can be handled quickly with Dapper, and writes can go through the domain model with EF Core."
  • "Vertical Slice Architecture is a pattern that organizes code by business feature (Feature) units rather than technical layers (Controller, Service, Repository)."
  • "It solves the Shotgun Surgery problem in traditional layered architecture, where modifying a single feature requires changes across multiple layers."
  • "Since each slice is independent, code conflicts between teams are reduced, and migration to microservices can also be done slice by slice."
  • "Combined with CQRS, Query slices can use performance-optimized direct queries and Command slices can use a rich domain model, which increases flexibility."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

  • "This feature has nothing to share with other slices, so I think it's fine to define the DTO directly inside the slice. We don't need to put it in a common Models folder."
  • "Don't call another slice's Handler directly from a Handler; please Send via MediatR. We need to keep dependency inversion."
  • "Similar Validation logic is duplicated across 3 slices. At this point, I think it's time to extract it into a common Validator."
  • "Don't return an Entity from a Query Handler; please Select into a DTO. It's a read optimization principle."

⚠️ Cautions

πŸ”— Related Terms

πŸ“š Learn More