Software Architecture

Domain-Driven Design: Anti-Corruption Layer, protecting the domain from external models and systems.

Build an ACL to integrate a payment provider without leaking its statuses into the domain. Define an internal contract, validate responses, translate identities and meanings, and distinguish technical errors from business outcomes with TypeScript.

Updated on October 29, 2026

Content explored 0%
18px

The indicator keeps the furthest percentage explored; marking the article complete is your choice.

When “approved” starts deciding for your business

Payments integrates an external gateway. A response includes transaction_id and an APPROVED status. To move quickly, those fields appear in the use case, payment model, and application responses.

Months later another provider arrives. It also uses the word “approved,” but for an authorization that has not yet been captured. The code compiles, yet the application could treat an amount it has not collected as confirmed.

The problem is not the language of identifiers. It is that an external interpretation has come to decide what a payment means within Payments.

An Anti-Corruption Layer, or ACL, allows integrating that functionality in terms of the consumer model. We will build a results query with an internal contract, validation, translation, and an HTTP adapter. We will not execute charges or implement a complete financial platform.

What an Anti-Corruption Layer protects

The ACL maintains an interpretation boundary between the consumer context and an external model. The domain uses its own concepts; the integration understands the outside contract and translates it.

Evans proposes this layer as a way of offering Upstream functionality in terms of Downstream's own model. DDD Reference: Anticorruption Layer, page 34 of the document.

“Corruption” here means the local model loses coherence by incorporating concepts and assumptions that do not belong to it. It does not imply that the provider is defective, malicious, or old.

An ACL can protect integration with a modern gateway, another context in the same organization, or an essential legacy system.

Microsoft also describes its application when two subsystems do not share semantics. The layer can be implemented through adapters or facades; it need not become a separately deployed service. Anti-Corruption Layer pattern.

The boundary in our example

Payments application
        |
        | PaymentResults: consumer language
        v
ACL within Payments
  - HTTP adapter
  - external contract validation
  - status and identity translation
        |
        | transaction_id, APPROVED, DECLINED, IN_REVIEW
        v
External payment provider

The arrows represent collaboration. Internal model dependencies do not point to provider DTOs.

The ACL belongs to the consumer that needs protection. The provider does not have to change its API for us to introduce it.

The initial mistake: using the DTO as your own model

This snippet is deliberately problematic:

interface ProviderTransaction {
  transaction_id: string;
  status: string;
}

function mayConfirmPayment(transaction: ProviderTransaction): boolean {
  return transaction.status === "APPROVED";
}

The use case knows the gateway code. It does not check which payment the transaction belongs to or under what conditions APPROVED allows confirmation.

Adding as Payment to a JSON response does not fix it. Renaming transaction_id to paymentId is not enough either: they could be different identities.

First define what Payments needs to assert.

Agree on equivalences before programming them

In this hypothetical case, the provider documents a query for capture operations. In that particular API:

  • APPROVED means capture of the specified amount completed.
  • DECLINED means that attempt was rejected.
  • IN_REVIEW means the provider is still reviewing the outcome.
  • The response includes merchant reference, amount, and currency.
  • An HTTP or network error is not a financial rejection.

Payments uses CONFIRMED, REJECTED, and PENDING_REVIEW to represent those query results.

The equivalence APPROVED → CONFIRMED depends on that specific agreement. It is not a general rule about gateways. If another provider uses APPROVED for authorization, another interpretation and possibly more information will be needed.

Also, REJECTED means the queried attempt was rejected, not that a person can never pay or that every other attempt has failed.

An ACL cannot turn insufficient information into certainty. If the provider does not distinguish authorization from capture, obtain that evidence or leave the operation unconfirmed.

An internal contract expressing the need

Payments defines these types in application/payment-results.ts:

export type PaymentId = string;

export type PaymentState =
  | "CONFIRMED"
  | "REJECTED"
  | "PENDING_REVIEW";

export interface PaymentExpectation {
  readonly paymentId: PaymentId;
  readonly amountMinor: number;
  readonly currency: "EUR";
}

