🏗️ Architecture

Hexagonal Architecture

Hexagonal Architecture / Ports and Adapters Pattern

A software architecture style also known as the Ports and Adapters pattern. It completely separates the application's core business logic (domain) from the outside world (UI, database, external APIs), so changes in technical details do not affect the business logic. It implements the Dependency Inversion Principle (DIP) at the architecture level and is the theoretical basis for Clean Architecture and Onion Architecture.

📖 Detailed Explanation

Hexagonal Architecture is an architectural pattern proposed by Alistair Cockburn in 2005. It is called "hexagonal" because the application is visualized as a polygon with multiple sides (ports). The actual number of sides does not matter; the key is to clearly separate the inside of the application from the outside.

The core concepts of this architecture are Port and Adapter. A Port is an interface at the application boundary that defines how the application interacts with the outside. An Adapter implements this Port and connects it to the actual external technology (MySQL, Redis, REST API, etc.). Domain logic knows only the Port (interface), not the concrete Adapter.

Ports fall into two types. A Driving Port is an interface through which the outside calls the application (e.g., REST Controller → Application Service). A Driven Port is an interface the application uses to call external systems (e.g., Repository Interface → Database). A Driving Adapter receives user requests and passes them to the application, while a Driven Adapter passes the application's requests to external systems.

In practice, Hexagonal Architecture greatly improves testability, technology independence, and maintainability. With only a Repository interface, you can unit test business logic without a real DB, and even if you switch from PostgreSQL to MongoDB, the domain code does not need to change. It is especially effective when used together with DDD (Domain-Driven Design).

Key concepts

Port

An interface at the application boundary. The contract through which the domain communicates with the outside. Defined independently of technology.

Adapter

A Port implementation. Translation code that connects a specific technology (HTTP, SQL, gRPC, etc.) to a Port.

Driving (Primary)

The side that "drives" the application. UI, API, tests, and so on call the application.

Driven (Secondary)

The side "driven" by the application. Infrastructure such as databases, message queues, and external APIs.

💻 Code Example

TypeScript - Order system Hexagonal structure

// ===== 프로젝트 구조 =====
// src/
// ├── domain/           # 도메인 레이어 (순수 비즈니스 로직)
// │   ├── model/        # 도메인 엔티티, 값 객체
// │   ├── service/      # 도메인 서비스
// │   └── port/         # 포트 인터페이스
// ├── application/      # 애플리케이션 레이어 (유스케이스)
// │   └── usecase/      # 애플리케이션 서비스
// └── infrastructure/   # 인프라스트럭처 레이어 (어댑터)
//     ├── adapter/
//     │   ├── in/       # Driving Adapters (Web, CLI)
//     │   └── out/      # Driven Adapters (DB, External API)
//     └── config/       # 의존성 주입 설정

// ===== Domain Layer =====

// domain/model/Order.ts - 도메인 엔티티
export class Order {
  private constructor(
    public readonly id: OrderId,
    public readonly customerId: CustomerId,
    private _items: OrderItem[],
    private _status: OrderStatus,
    public readonly createdAt: Date
  ) {}

  static create(customerId: CustomerId, items: OrderItem[]): Order {
    if (items.length === 0) {
      throw new EmptyOrderError();
    }
    return new Order(
      OrderId.generate(),
      customerId,
      items,
      OrderStatus.PENDING,
      new Date()
    );
  }

  get items(): readonly OrderItem[] {
    return this._items;
  }

  get status(): OrderStatus {
    return this._status;
  }

  get totalAmount(): Money {
    return this._items.reduce(
      (sum, item) => sum.add(item.subtotal),
      Money.zero()
    );
  }

  confirm(): void {
    if (this._status !== OrderStatus.PENDING) {
      throw new InvalidOrderStateError(this._status, 'confirm');
    }
    this._status = OrderStatus.CONFIRMED;
  }

  cancel(): void {
    if (this._status === OrderStatus.SHIPPED) {
      throw new CannotCancelShippedOrderError(this.id);
    }
    this._status = OrderStatus.CANCELLED;
  }
}

// domain/model/valueObjects.ts
export class OrderId {
  constructor(public readonly value: string) {}

