🏗️ Architecture

Anti-Corruption Layer

Anti-Corruption Layer / ACL

A translation layer that protects your own domain model from being "corrupted" when integrating with legacy or external systems. A core strategic pattern of Domain-Driven Design (DDD), it enables integration while keeping the conceptual boundaries between different Bounded Contexts clear. Implemented through a combination of Facade, Adapter, and Translator patterns.

📖 Detailed Explanation

Anti-Corruption Layer (ACL) is a strategic pattern introduced in Eric Evans's "Domain-Driven Design" (2003). "Corruption" means that the concepts, terminology, and data structures of an external system penetrate one's own domain model and undermine the purity and meaning of the domain. The ACL acts as a firewall that prevents such contamination.

Integration with legacy systems is unavoidable, but if the structural problems or flawed abstractions of the legacy system are brought into the new system as they are, technical debt propagates. The ACL accepts the legacy system's "bad" model but internally converts it into meaningful domain objects. Even if an external API changes, only the ACL needs to be modified, which minimizes the impact of the change.

The ACL has three core components. The Facade provides a simplified interface to the external system. The Adapter converts the external system's protocol into the format used internally. The Translator maps the external system's data to domain objects. These three elements work together to provide complete isolation.

In practice, the ACL is essential in microservice integration, legacy monolith decomposition, external SaaS integration, and system integration following M&A. In particular, when gradually replacing a legacy system with the Strangler Fig pattern, the ACL is a key pattern that enables coexistence between the new system and the legacy system.

Core Components of the ACL

Facade

Abstracts a complex external system into a simple interface. Internal code only needs to know the Facade.

Adapter

Responsible for protocol conversion. Handles technical conversions such as REST↔gRPC and XML↔JSON.

Translator

Responsible for conceptual mapping. Converts the external model's entities/value objects into the domain model.

Domain Service

Domain logic that uses the ACL. Written solely in pure domain language.

💻 Code Example

TypeScript - Legacy Payment System ACL

// ===== 레거시 시스템의 모델 (외부, 변경 불가) =====
// 레거시는 "트랜잭션"이라는 모호한 개념을 사용
interface LegacyTransaction {
  txn_id: string;
  txn_type: 'P' | 'R' | 'C';  // Payment, Refund, Chargeback
  amt: number;                 // 센트 단위
  ccy: string;                 // 통화 코드
  cust_no: string;
  status_cd: 'A' | 'P' | 'D' | 'F';  // Approved, Pending, Declined, Failed
  created_ts: string;          // 'YYYYMMDDHHMMSS' 형식
}

// 레거시 API 클라이언트
class LegacyPaymentAPI {
  async getTransaction(txnId: string): Promise {
    // 레거시 SOAP/XML API 호출
    const response = await fetch(`${LEGACY_URL}/txn/${txnId}`);
    return this.parseXmlResponse(response);
  }

  async processPayment(data: any): Promise {
    // 복잡한 레거시 API 호출
    return {} as LegacyTransaction;
  }
}

// ===== 우리 도메인 모델 (순수한 비즈니스 개념) =====
// 결제(Payment)라는 명확한 개념
interface Payment {
  id: PaymentId;
  type: PaymentType;
  amount: Money;
  customerId: CustomerId;
  status: PaymentStatus;
  createdAt: Date;
}

type PaymentType = 'PAYMENT' | 'REFUND' | 'CHARGEBACK';
type PaymentStatus = 'APPROVED' | 'PENDING' | 'DECLINED' | 'FAILED';

// 값 객체 (Value Object)
class Money {
  constructor(
    public readonly amount: number,  // 원 단위 (정수)
    public readonly currency: Currency
  ) {}

  static fromCents(cents: number, currencyCode: string): Money {
    const currency = Currency.fromCode(currencyCode);
    return new Money(cents / 100, currency);
  }

  add(other: Money): Money {
    if (!this.currency.equals(other.currency)) {
      throw new Error('Currency mismatch');
    }
    return new Money(this.amount + other.amount, this.currency);
  }
}

class PaymentId {
  constructor(public readonly value: string) {}
}

class CustomerId {
  constructor(public readonly value: string) {}
}

// ===== Anti-Corruption Layer =====