export interface PaymentObservation {
  readonly paymentId: PaymentId;
  readonly state: PaymentState;
}

export interface PaymentResults {
  observe(expected: PaymentExpectation): Promise<PaymentObservation>;
}

PaymentId is a teaching alias. It provides neither nominal identity nor string validation by itself; in a real project it may be a stricter type or value object.

The contract mentions neither HTTP nor transaction_id. Payments asks about its payment and receives an observation in its language.

The remote transaction's identity is resolved through a reference the integration obtained previously. It must not be confused with the local identifier.

Separate files by what they know

One possible structure:

payments/
  application/
    payment-results.ts
    inspect-payment.ts
  infrastructure/
    capture-provider/
      provider-contract.ts
      translate-capture.ts
      capture-http-results.ts
  test/
    translate-capture.test.ts

There is no need to create a class per property. The criterion is to localize provider-specific details and prevent them from reaching consumer logic.

The HTTP client uses the internal contract; the application does not import the external DTO. This organization is illustrative and does not claim to describe existing project files.

Validate the response structure

The provider returns a fictional representation like this:

{
  "transaction_id": "tx-900",
  "merchant_reference": "payment-100",
  "status": "APPROVED",
  "amount_minor": 7000,
  "currency_code": "EUR"
}

In provider-contract.ts we localize its structure and validation:

export interface ProviderCapture {
  readonly transaction_id: string;
  readonly merchant_reference: string;
  readonly status: "APPROVED" | "DECLINED" | "IN_REVIEW";
  readonly amount_minor: number;
  readonly currency_code: "EUR";
}

export class ProviderContractError extends Error {}

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null &&
    !Array.isArray(value);
}

export function parseCapture(raw: unknown): ProviderCapture {
  if (!isRecord(raw)) {
    throw new ProviderContractError("Respuesta de captura inválida");
  }

  if (
    typeof raw.transaction_id !== "string" ||
    !/^[A-Za-z0-9_-]{1,64}$/.test(raw.transaction_id) ||
    typeof raw.merchant_reference !== "string" ||
    !/^[A-Za-z0-9_-]{1,64}$/.test(raw.merchant_reference)
  ) {
    throw new ProviderContractError("Referencias de captura inválidas");
  }

  const status = raw.status;
  if (
    status !== "APPROVED" &&
    status !== "DECLINED" &&
    status !== "IN_REVIEW"
  ) {
    throw new ProviderContractError("Estado de captura no soportado");
  }

  const amount = raw.amount_minor;
  if (
    typeof amount !== "number" ||
    !Number.isSafeInteger(amount) ||
    amount <= 0 ||
    raw.currency_code !== "EUR"
  ) {
    throw new ProviderContractError("Importe o moneda inválidos");
  }

  return {
    transaction_id: raw.transaction_id,
    merchant_reference: raw.merchant_reference,
    status,
    amount_minor: amount,
    currency_code: "EUR",
  };
}

The parser constructs a new object with known fields. Additional properties are not carried inside.

Identifier restrictions and the single currency are explicit example assumptions. A real provider may require other formats. Do not copy these limits without checking its documentation.

So far we have checked shape and allowed values. Identity, expected amount, and result meaning still need checking.

Translate meaning and check correspondence

In translate-capture.ts:

import type {
  PaymentExpectation,
  PaymentObservation,
  PaymentState,
} from "../../application/payment-results.js";
import {
  ProviderContractError,
  type ProviderCapture,
} from "./provider-contract.js";

export function translateCapture(
  capture: ProviderCapture,
  expected: PaymentExpectation,
  requestedTransactionId: string,
): PaymentObservation {
  if (
    capture.transaction_id !== requestedTransactionId ||
    capture.merchant_reference !== expected.paymentId ||
    capture.amount_minor !== expected.amountMinor ||
    capture.currency_code !== expected.currency
  ) {
    throw new ProviderContractError("La captura no corresponde al pago");
  }

  let state: PaymentState;

  switch (capture.status) {
    case "APPROVED":
      state = "CONFIRMED";
      break;
    case "DECLINED":
      state = "REJECTED";
      break;
    case "IN_REVIEW":
      state = "PENDING_REVIEW";
      break;
    default:
      throw new ProviderContractError("Estado de captura no soportado");
  }

  return { paymentId: expected.paymentId, state };
}