  static generate(): OrderId {
    return new OrderId(crypto.randomUUID());
  }

  equals(other: OrderId): boolean {
    return this.value === other.value;
  }
}

export class Money {
  constructor(
    public readonly amount: number,
    public readonly currency: string = 'KRW'
  ) {}

  static zero(): Money {
    return new Money(0);
  }

  add(other: Money): Money {
    if (this.currency !== other.currency) {
      throw new CurrencyMismatchError();
    }
    return new Money(this.amount + other.amount, this.currency);
  }
}

// ===== Ports (인터페이스) =====

// domain/port/in/OrderUseCase.ts - Driving Port
export interface CreateOrderUseCase {
  execute(command: CreateOrderCommand): Promise;
}

export interface GetOrderUseCase {
  execute(query: GetOrderQuery): Promise;
}

export interface CancelOrderUseCase {
  execute(command: CancelOrderCommand): Promise;
}

// domain/port/out/OrderRepository.ts - Driven Port
export interface OrderRepository {
  save(order: Order): Promise;
  findById(id: OrderId): Promise;
  findByCustomerId(customerId: CustomerId): Promise;
}

// domain/port/out/PaymentGateway.ts - Driven Port
export interface PaymentGateway {
  processPayment(orderId: OrderId, amount: Money): Promise;
  refund(paymentId: PaymentId): Promise;
}

// domain/port/out/NotificationService.ts - Driven Port
export interface NotificationService {
  sendOrderConfirmation(order: Order): Promise;
  sendOrderCancellation(order: Order): Promise;
}

// domain/port/out/EventPublisher.ts - Driven Port
export interface DomainEventPublisher {
  publish(event: DomainEvent): Promise;
}

// ===== Application Layer (Use Cases) =====

// application/usecase/CreateOrderService.ts
export class CreateOrderService implements CreateOrderUseCase {
  constructor(
    private readonly orderRepository: OrderRepository,
    private readonly paymentGateway: PaymentGateway,
    private readonly eventPublisher: DomainEventPublisher
  ) {}

  async execute(command: CreateOrderCommand): Promise {
    // 1. 도메인 객체 생성 (비즈니스 규칙 검증)
    const items = command.items.map(item =>
      OrderItem.create(
        new ProductId(item.productId),
        item.quantity,
        new Money(item.price)
      )
    );

    const order = Order.create(
      new CustomerId(command.customerId),
      items
    );

    // 2. 결제 처리 (Driven Port 사용)
    const paymentResult = await this.paymentGateway.processPayment(
      order.id,
      order.totalAmount
    );

    if (!paymentResult.isSuccess) {
      throw new PaymentFailedError(paymentResult.errorMessage);
    }

    // 3. 주문 확정 (도메인 로직)
    order.confirm();

    // 4. 저장 (Driven Port 사용)
    await this.orderRepository.save(order);

    // 5. 이벤트 발행 (Driven Port 사용)
    await this.eventPublisher.publish(
      new OrderCreatedEvent(order.id, order.customerId, order.totalAmount)
    );

    return OrderDto.from(order);
  }
}

// ===== Infrastructure Layer (Adapters) =====

// infrastructure/adapter/in/web/OrderController.ts - Driving Adapter
@Controller('/api/orders')
export class OrderController {
  constructor(
    private readonly createOrderUseCase: CreateOrderUseCase,
    private readonly getOrderUseCase: GetOrderUseCase,
    private readonly cancelOrderUseCase: CancelOrderUseCase
  ) {}

  @Post('/')
  async createOrder(@Body() request: CreateOrderRequest): Promise {
    // HTTP 요청을 Command로 변환
    const command = new CreateOrderCommand(
      request.customerId,
      request.items.map(item => ({
        productId: item.productId,
        quantity: item.quantity,
        price: item.price,
      }))
    );

    // Use Case 호출 (Port 사용)
    const orderDto = await this.createOrderUseCase.execute(command);

    // DTO를 HTTP 응답으로 변환
    return OrderResponse.from(orderDto);
  }

  @Get('/:id')
  async getOrder(@Param('id') id: string): Promise {
    const query = new GetOrderQuery(id);
    const orderDto = await this.getOrderUseCase.execute(query);
    return OrderResponse.from(orderDto);
  }

