The Anti-Corruption Layer (ACL) pattern places a dedicated translation boundary between your application's clean core domain model and an external or legacy subsystem whose data structures, terminology, error semantics, or invariants would otherwise pollute your codebase. Originally formalized in Domain-Driven Design, the ACL ensures that two Bounded Contexts never silently couple their internal tables, enums, or quirk workarounds across a shared boundary.
For coding agents integrating enterprise ERPs, payment processors, AI/LLM providers, identity directories, or legacy monolith databases during incremental modernization (Strangler Fig Pattern), omitting an ACL is one of the fastest ways to corrupt a codebase: soon external stringly-typed status codes ("INV_STAT_09B"), vendor-specific webhook shapes, and legacy nullability quirks leak straight into React UI state, PostgreSQL columns, and core business rules. For related integration and structural design patterns, see Design Patterns Hub, Enterprise Integration Hub, Adapter Pattern, and Integration Pattern Vocabulary.
While the classic Gang-of-Four Adapter Pattern harmonizes two method signatures at the object level, an Anti-Corruption Layer operates at the Bounded Context / Subsystem boundary. It combines facade simplification, schema validation, bi-directional semantic mapping, identity correlation, and resilience controls (Circuit Breaker Pattern) so the core domain remains completely ignorant of the upstream system's protocol or mental model.
graph LR
Domain["Clean Core Domain (Order, Money, FulfillmentStatus)"] --> Port["Outbound Domain Port (PaymentGateway / ErpPort)"]
Port --> ACL["Anti-Corruption Layer (Translator + Validator + IdMapper)"]
ACL --> Legacy["Legacy ERP / Vendor API (XML/REST, String Codes, Cents-vs-Dollars)"]
ACL --> DLQ["Poison Schema Quarantine / Telemetry"]
click Domain "/wiki/DomainDrivenDesign" "Domain-Driven Design"
click Port "/wiki/RepositoryPattern" "Repository Pattern"
click ACL "/wiki/AdapterPattern" "Adapter Pattern"
click DLQ "/wiki/DeadLetterQueuePatterns" "Dead Letter Queue Patterns"
| Pattern | Granularity | Primary Problem Solved | Key Distinction from ACL |
|---|---|---|---|
| Adapter Pattern | Class / interface wrapper | Converts interface A method calls into interface B | Usually thin signature shim; often passes external DTOs right through |
| Canonical Data Model | Organization-wide shared bus schema | Standardizes messages on an enterprise ESB | Forces every team to negotiate central schema governance; high coupling if over-applied |
| Strangler Fig Pattern | Edge routing & migration lifecycle | Incrementally shifts live traffic from monolith to new services | Architecture migration strategy; an ACL typically sits inside the strangler boundary during coexistence |
| Anti-Corruption Layer (ACL) | Bounded context boundary (Port + Translator + Quarantine) | Prevents foreign domain semantics, dirty invariants, and vendor churn from leaking into your domain | Rejects/normalizes unmapped states at ingress and owns external-to-internal ID translation |
Agents sometimes resist introducing an ACL because mapping DTOs feels like "extra boilerplate." Quantifying the blast radius of tight coupling shows why that small mapping cost pays off immediately when an external vendor introduces breaking changes or ambiguous states.
Suppose an organization integrates 1 external billing ERP API directly across M = 18 internal modules (checkout handlers, invoice PDF generators, React forms, reporting jobs, and subscription renewals). Let:
status: "paid" splits into settlement_state: "CLEARED" | "PENDING_ACH"): assume 3.5 hours per call site.The avoided maintenance rework factor over K = 4 breaking vendor/legacy schema updates per year is:
Meanwhile, runtime serialization and validation inside an ACL add negligible overhead compared to network I/O. With a 2\text{ KB} JSON payload validated through a compiled schema parser (Zod/Ajv/Pydantic v2), ACL ingress mapping takes L_{\text{acl}} \approx 0.15\text{ ms} against a 65\text{ ms} external HTTPS call—just 0.23\% of external request latency.
A production-ready ACL consists of four explicit components:
OutboundPort): Uses pure domain value objects (Money in integer minor units + ISO currency, strict discriminated union PaymentSettlementStatus), zero vendor imports, and domain-specific error types.ExternalSchema): Strict runtime schema validation (failing explicitly on unexpected payload shapes rather than silently casting any or indexing undefined)."SETTLED_NET", "CHRG_B_OPEN"), monetary formats (float dollars like "129.95" parsed deterministically to integer minor units 12995 via string/decimal parsing—never IEEE 754 float * 100!), and timestamps (legacy local timezone strings -> UTC Instant) while normalizing vendor errors into domain faults (Error Handling Strategies).500 crashes mid-batch or writing "UNKNOWN" into financial tables.// 1. Core Domain Model & Outbound Port (zero external vendor types!)
export type CurrencyCode = "USD" | "EUR" | "GBP";
export interface Money {
readonly minorUnits: number; // integer cents, e.g. 12995 for $129.95
readonly currency: CurrencyCode;
}
export type SettlementState =
| { readonly kind: "AUTHORIZED"; readonly expiresAtIso: string }
| { readonly kind: "SETTLED"; readonly settledAtIso: string }
| { readonly kind: "DISPUTED"; readonly disputeReason: string }
| { readonly kind: "FAILED"; readonly retryable: boolean; readonly domainCode: string };
export interface ExternalChargeSnapshot {
readonly internalOrderId: string;
readonly amount: Money;
readonly state: SettlementState;
}
export interface PaymentSettlementPort {
fetchChargeSnapshot(internalOrderId: string): Promise<ExternalChargeSnapshot>;
}
// 2. Messy Legacy/Vendor DTO (contained strictly inside acl/legacyPay/)
interface LegacyVendorChargePayload {
order_ref_str: string; // e.g. "ORD-9921"
gross_amt_str: string; // vendor sends decimal strings like "129.95"
ccy_num: 840 | 978 | 826; // ISO 4217 numeric codes!
proc_stat_cd: string; // e.g. "00_CLR", "05_HLD", "91_TMO", "77_CHB"
proc_ts_est: string; // legacy timestamp "2026-11-13 08:15:00" without Z
err_sub_txt?: string | null;
}
export class AclTranslationError extends Error {
constructor(
public readonly vendorCode: string,
message: string
) {
super(message);
}
}
// Deterministic decimal string -> integer minor units (avoids 19.99 * 100 === 1998.9999999999998)
function parseDecimalToMinorUnits(raw: string): number {
const match = /^(\d+)(?:\.(\d{1,2}))?$/.exec(raw.trim());
if (!match) {
throw new AclTranslationError("INVALID_AMOUNT", `Unparseable vendor amount: ${raw}`);
}
const whole = Number.parseInt(match[1], 10);
const frac = (match[2] ?? "").padEnd(2, "0");
return whole * 100 + Number.parseInt(frac, 10);
}
const NUMERIC_TO_ISO_CURRENCY: Record<number, CurrencyCode> = {
840: "USD",
978: "EUR",
826: "GBP",
};
// 3. Translator isolating vendor quirks, codes, and timezone assumptions
export function translateLegacyCharge(
raw: LegacyVendorChargePayload,
expectedInternalOrderId: string
): ExternalChargeSnapshot {
const currency = NUMERIC_TO_ISO_CURRENCY[raw.ccy_num];
if (!currency) {
throw new AclTranslationError("UNKNOWN_CURRENCY", `Unsupported ISO 4217 code: ${raw.ccy_num}`);
}
const amount: Money = {
minorUnits: parseDecimalToMinorUnits(raw.gross_amt_str),
currency,
};
let state: SettlementState;
switch (raw.proc_stat_cd) {
case "00_CLR":
state = { kind: "SETTLED", settledAtIso: normalizeLegacyEstToUtc(raw.proc_ts_est) };
break;
case "05_HLD":
state = { kind: "AUTHORIZED", expiresAtIso: normalizeLegacyEstToUtc(raw.proc_ts_est) };
break;
case "77_CHB":
state = { kind: "DISPUTED", disputeReason: raw.err_sub_txt?.trim() || "UNSPECIFIED_CHARGEBACK" };
break;
case "91_TMO":
state = { kind: "FAILED", retryable: true, domainCode: "PROCESSOR_TIMEOUT" };
break;
default:
// Fail visibly to quarantine/DLQ rather than silently defaulting to FAILED or SETTLED!
throw new AclTranslationError(
"UNMAPPED_STATUS",
`Unknown vendor status ${raw.proc_stat_cd} for order ${expectedInternalOrderId}`
);
}
return { internalOrderId: expectedInternalOrderId, amount, state };
}
function normalizeLegacyEstToUtc(legacyTs: string): string {
// Explicit offset conversion rather than trusting server local TZ
const parsed = new Date(legacyTs.replace(" ", "T") + "-05:00");
if (Number.isNaN(parsed.getTime())) {
throw new AclTranslationError("INVALID_TIMESTAMP", `Bad vendor timestamp: ${legacyTs}`);
}
return parsed.toISOString();
}
integrations/salesforce/ module that defines interface SalesforceAccountDTO and returns that exact interface directly to business services or React UI components gives zero insulation—when Salesforce renames a custom field Billing_Tier__c, 20 files still break. The ACL's public return type must contain zero vendor column names.default: return "PENDING"): Mapping unrecognized vendor status codes into an existing valid domain enum corrupts accounting and state machines when the vendor introduces "PARTIAL_REFUND_HOLD". Throw AclTranslationError, park asynchronous events in a Dead Letter Queue, and alert engineering so the translator lookup table is updated safely."19.99" by 100 in JavaScript/Python floats produces 1998.9999999999998, which Math.floor truncates to 1998 cents (\$19.98). Always parse monetary strings lexically or with exact Decimal types inside the ACL boundary before entering core domain objects.1900-01-01), and multi-purpose columns corrupt new services. During Strangler Fig Pattern migrations, keep a strict read/write ACL gateway or CDC translator (Data Consistency and Sync Patterns) between legacy schemas and new bounded contexts.When an automated coding agent integrates a third-party SaaS API, payment gateway, LLM provider, or legacy internal service, enforce this structural contract:
domain/ports/<capability>.port.ts): Define the capability interface using only domain types and domain error classes. External SDKs (stripe, @aws-sdk/*, axios, SOAP/XML clients) are forbidden inside domain/.infrastructure/acl/<vendor>/): Place three distinct files per external integration:
schema.ts: strict runtime input validation (Zod/JSON Schema/Pydantic) of raw external responses and webhooks,translator.ts: pure side-effect-free functions mapping external DTOs -> domain objects (and domain commands -> external requests) with explicit error/unknown-code handling,adapter.ts: HTTP/RPC client wrapped with timeouts, retries, idempotency keys (Idempotency Patterns), and circuit breaking (Circuit Breaker Pattern).external_id_mappings (internal_id, provider, external_id) table rather than storing vendor-specific ID strings as primary keys of core domain entities.proc_stat_cd or non-numeric amount into the translator and verify it throws AclTranslationError rather than silently succeeding.infrastructure/acl/<vendor>/ imports the vendor SDK or references vendor-specific field names.