Structural translation changes merchant_reference to a local reference. Semantic translation determines which observation each status allows asserting according to the earlier agreement.

The local identifier comes from Payments. We return it only after checking that the response corresponds to that payment and the requested transaction.

If the provider supports partial captures or multiple currencies, this translation would be insufficient. Do not force those cases into an equivalence designed for full capture in EUR.

Connect the query through an HTTP adapter

The adapter needs to locate the remote reference. The following abstraction does not load another context's aggregate; it resolves an identity relationship managed by the integration.

In capture-http-results.ts:

import type {
  PaymentExpectation,
  PaymentId,
  PaymentObservation,
  PaymentResults,
} from "../../application/payment-results.js";
import { parseCapture } from "./provider-contract.js";
import { translateCapture } from "./translate-capture.js";

export interface CaptureReferences {
  findTransaction(paymentId: PaymentId): Promise<string | null>;
}

export class PaymentLookupError extends Error {
  constructor(readonly kind: "UNAVAILABLE" | "REFERENCE_NOT_FOUND") {
    super("No se pudo obtener una observación del pago");
  }
}

export class CaptureHttpResults implements PaymentResults {
  constructor(
    private readonly origin: string,
    private readonly references: CaptureReferences,
  ) {
    const url = new URL(origin);
    if (
      url.protocol !== "https:" ||
      url.username !== "" ||
      url.password !== "" ||
      url.pathname !== "/" ||
      url.search !== "" ||
      url.hash !== ""
    ) {
      throw new Error("Se requiere un origen HTTPS del proveedor");
    }
  }

  async observe(
    expected: PaymentExpectation,
  ): Promise<PaymentObservation> {
    if (
      !/^[A-Za-z0-9_-]{1,64}$/.test(expected.paymentId) ||
      !Number.isSafeInteger(expected.amountMinor) ||
      expected.amountMinor <= 0 ||
      expected.currency !== "EUR"
    ) {
      throw new Error("Expectativa de pago inválida");
    }

    const transactionId = await this.references.findTransaction(
      expected.paymentId,
    );

    if (
      transactionId === null ||
      !/^[A-Za-z0-9_-]{1,64}$/.test(transactionId)
    ) {
      throw new PaymentLookupError("REFERENCE_NOT_FOUND");
    }

    const url = new URL(
      "/v1/captures/" + encodeURIComponent(transactionId),
      this.origin,
    );

    let response: Response;
    try {
      response = await fetch(url, {
        headers: { accept: "application/json" },
        signal: AbortSignal.timeout(3000),
        redirect: "error",
        cache: "no-store",
      });
    } catch {
      throw new PaymentLookupError("UNAVAILABLE");
    }

    if (!response.ok) {
      throw new PaymentLookupError("UNAVAILABLE");
    }

    const raw: unknown = await response.json();
    return translateCapture(parseCapture(raw), expected, transactionId);
  }
}

The snippets assume Node.js with fetch and AbortSignal.timeout, as well as TypeScript compilation with the corresponding types. The route is fictional and must not be used to query a real gateway.

The origin must come from controlled configuration for an authorized provider. HTTPS does not permit accepting arbitrary destinations from a user request.

We do not show provider authentication, response size limits, or complete observability. These must be specified before production. The example performs reads only; it does not implement capture, charge retries, or reference persistence.

Invalid JSON or a contract violation remain errors. The entry layer must handle them explicitly and record what is needed without exposing credentials, card data, or complete bodies.

A remote 404 does not become REJECTED either: it could mean an incorrect reference, an invisible resource, or a contract situation we must investigate.

The application no longer knows external statuses