  @Delete('/:id')
  async cancelOrder(@Param('id') id: string): Promise {
    const command = new CancelOrderCommand(id);
    await this.cancelOrderUseCase.execute(command);
  }
}

// infrastructure/adapter/out/persistence/TypeOrmOrderRepository.ts - Driven Adapter
@Injectable()
export class TypeOrmOrderRepository implements OrderRepository {
  constructor(
    @InjectRepository(OrderEntity)
    private readonly ormRepository: Repository
  ) {}

  async save(order: Order): Promise {
    // 도메인 객체 → ORM 엔티티 변환
    const entity = this.toEntity(order);
    await this.ormRepository.save(entity);
  }

  async findById(id: OrderId): Promise {
    const entity = await this.ormRepository.findOne({
      where: { id: id.value },
      relations: ['items'],
    });

    if (!entity) return null;

    // ORM 엔티티 → 도메인 객체 변환
    return this.toDomain(entity);
  }

  private toEntity(order: Order): OrderEntity {
    const entity = new OrderEntity();
    entity.id = order.id.value;
    entity.customerId = order.customerId.value;
    entity.status = order.status;
    entity.items = order.items.map(item => this.toItemEntity(item));
    entity.createdAt = order.createdAt;
    return entity;
  }

  private toDomain(entity: OrderEntity): Order {
    // Factory 또는 reconstitute 메서드 사용
    return Order.reconstitute(
      new OrderId(entity.id),
      new CustomerId(entity.customerId),
      entity.items.map(this.toItemDomain),
      entity.status as OrderStatus,
      entity.createdAt
    );
  }
}

// infrastructure/adapter/out/payment/StripePaymentAdapter.ts - Driven Adapter
@Injectable()
export class StripePaymentAdapter implements PaymentGateway {
  constructor(private readonly stripeClient: Stripe) {}

  async processPayment(orderId: OrderId, amount: Money): Promise {
    try {
      const paymentIntent = await this.stripeClient.paymentIntents.create({
        amount: amount.amount,
        currency: amount.currency.toLowerCase(),
        metadata: { orderId: orderId.value },
      });

      return PaymentResult.success(new PaymentId(paymentIntent.id));
    } catch (error) {
      return PaymentResult.failure(error.message);
    }
  }

  async refund(paymentId: PaymentId): Promise {
    const refund = await this.stripeClient.refunds.create({
      payment_intent: paymentId.value,
    });
    return RefundResult.success(new RefundId(refund.id));
  }
}

// ===== Dependency Injection Configuration =====

// infrastructure/config/DependencyInjection.ts
@Module({
  imports: [TypeOrmModule.forFeature([OrderEntity, OrderItemEntity])],
  controllers: [OrderController],
  providers: [
    // Use Cases
    {
      provide: 'CreateOrderUseCase',
      useClass: CreateOrderService,
    },
    {
      provide: 'GetOrderUseCase',
      useClass: GetOrderService,
    },
    // Driven Adapters
    {
      provide: 'OrderRepository',
      useClass: TypeOrmOrderRepository,
    },
    {
      provide: 'PaymentGateway',
      useClass: StripePaymentAdapter,
    },
    {
      provide: 'NotificationService',
      useClass: SendGridNotificationAdapter,
    },
  ],
})
export class OrderModule {}

Architecture diagram

                     ┌─────────────────────────────────────────┐
                     │         DRIVING SIDE (왼쪽)              │
                     │     애플리케이션을 "호출하는" 쪽           │
                     └─────────────────────────────────────────┘
                                        │
           ┌────────────────────────────┼────────────────────────────┐
           │                            │                            │
           ▼                            ▼                            ▼
   ┌───────────────┐          ┌───────────────┐          ┌───────────────┐
   │  REST API     │          │   GraphQL     │          │   CLI         │
   │  Adapter      │          │   Adapter     │          │   Adapter     │
   │  (Controller) │          │   (Resolver)  │          │   (Command)   │
   └───────┬───────┘          └───────┬───────┘          └───────┬───────┘
           │                          │                          │
           └──────────────────────────┼──────────────────────────┘
                                      │
                                      ▼
                     ┌─────────────────────────────────────────┐
                     │          DRIVING PORT (Input)           │
                     │    <> CreateOrderUseCase     │
                     │    <> GetOrderUseCase        │
                     └─────────────────────────────────────────┘
                                      │
                                      ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                                                                              │
