Vertical Slice Architecture
Vertical Slice Architecture
An architecture that vertically splits code by feature
Vertical Slice Architecture
An architecture that vertically splits code by feature
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.
# μ ν΅μ μΈ κ³μΈ΅ν ꡬ쑰 (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
// 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);
});
// 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 };
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free