In inspect-payment.ts:

import type {
  PaymentExpectation,
  PaymentObservation,
  PaymentResults,
} from "./payment-results.js";

export async function inspectPayment(
  expected: PaymentExpectation,
  results: PaymentResults,
): Promise<PaymentObservation> {
  return results.observe(expected);
}

The use case is small because it only requests an observation. A later decision can use CONFIRMED, REJECTED, or PENDING_REVIEW without knowing gateway codes.

We have not persisted a state change. An observation does not authorize indiscriminately overwriting later states: refunds, voids, or newer information require local rules.

Changing providers may require another adapter and another reference resolution. The ACL reduces propagation of those changes; it does not promise that replacing a system is free.

Test the semantic boundary

These unit test examples use Node.js built-in APIs and assume compilation to JavaScript ESM. They have not been run as part of the article.

In test/translate-capture.test.ts:

import test from "node:test";
import assert from "node:assert/strict";
import { parseCapture } from "../infrastructure/capture-provider/provider-contract.js";
import { translateCapture } from "../infrastructure/capture-provider/translate-capture.js";

const expected = {
  paymentId: "payment-100",
  amountMinor: 7000,
  currency: "EUR",
} as const;

function response(status: string, amount = 7000) {
  return {
    transaction_id: "tx-900",
    merchant_reference: "payment-100",
    status,
    amount_minor: amount,
    currency_code: "EUR",
  };
}

test("traduce una captura aprobada según el acuerdo", () => {
  const result = translateCapture(
    parseCapture(response("APPROVED")),
    expected,
    "tx-900",
  );

  assert.deepEqual(result, {
    paymentId: "payment-100",
    state: "CONFIRMED",
  });
});

test("mantiene pendiente una revisión del proveedor", () => {
  const result = translateCapture(
    parseCapture(response("IN_REVIEW")),
    expected,
    "tx-900",
  );
  assert.equal(result.state, "PENDING_REVIEW");
});

test("traduce un rechazo explícito del intento", () => {
  const result = translateCapture(
    parseCapture(response("DECLINED")),
    expected,
    "tx-900",
  );
  assert.equal(result.state, "REJECTED");
});

test("un estado nuevo no se convierte en confirmación", () => {
  assert.throws(() => parseCapture(response("AUTHORIZED")));
});

test("rechaza una captura de otro importe o transacción", () => {
  assert.throws(() => translateCapture(
    parseCapture(response("APPROVED", 6000)),
    expected,
    "tx-900",
  ));

  assert.throws(() => translateCapture(
    parseCapture(response("APPROVED")),
    expected,
    "tx-other",
  ));
});

The tests verify equivalences and correspondence under the stated assumptions. They do not demonstrate that a real provider preserves those semantics.

Adapter tests for network errors, 404, invalid JSON, and a missing local reference are also needed, as well as checks against the actual contract in an authorized test environment.

If all tests are mocks invented by the consumer, a mistaken interpretation of APPROVED can still appear green.

Adapter Pattern: adapts one interface to another. It can be part of the ACL, but does not by itself express which model is protected or whether semantic translation is correct.

Facade: offers a simplified entry point to a subsystem. It can hide complexity without preventing external concepts from defining local decisions.

Mapper: transforms data. A mapper that only renames fields may suffice for a format, but does not resolve differences of identity, units, or meaning.

Conformist: adopts the external model because it is acceptable. The ACL retains its own interpretation and translates the interaction.

Repository: normally expresses access to persistence of the local model. An adapter querying a gateway is integrating an external capability; calling it a repository does not grant direct access to another context's storage.

An ACL can combine adapters, mappers, and a facade. It does not need a class called AntiCorruptionLayer; its value lies in the boundary it maintains.

Errors and evolution that must not leak into the domain

If the provider adds AUTHORIZED, do not map it to CONFIRMED based on similarity. Review the evidence it represents and what Payments needs to decide.

If it changes cents to a decimal string, the parser will fail. The correction must clarify units and precision before converting the data.