// 1. Translator: 개념적 매핑
class PaymentTranslator {
  // 레거시 → 도메인
  toDomain(legacy: LegacyTransaction): Payment {
    return {
      id: new PaymentId(legacy.txn_id),
      type: this.translateType(legacy.txn_type),
      amount: Money.fromCents(legacy.amt, legacy.ccy),
      customerId: new CustomerId(legacy.cust_no),
      status: this.translateStatus(legacy.status_cd),
      createdAt: this.parseTimestamp(legacy.created_ts),
    };
  }

  // 도메인 → 레거시 (필요시)
  toLegacy(payment: Payment): Partial {
    return {
      txn_type: this.reverseType(payment.type),
      amt: payment.amount.amount * 100,  // 센트로 변환
      ccy: payment.amount.currency.code,
      cust_no: payment.customerId.value,
    };
  }

  private translateType(code: string): PaymentType {
    const mapping: Record = {
      'P': 'PAYMENT',
      'R': 'REFUND',
      'C': 'CHARGEBACK',
    };
    return mapping[code] || 'PAYMENT';
  }

  private translateStatus(code: string): PaymentStatus {
    const mapping: Record = {
      'A': 'APPROVED',
      'P': 'PENDING',
      'D': 'DECLINED',
      'F': 'FAILED',
    };
    return mapping[code] || 'PENDING';
  }

  private reverseType(type: PaymentType): 'P' | 'R' | 'C' {
    const mapping: Record = {
      'PAYMENT': 'P',
      'REFUND': 'R',
      'CHARGEBACK': 'C',
    };
    return mapping[type];
  }

  private parseTimestamp(ts: string): Date {
    // 'YYYYMMDDHHMMSS' → Date
    const year = parseInt(ts.substring(0, 4));
    const month = parseInt(ts.substring(4, 6)) - 1;
    const day = parseInt(ts.substring(6, 8));
    const hour = parseInt(ts.substring(8, 10));
    const min = parseInt(ts.substring(10, 12));
    const sec = parseInt(ts.substring(12, 14));
    return new Date(year, month, day, hour, min, sec);
  }
}

// 2. Adapter: 프로토콜 변환 + 에러 핸들링
class LegacyPaymentAdapter {
  constructor(
    private legacyApi: LegacyPaymentAPI,
    private translator: PaymentTranslator
  ) {}

  async getPayment(id: PaymentId): Promise {
    try {
      const legacyTxn = await this.legacyApi.getTransaction(id.value);
      return this.translator.toDomain(legacyTxn);
    } catch (error) {
      // 레거시 에러를 도메인 예외로 변환
      if (error.code === 'TXN_NOT_FOUND') {
        return null;
      }
      throw new PaymentSystemError('결제 조회 실패', error);
    }
  }

  async processPayment(payment: CreatePaymentCommand): Promise {
    const legacyData = this.translator.toLegacy(payment);
    try {
      const result = await this.legacyApi.processPayment(legacyData);
      return this.translator.toDomain(result);
    } catch (error) {
      throw new PaymentProcessingError('결제 처리 실패', error);
    }
  }
}

// 3. Facade: 단순화된 인터페이스
// 도메인 서비스가 사용하는 인터페이스 (Port)
interface PaymentGateway {
  getPayment(id: PaymentId): Promise;
  processPayment(command: CreatePaymentCommand): Promise;
  refundPayment(paymentId: PaymentId, amount: Money): Promise;
}

// ACL Facade 구현
class LegacyPaymentGateway implements PaymentGateway {
  constructor(private adapter: LegacyPaymentAdapter) {}

  async getPayment(id: PaymentId): Promise {
    return this.adapter.getPayment(id);
  }

  async processPayment(command: CreatePaymentCommand): Promise {
    return this.adapter.processPayment(command);
  }

  async refundPayment(paymentId: PaymentId, amount: Money): Promise {
    // 레거시 환불 로직을 도메인 메서드로 추상화
    const refundCommand = { originalPaymentId: paymentId, amount };
    return this.adapter.processRefund(refundCommand);
  }
}

// ===== 도메인 서비스 (ACL 사용) =====
// 도메인 서비스는 레거시의 존재를 전혀 모름
class PaymentService {
  constructor(private paymentGateway: PaymentGateway) {}

