Nov 20, 20264 min read

The Anti-Corruption Layer Pattern for Third-Party APIs

An anti-corruption layer translates a third-party or legacy API into your own domain model, so its quirks stop at one boundary. How to design the translation, handle errors and versioning, test it, and build one in TypeScript on Encore.

Illustration for The Anti-Corruption Layer Pattern for Third-Party APIs

Third-party APIs name things their own way: a shipping carrier returns status codes like PU and OFD, an accounting system calls your customers contacts, and a legacy service models an order as five loosely related records.

If those shapes spread through your code, every provider change becomes a refactor. An anti-corruption layer keeps them at one boundary, and this guide shows how to design it, test it and build one in TypeScript.

What is an anti-corruption layer?

The pattern comes from domain-driven design (Eric Evans' reference names it): when two models meet, put a translation layer between them so the foreign model cannot leak into yours. The Azure Architecture Center describes it as a façade or adapter between subsystems with different semantics.

In practice it is a module with an interface written in your own terms, such as getShipmentStatus(trackingNumber) returning in_transit, and an implementation that calls the provider and maps the answer.

What does the layer translate?

Four things cover most of the work:

  • Data shapes. Rename fields, convert units and money formats, parse dates and flatten nested structures into your types.
  • Vocabulary. Map provider status codes onto your own enum, with an explicit unknown value for codes you have not seen.
  • Errors. Turn HTTP statuses, error bodies and timeouts into a small set of your own errors, such as not found, rate limited and unavailable, so callers handle categories instead of provider details.
  • Behavior. Add retries, timeouts and rate limit handling in one place, since providers differ in how they fail.

Mapping unknown codes to unknown instead of throwing matters, because providers add values without telling you, and a new status should not take the checkout page down.

How do you handle provider API versions?

Pin the provider API version in the layer and write the mapping against it. When the provider releases a new version, add a second mapper and switch behind a flag, then delete the old one. Callers never see the change, since the domain interface stays the same. This is also what makes switching providers realistic, because a second implementation of the same interface is all that is needed.

How do you test the layer?

Test the mapping with recorded provider responses, including odd ones such as missing fields, new status codes and error bodies, and assert on your domain types. Elsewhere in the system, replace the layer with a fake that implements the same interface. A small set of contract tests against the provider's sandbox, run on a schedule, catches the day the provider changes its response shape.

An anti-corruption layer with Encore

Encore

Encore is a backend framework with built-in infrastructure, and a service is a natural boundary for the layer. Its API speaks your domain types, its provider key is an Encore secret, and the rest of the system calls it through generated type-safe functions instead of importing a provider client.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

// tracking/tracking.ts import { api, APIError } from "encore.dev/api"; import { secret } from "encore.dev/config"; const carrierKey = secret("CarrierApiKey"); export type ShipmentStatus = "label_created" | "in_transit" | "out_for_delivery" | "delivered" | "exception" | "unknown"; export interface Shipment { trackingNumber: string; status: ShipmentStatus; estimatedDelivery: string | null; // ISO date } // The carrier's shape, kept private to this service. interface CarrierResponse { tracking_id: string; status_code: string; eta?: { date: string }; } const statusMap: Record<string, ShipmentStatus> = { LC: "label_created", PU: "in_transit", IT: "in_transit", OFD: "out_for_delivery", DL: "delivered", EX: "exception", }; function toShipment(c: CarrierResponse): Shipment { return { trackingNumber: c.tracking_id, status: statusMap[c.status_code] ?? "unknown", estimatedDelivery: c.eta?.date ?? null, }; } export const get = api( { method: "GET", path: "/shipments/:trackingNumber", expose: true }, async ({ trackingNumber }: { trackingNumber: string }): Promise<Shipment> => { const resp = await fetch( `https://api.carrier.example/v2/tracking/${encodeURIComponent(trackingNumber)}`, { headers: { Authorization: `Bearer ${carrierKey()}` }, signal: AbortSignal.timeout(3000) }, ).catch(() => { throw APIError.unavailable("carrier did not respond"); }); if (resp.status === 404) throw APIError.notFound("unknown tracking number"); if (resp.status === 429) throw APIError.resourceExhausted("carrier rate limit reached"); if (!resp.ok) throw APIError.unavailable(`carrier returned ${resp.status}`); return toShipment((await resp.json()) as CarrierResponse); }, );

The request to the carrier has a three second timeout through AbortSignal.timeout, and other services call tracking.get through ~encore/clients and receive a Shipment in your terms. The carrier name, its codes and its HTTP errors appear only in this file, and calls to the carrier show up in the request trace, so a slow provider is easy to spot. Set the key with encore secret set --type dev,prod CarrierApiKey. The value is not stored in the repository or in git.

A coding agent can add a second carrier as another mapper behind the same Shipment interface, run the service locally and let the deploy handle the secret and service wiring.

Best fit: TypeScript teams integrating a carrier, payment, accounting or legacy API that want one service to own its quirks and expose domain types to everything else.

Frequently asked questions

What is an anti-corruption layer?

An anti-corruption layer is a component that sits between your system and an external or legacy one and translates between their models. Your code talks to a clean interface in your own terms, and only the layer knows the other system's field names, status codes and quirks.

When do you need an anti-corruption layer?

Use one when an external API's model differs from yours, when it changes without much notice, or when you may replace the provider later. For a single simple call that is unlikely to change, a thin wrapper function is usually enough.

Where should the anti-corruption layer live?

Put it in its own module or service with a narrow interface, and let nothing else import the provider's types or SDK. That boundary makes provider changes a one-place edit and makes the provider easy to fake in tests.

How do I build an anti-corruption layer with Encore?

Create a service whose API exposes your domain types and keeps the provider's HTTP calls and mapping private. Other services call it through Encore's type-safe service calls, and the provider API key lives in an Encore secret, so a provider change touches one service.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders