Hexagonal Architecture
Hexagonal Architecture is the Ports and Adapters pattern proposed by Alistair Cockburn. It separates the application's core logic from external technologies (DB, UI, API), making testing and maintenance easier.
Hexagonal Architecture is the Ports and Adapters pattern proposed by Alistair Cockburn. It separates the application's core logic from external technologies (DB, UI, API), making testing and maintenance easier.
Hexagonal Architecture is an architecture pattern proposed by Alistair Cockburn in 2005, and its official name is "Ports and Adapters." It is visualized as a hexagon, which gave it the name Hexagonal, and its core idea is "the application communicates with the outside world only through Ports and Adapters."
The hexagon has no special meaning. It is meant to express that there are multiple sides, visualizing that various input channels (HTTP, CLI, messages) and output channels (DB, external API, files) can be connected.
src/
├── domain/ # Application Core
│ ├── model/
│ │ ├── User.ts
│ │ └── Order.ts
│ └── service/
│ └── OrderService.ts
├── application/ # Ports (Inbound)
│ └── port/
│ └── in/
│ ├── CreateOrderUseCase.ts
│ └── GetOrderUseCase.ts
├── port/ # Ports (Outbound)
│ └── out/
│ ├── OrderRepository.ts
│ └── PaymentGateway.ts
└── adapter/ # Adapters
├── in/ # Primary Adapters (Driving)
│ ├── web/
│ │ └── OrderController.ts
│ └── cli/
│ └── OrderCLI.ts
└── out/ # Secondary Adapters (Driven)
├── persistence/
│ └── PostgresOrderRepository.ts
└── external/
└── StripePaymentGateway.ts
// application/port/in/CreateOrderUseCase.ts
export interface CreateOrderCommand {
customerId: string;
items: Array<{ productId: string; quantity: number }>;
shippingAddress: string;
}
export interface CreateOrderResult {
orderId: string;
totalAmount: number;
status: string;
}
// Inbound Port: 외부에서 애플리케이션을 호출하는 인터페이스
export interface CreateOrderUseCase {
execute(command: CreateOrderCommand): Promise<CreateOrderResult>;
}
// application/port/in/GetOrderUseCase.ts
export interface GetOrderQuery {
orderId: string;
}
export interface GetOrderUseCase {
execute(query: GetOrderQuery): Promise<OrderDTO | null>;
}
// port/out/OrderRepository.ts
import { Order } from '../../domain/model/Order';
// Outbound Port: 애플리케이션이 외부를 호출하는 인터페이스
export interface OrderRepository {
save(order: Order): Promise<void>;
findById(id: string): Promise<Order | null>;
findByCustomerId(customerId: string): Promise<Order[]>;
}
// port/out/PaymentGateway.ts
export interface PaymentRequest {
orderId: string;
amount: number;
currency: string;
}
export interface PaymentResult {
success: boolean;
transactionId?: string;
errorMessage?: string;
}
export interface PaymentGateway {
processPayment(request: PaymentRequest): Promise<PaymentResult>;
refund(transactionId: string, amount: number): Promise<PaymentResult>;
}
// domain/service/OrderService.ts
import { Order } from '../model/Order';
import { CreateOrderUseCase, CreateOrderCommand, CreateOrderResult } from '../../application/port/in/CreateOrderUseCase';
import { GetOrderUseCase, GetOrderQuery } from '../../application/port/in/GetOrderUseCase';
import { OrderRepository } from '../../port/out/OrderRepository';
import { ProductRepository } from '../../port/out/ProductRepository';
// Use Case 구현 (Application Core)
export class OrderService implements CreateOrderUseCase, GetOrderUseCase {
constructor(
private readonly orderRepository: OrderRepository,
private readonly productRepository: ProductRepository
) {}
async execute(command: CreateOrderCommand): Promise<CreateOrderResult> {
// 비즈니스 로직: 상품 가격 조회
const products = await Promise.all(
command.items.map(item => this.productRepository.findById(item.productId))
);
// 도메인 객체 생성 (순수 비즈니스 로직)
const order = Order.create({
customerId: command.customerId,
items: command.items.map((item, index) => ({
productId: item.productId,
quantity: item.quantity,
unitPrice: products[index]!.price,
})),
shippingAddress: command.shippingAddress,
});
// Outbound Port를 통해 저장 (어떤 DB인지 모름)
await this.orderRepository.save(order);
return {
orderId: order.id,
totalAmount: order.calculateTotal(),
status: order.status,
};
}
// GetOrderUseCase 구현
async execute(query: GetOrderQuery): Promise<OrderDTO | null> {
const order = await this.orderRepository.findById(query.orderId);
if (!order) return null;
return {
id: order.id,
customerId: order.customerId,
totalAmount: order.calculateTotal(),
status: order.status,
};
}
}
// adapter/in/web/OrderController.ts
import { Request, Response, Router } from 'express';
import { CreateOrderUseCase } from '../../../application/port/in/CreateOrderUseCase';
import { GetOrderUseCase } from '../../../application/port/in/GetOrderUseCase';
// Primary Adapter: HTTP 요청을 Use Case 호출로 변환
export class OrderController {
public readonly router = Router();
constructor(
private readonly createOrderUseCase: CreateOrderUseCase,
private readonly getOrderUseCase: GetOrderUseCase
) {
this.router.post('/orders', this.createOrder.bind(this));
this.router.get('/orders/:id', this.getOrder.bind(this));
}
async createOrder(req: Request, res: Response): Promise<void> {
try {
// HTTP → Use Case Command 변환
const command = {
customerId: req.body.customerId,
items: req.body.items,
shippingAddress: req.body.shippingAddress,
};
const result = await this.createOrderUseCase.execute(command);
res.status(201).json(result);
} catch (error) {
res.status(400).json({ error: (error as Error).message });
}
}
async getOrder(req: Request, res: Response): Promise<void> {
const result = await this.getOrderUseCase.execute({
orderId: req.params.id,
});
if (!result) {
res.status(404).json({ error: 'Order not found' });
return;
}
res.json(result);
}
}
// adapter/out/persistence/PostgresOrderRepository.ts
import { Pool } from 'pg';
import { Order } from '../../../domain/model/Order';
import { OrderRepository } from '../../../port/out/OrderRepository';
// Secondary Adapter: OrderRepository Port를 PostgreSQL로 구현
export class PostgresOrderRepository implements OrderRepository {
constructor(private readonly pool: Pool) {}
async save(order: Order): Promise<void> {
const client = await this.pool.connect();
try {
await client.query('BEGIN');
await client.query(
`INSERT INTO orders (id, customer_id, status, shipping_address, created_at)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (id) DO UPDATE SET status = $3`,
[order.id, order.customerId, order.status, order.shippingAddress, order.createdAt]
);
for (const item of order.items) {
await client.query(
`INSERT INTO order_items (order_id, product_id, quantity, unit_price)
VALUES ($1, $2, $3, $4)`,
[order.id, item.productId, item.quantity, item.unitPrice]
);
}
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
}
async findById(id: string): Promise<Order | null> {
const orderResult = await this.pool.query(
'SELECT * FROM orders WHERE id = $1',
[id]
);
if (orderResult.rows.length === 0) return null;
const itemsResult = await this.pool.query(
'SELECT * FROM order_items WHERE order_id = $1',
[id]
);
return Order.reconstitute({
id: orderResult.rows[0].id,
customerId: orderResult.rows[0].customer_id,
status: orderResult.rows[0].status,
shippingAddress: orderResult.rows[0].shipping_address,
items: itemsResult.rows,
});
}
}
// main.ts
import { Pool } from 'pg';
import express from 'express';
import { OrderService } from './domain/service/OrderService';
import { PostgresOrderRepository } from './adapter/out/persistence/PostgresOrderRepository';
import { PostgresProductRepository } from './adapter/out/persistence/PostgresProductRepository';
import { OrderController } from './adapter/in/web/OrderController';
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
// Secondary Adapters (바깥에서 안쪽으로)
const orderRepository = new PostgresOrderRepository(pool);
const productRepository = new PostgresProductRepository(pool);
// Application Core (Use Case 구현)
const orderService = new OrderService(orderRepository, productRepository);
// Primary Adapter
const orderController = new OrderController(orderService, orderService);
// Express 설정
const app = express();
app.use(express.json());
app.use('/api', orderController.router);
app.listen(3000);
"I'm trying to write a test, but how do I test OrderService without a DB connection?"
"It's easy because of Hexagonal Architecture. OrderRepository is an interface (Port), right? If you create an InMemoryOrderRepository for testing and inject it, you can test just the pure business logic without a DB."
"We need to switch the payment system from Stripe to Toss Payments. How long will it take?"
"Leave the PaymentGateway Port as it is and just implement a new TossPaymentGateway Adapter. You don't have to modify the business logic at all. Just changing the DI configuration is enough."
"You need a new CLI tool? OrderController was the Primary Adapter for REST, right? Just add an OrderCLI Adapter that calls the same Use Case. Business logic reuse is 100%."
Excessive interfaces: If you abstract everything into a Port, interfaces overflow. Separate only what is actually likely to be replaced into a Port.
Overkill for simple projects: Applying Hexagonal to a small CRUD-oriented project only increases boilerplate.
DTO conversion cost: The Adapter → Port → Domain → Port → Adapter flow requires multiple data conversions. Be aware of this cost and apply it only where needed.
Tip: Hexagonal Architecture shares the same core principles as Clean Architecture and Onion Architecture. If you just remember "dependencies point inward," it doesn't matter which name you use.