  async getPaymentDetails(paymentId: string): Promise {
    const id = new PaymentId(paymentId);
    const payment = await this.paymentGateway.getPayment(id);

    if (!payment) {
      throw new PaymentNotFoundError(paymentId);
    }

    // 순수한 도메인 모델로 작업
    return this.toDto(payment);
  }

  async processNewPayment(request: PaymentRequest): Promise {
    const command = this.toCommand(request);
    const payment = await this.paymentGateway.processPayment(command);
    return this.toDto(payment);
  }
}

Java - External API Integration ACL

// ===== 외부 배송 API 모델 (3rd party) =====
@JsonIgnoreProperties(ignoreUnknown = true)
public class ExternalShipmentResponse {
    private String shipment_id;
    private String carrier_code;
    private String tracking_num;
    private String ship_status;  // "IN_TRANSIT", "DELIVERED", "EXCEPTION"
    private List events;
}

// ===== 우리 도메인 모델 =====
public record Shipment(
    ShipmentId id,
    Carrier carrier,
    TrackingNumber trackingNumber,
    ShipmentStatus status,
    List events,
    LocalDateTime estimatedDelivery
) {}

public enum ShipmentStatus {
    PREPARING, SHIPPED, IN_TRANSIT, OUT_FOR_DELIVERY, DELIVERED, EXCEPTION
}

public record TrackingEvent(
    LocalDateTime occurredAt,
    String location,
    EventType type,
    String description
) {}

// ===== Anti-Corruption Layer =====

// Translator
@Component
public class ShipmentTranslator {

    public Shipment toDomain(ExternalShipmentResponse external) {
        return new Shipment(
            new ShipmentId(external.getShipmentId()),
            Carrier.fromCode(external.getCarrierCode()),
            new TrackingNumber(external.getTrackingNum()),
            translateStatus(external.getShipStatus()),
            translateEvents(external.getEvents()),
            calculateEstimatedDelivery(external)
        );
    }

    private ShipmentStatus translateStatus(String externalStatus) {
        return switch (externalStatus) {
            case "IN_TRANSIT" -> ShipmentStatus.IN_TRANSIT;
            case "DELIVERED" -> ShipmentStatus.DELIVERED;
            case "EXCEPTION" -> ShipmentStatus.EXCEPTION;
            case "OUT_FOR_DELIVERY" -> ShipmentStatus.OUT_FOR_DELIVERY;
            default -> ShipmentStatus.SHIPPED;
        };
    }

    private List translateEvents(List events) {
        return events.stream()
            .map(this::translateEvent)
            .sorted(Comparator.comparing(TrackingEvent::occurredAt))
            .toList();
    }
}

// Adapter
@Component
public class ExternalShippingAdapter {
    private final ExternalShippingClient client;
    private final ShipmentTranslator translator;
    private final CircuitBreaker circuitBreaker;

    public ExternalShippingAdapter(
        ExternalShippingClient client,
        ShipmentTranslator translator,
        CircuitBreakerRegistry registry
    ) {
        this.client = client;
        this.translator = translator;
        this.circuitBreaker = registry.circuitBreaker("shipping");
    }

    public Optional getShipment(ShipmentId id) {
        return circuitBreaker.executeSupplier(() -> {
            try {
                ExternalShipmentResponse response = client.getShipment(id.value());
                return Optional.of(translator.toDomain(response));
            } catch (ShipmentNotFoundException e) {
                return Optional.empty();
            } catch (ExternalApiException e) {
                throw new ShippingServiceException("배송 조회 실패", e);
            }
        });
    }
}

// Facade (Port 구현)
@Component
public class ExternalShippingGateway implements ShippingGateway {
    private final ExternalShippingAdapter adapter;

    @Override
    public Optional findById(ShipmentId id) {
        return adapter.getShipment(id);
    }

    @Override
    public Shipment createShipment(CreateShipmentCommand command) {
        return adapter.createShipment(command);
    }
}

// 도메인 서비스 - 외부 시스템의 존재를 모름
@Service
public class OrderFulfillmentService {
    private final ShippingGateway shippingGateway;  // Port
    private final OrderRepository orderRepository;