│    ╔═══════════════════════════════════════════════════════════════════╗    │
│    ║                    APPLICATION CORE                                ║    │
│    ║  ┌─────────────────────────────────────────────────────────────┐  ║    │
│    ║  │               APPLICATION LAYER                              │  ║    │
│    ║  │         (CreateOrderService, GetOrderService)                │  ║    │
│    ║  └─────────────────────────────────────────────────────────────┘  ║    │
│    ║                              │                                     ║    │
│    ║                              ▼                                     ║    │
│    ║  ┌─────────────────────────────────────────────────────────────┐  ║    │
│    ║  │                   DOMAIN LAYER                               │  ║    │
│    ║  │    Order, OrderItem, Money (Entities & Value Objects)        │  ║    │
│    ║  │    OrderRepository, PaymentGateway (Port Interfaces)         │  ║    │
│    ║  └─────────────────────────────────────────────────────────────┘  ║    │
│    ╚═══════════════════════════════════════════════════════════════════╝    │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘
                                      │
                                      ▼
                     ┌─────────────────────────────────────────┐
                     │          DRIVEN PORT (Output)           │
                     │    <> OrderRepository        │
                     │    <> PaymentGateway         │
                     │    <> NotificationService    │
                     └─────────────────────────────────────────┘
                                      │
           ┌──────────────────────────┼──────────────────────────┐
           │                          │                          │
           ▼                          ▼                          ▼
   ┌───────────────┐          ┌───────────────┐          ┌───────────────┐
   │  PostgreSQL   │          │    Stripe     │          │   SendGrid    │
   │  Adapter      │          │   Adapter     │          │   Adapter     │
   │  (Repository) │          │  (Payment)    │          │  (Email)      │
   └───────────────┘          └───────────────┘          └───────────────┘
                                        │
                     ┌─────────────────────────────────────────┐
                     │          DRIVEN SIDE (오른쪽)            │
                     │     애플리케이션이 "호출하는" 쪽          │
                     └─────────────────────────────────────────┘

📊 Architecture Comparison

Characteristics Hexagonal Clean Architecture Layered (N-Tier)
Dependency direction Outside → inside Outside → inside Top → bottom
Domain position Center (Core) Center (Entities) Middle layer
Infrastructure dependency Fully separated (Port) Fully separated (Interface) Direct dependency possible
Testability Very high Very high Moderate
Complexity Medium-high High Low
Suitable projects Complex domains Large enterprises Simple CRUD

✅ Selection criteria: For simple CRUD, Layered is enough. If the domain logic is complex and technology changes are expected, consider Hexagonal; for large teams and long-term projects, consider Clean Architecture.

🗣️ Examples of Practical Conversations

💬 In an architecture design meeting

"We need to switch the payment system from Toss to Stripe, but since we designed it with Hexagonal and only have a PaymentGateway interface, we just need to implement a new StripePaymentAdapter, and we don't have to change a single line of the order domain code."

💬 In a technical interview

"The core of Hexagonal Architecture is dependency inversion. The domain does not depend on infrastructure; the infrastructure implements the Port defined by the domain. Thanks to that, with only a Repository interface you can unit test pure domain logic without a real DB."

💬 In a code review

"This service class is injecting TypeORM's Repository directly. If you define an OrderRepository interface in domain/port and have TypeOrmOrderRepository implement it, you can easily swap it for InMemoryOrderRepository when testing."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Cautions

❌ Over-abstraction: Applying Hexagonal to a simple CRUD application only adds boilerplate code. Apply it when there is complex business logic.

❌ Port overuse: You do not need to create a Port for every external call. For things unlikely to change or that need no replacement in tests, depending on them directly is fine.

❌ Leaking domain objects: Domain entities must not go out directly as Controller responses. Convert them to DTOs to encapsulate the domain model.

✅ Recommendation: Apply Hexagonal only to core business logic (e.g., payments, inventory management), and implement simple features simply. Introducing it gradually is best.

🔗 Related Terms

📚 Learn More