If IN_REVIEW comes to mean a final blocked outcome, retaining the old translation would be a semantic error even if the schema does not change.

A timeout means we could not complete the query, not that payment is rejected. Unavailability and financial outcome belong to different categories.

External events may also need this protection. A remote event name must not automatically become a fact in the local model without checking identity and meaning. The principle holds even without HTTP.

The ACL does not create a shared transaction either. A failure recording a local observation does not reverse a remote financial operation.

Two additional cases for deciding whether it adds value

Logistics: from external incident to support decision

A carrier declares DELIVERY_EXCEPTION. For support, that status may justify an investigation, but not automatic compensation.

An ACL can translate it to “requires delivery review” and retain compensation rules in the responsible context. Its value lies in not turning an operational code into a stronger commercial conclusion.

If a page only reproduces the carrier's stated tracking, adopting that language may suffice. Additional translation does not have the same benefit for both consumers.

Education: protect an academic record from a legacy system

An old system returns grade 0 both for an assessment not taken and one taken with zero points. The new academic record needs to distinguish them.

Renaming the field is insufficient. The ACL must obtain additional information to separate the meanings. If the legacy system does not provide it, the ambiguity must be flagged or a review process agreed upon.

The lesson is that a translation layer does not recover facts the provider does not retain.

When protection becomes unnecessary complexity

An ACL adds value when relevant differences in concepts, rules, identity, or evolution should remain outside your own model.

It may be excessive when two interfaces already express exactly the same need and a transformation merely duplicates names without protecting any decision.

Start with the minimum internal contract. If the team creates a generic model capable of representing every possible gateway, it may end up imposing another external complexity on the domain.

Also review leak points: provider DTOs in public signatures, remote codes in local decisions, and direct gateway access from different use cases. If those paths keep growing, the adapters folder is not maintaining a real boundary.

Ask AI for translations you can justify

For Cursor, Claude, or Codex, provide the external contract, internal contract, and examples of confirmed semantics.

To analyze:

Compare this capture query with our Payments model. Identify differences in identity, statuses, units, and errors. Distinguish documented equivalences from hypotheses. Do not assume APPROVED means completed capture without evidence.

To implement:

Implement an internal observation port and an HTTP ACL owned by Payments. Validate unknown JSON, remote reference, local reference, amount, and currency. Keep provider DTOs and codes inside the adapter. A timeout or 404 does not represent a financial rejection.

To review:

Review this diff for external terms outside the ACL, casts replacing validation, and new statuses treated as confirmed. Explain the affected behavior and necessary tests. Do not propose executing real charges or introducing infrastructure without need.

The responsible person must validate equivalences against the business and provider documentation. Compiling does not turn linguistic similarity into a financial guarantee.

Exercises

1. Approved without capture

Another gateway uses APPROVED to indicate authorization. Can you reuse the previous translation by changing the URL?

2. The reference that looks like a PaymentId

The provider changes transaction_id on each retry. The team wants to use it as the local payment identifier. What would you review?

3. The timeout turned into rejection

A capture takes too long and the application marks the payment REJECTED. What should change?

Reasoned solutions

1. No. Equivalence depends on the operation's meaning, not the status name. Capture evidence must be obtained or an observation retained that does not yet confirm. The same internal contract works only if the new provider can satisfy it correctly.

2. I would review the identity of the local payment, each attempt, and external references. They are not interchangeable for convenience. The integration must preserve their mapping without redefining the local identifier according to provider retries.

3. Separate communication failure from financial rejection. The query must produce a technical error or a pending-verification situation according to the agreed process, without inventing that the provider rejected the operation.

Recognize a useful ACL

Protection works when you can change an external representation without teaching its details to every use case, and when every important equivalence has verifiable justification.

Check that the internal contract expresses a real need, translation preserves identity and meaning, and errors do not become business facts.

The ACL does not eliminate provider dependency. It keeps it within an explicit boundary where it can be understood, tested, and evolved without accidentally redefining the domain.

Loading conversation…

Keep learning