    public ShipmentStatusDto getOrderShipmentStatus(OrderId orderId) {
        Order order = orderRepository.findById(orderId)
            .orElseThrow(() -> new OrderNotFoundException(orderId));

        Shipment shipment = shippingGateway.findById(order.getShipmentId())
            .orElseThrow(() -> new ShipmentNotFoundException(order.getShipmentId()));

        // 순수한 도메인 로직
        return ShipmentStatusDto.from(shipment);
    }
}

Architecture diagram

┌─────────────────────────────────────────────────────────────┐
│                    Our Bounded Context                       │
│  ┌─────────────────────────────────────────────────────────┐ │
│  │                   Domain Layer                           │ │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────────┐  │ │
│  │  │ Domain      │  │ Domain      │  │ Domain          │  │ │
│  │  │ Model       │  │ Service     │  │ Events          │  │ │
│  │  │ (Payment,   │  │ (uses Port) │  │ (PaymentMade)   │  │ │
│  │  │  Money...)  │  │             │  │                 │  │ │
│  │  └─────────────┘  └──────┬──────┘  └─────────────────┘  │ │
│  │                          │ uses                          │ │
│  │                          ▼                               │ │
│  │  ┌─────────────────────────────────────────────────────┐│ │
│  │  │                   Port (Interface)                   ││ │
│  │  │              PaymentGateway                          ││ │
│  │  │  - getPayment(id): Payment                          ││ │
│  │  │  - processPayment(cmd): Payment                     ││ │
│  │  └─────────────────────────────────────────────────────┘│ │
│  └─────────────────────────────────────────────────────────┘ │
│                              │                               │
│  ════════════════════════════╪═══════════════════════════════│
│                              │ implements                    │
│  ┌───────────────────────────▼─────────────────────────────┐ │
│  │           Anti-Corruption Layer (ACL)                    │ │
│  │  ┌──────────┐  ┌──────────┐  ┌──────────────────────┐   │ │
│  │  │ Facade   │→ │ Adapter  │→ │    Translator        │   │ │
│  │  │ (Gateway │  │ (Protocol│  │ (LegacyTxn→Payment)  │   │ │
│  │  │  impl)   │  │  convert)│  │                      │   │ │
│  │  └──────────┘  └──────────┘  └──────────────────────┘   │ │
│  └─────────────────────────────────────────────────────────┘ │
└───────────────────────────────│──────────────────────────────┘
                                │ calls
                                ▼
┌─────────────────────────────────────────────────────────────┐
│               External / Legacy System                       │
│  ┌─────────────────────────────────────────────────────────┐ │
│  │  Different model, different language                     │ │
│  │  (LegacyTransaction, txn_type: 'P'|'R'|'C', ...)       │ │
│  └─────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘

🗣️ Examples of Practical Conversations

💬 In a Design Review

"We need to integrate with the legacy ERP, but the ERP's 'Transaction' concept is completely different from our domain's 'Order.' We will introduce an ACL and build a translation layer so that the ERP's model does not contaminate our order domain."

💬 In a technical interview

"The Anti-Corruption Layer is one of DDD's Context Mapping strategies. It acts as a firewall that prevents concepts from an external system from penetrating my domain. We simplify with a Facade, convert protocols with an Adapter, and map concepts with a Translator."

💬 In a Legacy Migration Meeting

"To do a gradual migration with the Strangler Fig pattern, an ACL is essential. The new microservice communicates with the legacy system through the ACL, so it can keep a clean domain model without being affected by the legacy system's bad model."

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

⚠️ Cautions

❌ Excessive abstraction: Applying an ACL to a simple integration adds unnecessary complexity. If the external system's model is similar to your own domain, you can integrate directly without an ACL.

❌ Ignoring synchronization issues: The ACL is responsible only for model conversion, and data consistency must be considered separately. If two-way synchronization is required, apply an event-driven architecture together.

❌ Overlooking performance: If every external call goes through the Translator, object creation overhead occurs. When processing large volumes of data, consider batch conversion or lazy loading.

✅ Recommendation: Log all external calls at the ACL boundary and handle conversion failures explicitly. It should be possible to determine the scope of impact of an external system change through ACL tests alone.

🔗 Related Terms

📚 Learn More