📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Show me how you would build an anti-corruption layer that protects your domain model from a legacy or third-party system. What are the translator, adapter and facade parts, where do they live in a .NET solution, and how do you test it?

Covers implementing an anti-corruption layer in .NET: a domain-owned port, adapter and translator in infrastructure, a typed HttpClient facade, resilience, error translation and contract tests.

Mid-Level Coding Intermediate adapter anti-corruption-layer architecture domain-driven-design httpclient integration

🎯 Key points

  • Port (interface) defined by the downstream domain in its own language
  • Facade/client: typed HttpClient registered with AddHttpClient<T>().AddStandardResilienceHandler() (Polly v8: timeout, retry with jitter, circuit breaker), tuned per vendor
  • Translator: pure mapping in both directions (inbound DTOs/codes to domain types, outbound domain to vendor request with validation)
  • Adapter implements the port, combining client and translator; lives in Infrastructure and is internal
  • Translate errors and unknown codes explicitly (safe outcome or failure), never leak upstream exceptions
  • Retry only idempotent calls, or send an idempotency key; disable retries for non-idempotent POSTs
  • Log and meter translation failures (raw code, no PII) and alert on them to detect upstream changes early
  • Test translators with unit tests, the adapter with WireMock.Net, and run contract tests against the vendor sandbox

⏱ 30-second answer

An anti-corruption layer is code on the downstream side that translates an upstream model into yours, so the upstream's names, codes and quirks never reach your domain. It has three parts. A port: an interface your domain defines in its own language (IIdentityVerifier). A facade/client: a typed HttpClient with AddStandardResilienceHandler() (timeouts, retries with jitter, circuit breaker). A translator: pure functions mapping both ways, vendor DTOs and codes to your value objects and your types to validated vendor requests. An adapter implements the port, lives in Infrastructure and is internal.

Unknown codes map to a safe outcome and are logged and metered so upstream changes are caught the same day. Test translators with unit tests, the adapter against WireMock.Net, and run contract tests against the sandbox. The trade-off: extra code, in exchange for surviving or replacing the upstream without touching the domain.

🗣 Full answer (senior)

How I would answer this in an interview

"I build an anti-corruption layer whenever my core domain depends on a model I can't control and don't want to adopt: a legacy mainframe, a SOAP service with cryptic codes, or a vendor API. The goal is that the upstream's language stops at one boundary. My domain never sees VRF_STS_CD = 'P2'; it sees VerificationOutcome.NeedsManualReview.

Structurally there are three pieces. First, the port, an interface owned by the domain or application layer and written in our language, like IIdentityVerifier.VerifyAsync(Applicant, ct) returning our own result type. Second, the facade or client, which is a typed HttpClient that knows the upstream's URLs, auth and DTOs, with the standard resilience handler for retries, timeouts and a circuit breaker. Third, the translator, a static class of pure functions that maps their DTOs and codes into our value objects. An adapter class implements the port by calling the client and then the translator. All of that sits in an Infrastructure folder for that integration, marked internal, and only the DI registration is public.

Two details matter in practice. One is unknown values: when the vendor adds a new status code, the translator must not quietly default to 'approved'. I map unknown codes to an explicit failure, log it with the raw value, and increment a metric so we find out the same day. The other is errors: their HTTP 500s and SOAP faults become our domain-level outcomes or a single infrastructure exception type, never their exception classes leaking upwards. For testing, the translator gets fast table-driven unit tests, the adapter gets tests against WireMock.Net with recorded responses, and a nightly contract test hits the vendor's sandbox. The mistake I see is the ACL being a thin pass-through that just renames the class but still returns the vendor's fields; then it isn't protecting anything."


The parts and where they live

Part Knows about Project / folder Visibility
Port (interface) Domain types only Domain or Application public
Facade / client Upstream protocol, auth, DTOs Infrastructure/Integrations/Vendor internal
Translator Upstream DTOs + domain types Infrastructure/Integrations/Vendor internal
Adapter Port, client, translator Infrastructure/Integrations/Vendor internal
DI registration Everything above Infrastructure (extension method) public

Testing strategy

Test Tool Catches
Translator unit tests xUnit theory with every code Mapping mistakes, unknown codes
Adapter tests WireMock.Net with recorded JSON Serialisation, headers, error handling
Contract test Vendor sandbox, nightly Upstream changes before production
Domain tests Fake implementation of the port Domain logic, no network

Production example

We wrapped a [document-verification vendor] used for Australian identity checks (driver licence and passport via the [DVS] gateway) behind an IIdentityVerifier ACL. When we moved to a [second vendor] [18 months] later, the change was a new adapter of [about 350 lines] plus its tests; the onboarding domain and its [120] tests didn't change, and the cut-over was a feature flag.

🔍 What the interviewer is checking

Checks that the candidate can implement an ACL that actually translates a model, places it correctly, and makes it resilient and testable.

Green flags

  • Port owned by the domain, implementation internal in Infrastructure
  • Pure translator with explicit handling of unknown codes
  • Uses typed HttpClient with the standard resilience handler
  • Layered testing including contract tests; avoids logging PII

Red flags

  • Interface that returns vendor DTOs
  • Vendor SDK types referenced from the domain
  • No plan for unknown values or upstream errors

📚 Learn in depth

1. Why translation, not just wrapping

Wrapping hides the transport; translation hides the model. If your interface returns VendorResultDto, you have an adapter but not an ACL. The ACL's job is semantic: mapping concepts, codes, units, time zones and identities.

 Onboarding domain            ACL (Infrastructure)                      Vendor
 -----------------            --------------------                      ------
 IIdentityVerifier ◄── VendorIdentityAdapter ──► VendorClient ── HTTPS ──► /v3/checks
   Applicant                    │                (typed HttpClient,
   VerificationOutcome          ▼                 resilience, auth)
                         VendorTranslator
                         (DTO ↔ domain, codes, dates, errors)

2. What translators handle

Concern Example
Codes "P2" → NeedsManualReview
Units cents → Money in dollars
Time "20261120" in AEST → DateOnly / DateTimeOffset
Identity vendor reference → your VerificationId
Structure flat 60-field record → small value objects
Errors {"err":"E104"} → VerificationOutcome.DocumentExpired

3. Resilience

AddHttpClient<VendorClient>().AddStandardResilienceHandler() (Microsoft.Extensions.Http.Resilience, built on Polly v8) adds a total timeout, retry with exponential backoff and jitter, a circuit breaker and an attempt timeout. Only retry idempotent calls or calls with an idempotency key.

4. Two-way ACLs

When you also send data upstream (create a policy in the legacy system), the translator maps both ways. Keep the outbound mapping just as strict: validate before sending.

5. ACL vs other boundaries

  • An adapter (hexagonal) converts protocols; an ACL is an adapter plus translation, protecting a model.
  • A gateway or YARP proxy routes traffic; it can host an ACL in a strangler-fig migration but is not one by itself.

6. Observability

Log upstream request ids and raw codes on translation failures (never PII: identity documents fall under the Privacy Act 1988 and APPs). Emit a counter like acl.translation_failures{vendor,code} and alert on any non-zero rate after a vendor release.

Try it yourself

  1. Write a translator for a vendor status enum with a theory test per code, including an unknown code.
  2. Stand up WireMock.Net returning a recorded response and test the adapter end to end.
  3. Add AddStandardResilienceHandler() and simulate a 503 burst; watch retries in logs.
  4. Search your domain project for any type from a vendor SDK namespace; that is a leak.

💻 Code

An identity-verification ACL: port, client, translator, adapter, DI and tests.

// Domain (or Application): the port, in our language.
namespace Onboarding.Domain;

public sealed record Applicant(string GivenName, string FamilyName, DateOnly DateOfBirth, string LicenceNumber, string State);

public enum VerificationOutcome { Verified, NotVerified, NeedsManualReview, DocumentExpired, Unavailable }

public interface IIdentityVerifier
{
    Task<VerificationOutcome> VerifyAsync(Applicant applicant, CancellationToken ct);
}
// Infrastructure: the ACL. Everything internal except registration.
namespace Onboarding.Infrastructure.IdVendor;

using System.Net.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Onboarding.Domain;

internal sealed record VendorCheckRequest(string fn, string ln, string dob, string doc_no, string doc_juris);
internal sealed record VendorCheckResponse(string ref_id, string sts_cd, string? err);

internal sealed class VendorClient(HttpClient http)
{
    public async Task<VendorCheckResponse?> CheckAsync(VendorCheckRequest req, CancellationToken ct)
    {
        using var resp = await http.PostAsJsonAsync("/v3/checks", req, ct);
        resp.EnsureSuccessStatusCode();
        return await resp.Content.ReadFromJsonAsync<VendorCheckResponse>(ct);
    }
}

internal static class VendorTranslator
{
    public static VendorCheckRequest ToVendor(Applicant a) =>
        new(a.GivenName, a.FamilyName, a.DateOfBirth.ToString("yyyyMMdd"), a.LicenceNumber, a.State);

    public static VerificationOutcome? ToDomain(VendorCheckResponse r) => (r.sts_cd, r.err) switch
    {
        ("Y", _) => VerificationOutcome.Verified,
        ("N", _) => VerificationOutcome.NotVerified,
        ("P1" or "P2", _) => VerificationOutcome.NeedsManualReview,
        (_, "E104") => VerificationOutcome.DocumentExpired,
        _ => null // unknown: caller decides; never silently 'Verified'
    };
}

internal sealed class VendorIdentityAdapter(VendorClient client, ILogger<VendorIdentityAdapter> log) : IIdentityVerifier
{
    public async Task<VerificationOutcome> VerifyAsync(Applicant applicant, CancellationToken ct)
    {
        try
        {
            var resp = await client.CheckAsync(VendorTranslator.ToVendor(applicant), ct);
            if (resp is null) return VerificationOutcome.Unavailable;

            var outcome = VendorTranslator.ToDomain(resp);
            if (outcome is null)
            {
                log.LogWarning("Unknown vendor status {Status}/{Error} for ref {Ref}", resp.sts_cd, resp.err, resp.ref_id);
                return VerificationOutcome.NeedsManualReview; // safe default for an unknown code
            }
            return outcome.Value;
        }
        catch (HttpRequestException ex)
        {
            log.LogError(ex, "Identity vendor unavailable");
            return VerificationOutcome.Unavailable; // vendor exceptions never leak upwards
        }
    }
}

public static class IdVendorRegistration
{
    public static IServiceCollection AddIdVendor(this IServiceCollection services, Uri baseAddress)
    {
        services.AddHttpClient<VendorClient>(c => c.BaseAddress = baseAddress)
                .AddStandardResilienceHandler();
        services.AddScoped<IIdentityVerifier, VendorIdentityAdapter>();
        return services;
    }
}
// Tests: translator is pure, so tests are trivial and fast.
public class VendorTranslatorTests
{
    [Theory]
    [InlineData("Y", null, VerificationOutcome.Verified)]
    [InlineData("N", null, VerificationOutcome.NotVerified)]
    [InlineData("P2", null, VerificationOutcome.NeedsManualReview)]
    [InlineData("X", "E104", VerificationOutcome.DocumentExpired)]
    public void Maps_known_codes(string sts, string? err, VerificationOutcome expected) =>
        Assert.Equal(expected, VendorTranslator.ToDomain(new("r1", sts, err)));

    [Fact]
    public void Unknown_code_is_not_silently_accepted() =>
        Assert.Null(VendorTranslator.ToDomain(new("r1", "Z9", null)));
}

(InternalsVisibleTo lets the test project see the internal translator.)

⚠ Common mistakes

  • Mistake: Returning the vendor's DTO through the interface. Why it is wrong: the upstream model leaks into the domain; it is an adapter, not an ACL. Instead: the port returns domain types only.
  • Mistake: Defaulting unknown codes to a success value. Why it is wrong: a new vendor code silently approves applicants or orders. Instead: map unknowns to an explicit safe outcome or failure, log the raw value and alert.
  • Mistake: Letting vendor exceptions or SDK types propagate. Why it is wrong: callers couple to the vendor's error model. Instead: catch at the adapter and return domain outcomes or one infrastructure exception type.
  • Mistake: Making the ACL types public. Why it is wrong: other code starts using the vendor client directly. Instead: internal types and a public DI extension method.
  • Mistake: Applying the same retry policy to every call. Why it is wrong: GET and other idempotent calls are safe to retry, but retrying a non-idempotent POST after a timeout can create a second verification, payment or policy upstream, because the first may have succeeded. In domain terms that is a duplicate business fact. Instead: retry idempotent calls freely; for POSTs send an idempotency key the vendor honours, or disable retries for that route and reconcile.
  • Mistake: Translating only inbound data. Why it is wrong: outbound requests built from domain objects without validation send invalid or partial data upstream, and the vendor's rejection codes leak back. Instead: translate and validate outbound too, and map rejection codes to domain outcomes.
  • Mistake: Logging full requests and responses. Why it is wrong: identity documents and personal data end up in logs, breaching APP 11 obligations. Instead: log references and codes, redact PII.
  • Mistake: Testing only against mocks of your own port. Why it is wrong: serialisation and vendor changes are never exercised. Instead: WireMock.Net adapter tests plus a nightly sandbox contract test.

🏛 Senior insight: trade-offs

An ACL is insurance: you pay a premium (translation code and tests) to protect the most valuable part of your system from things you don't control. It is worth it for a core domain and for any vendor you might replace; it is overkill for a supporting context reading a good upstream model, where conforming is cheaper.

Option When it fits Cost When not to
Full ACL (port, client, translator) Core domain, poor or volatile upstream, possible vendor swap 300-800 lines per integration plus tests Supporting context with a decent upstream
Thin adapter (conformist) Supporting context, good upstream model Low Upstream naming would spread into a core model
Shared ACL service Several contexts consuming the same legacy system A service to run Only one consumer

I measure the ACL by translation failure counts after upstream releases and by how much domain code changes when the vendor changes (target: none).

🔗 Follow-ups the interviewer may ask

  1. When: Candidate describes the ACL as an adapter around a vendor SDK. Why: Checks the Adapter pattern basics and what belongs inside an adapter.
    How to answer

    Adapter converts the interface of an existing class into the interface your code expects, without changing either side. It's a translator.

    • An object adapter wraps the adaptee by composition. This is the normal C# form.
    • A class adapter inherits the adaptee and implements the target. C# allows only one base class, so it's rare.

    For a payment SDK, I define IPaymentGateway in my domain's terms. A StripePaymentGateway adapter then turns it into SDK calls, translating types and units (decimal AUD to cents), statuses and vendor exceptions into domain results. That keeps vendor types out of the codebase, lets tests use a fake, and confines a provider change to one class.

    The trade-off is an extra layer. Keep it thin: an adapter translates, and business rules don't belong in it.

  2. When: Candidate mentions ports and adapters. Why: Checks they connect the ACL to hexagonal architecture.
    How to answer

    They are variations of one idea: put the domain at the centre and make every source dependency point inwards, so technology plugs into the business logic rather than the reverse.

    • Hexagonal / ports and adapters (Cockburn, 2005) frames it as an application with ports (interfaces in the app's language) and adapters: driving adapters call in (HTTP endpoints, message consumers, tests); driven adapters are called out to (SQL Server, email, payment APIs).
    • Onion (Palermo, 2008) draws concentric rings: domain model, domain services, application services, then infrastructure and UI.
    • Clean (Martin, 2012) combines them with an explicit dependency rule and a use-case layer.

    The trade-off is the same for all three: testable, swappable boundaries in exchange for more interfaces and indirection.

  3. When: Candidate mentions conformist or open host service as alternatives. Why: Checks they can choose between context-mapping patterns.
    How to answer

    A context map shows the bounded contexts and how their teams and models relate. Each relationship has an upstream (whose model influences others) and a downstream. The patterns describe who adapts: partnership (teams succeed or fail together), shared kernel (a small model both own), customer-supplier (upstream plans for downstream needs), conformist (downstream simply adopts the upstream model), anti-corruption layer (downstream translates to protect its model), open host service with a published language (upstream offers a stable, versioned protocol for many consumers) and separate ways (do not integrate).

    I choose by power (can I influence the upstream?), upstream model quality, how core my context is and how many consumers exist. The trade-off is translation cost versus model purity: an ACL costs code, conforming costs your model.

🛠 Real-world problems: how you handle them

Vendor added a status code and applicants were auto-approved
Situation
A [lending] platform called an identity-verification vendor during onboarding, [~3,000] applications a day. The integration deserialised the vendor's status straight into an enum with a default of `Verified`.
Signals
Fraud team noticed [40+] approved applications in a day with no matching vendor verification record; the vendor's release notes mentioned a new 'pending secondary source' code.
Investigation
Searched logs for the raw status values, found the new code mapping to the default enum value, and traced the vendor DTO usage across [seven] files in the domain and API.
Resolution
Immediately paused auto-approval behind a feature flag and sent affected applications to manual review. Then built an ACL: a domain `IIdentityVerifier` port, an internal translator that maps unknown codes to `NeedsManualReview`, and a resilient typed client.
Prevention
Translator theory tests for every known code plus an unknown-code test, a translation-failure metric with an alert, a nightly sandbox contract test, and an architecture test banning vendor namespaces in the domain.

How to tell it (STAR)

**S:** At [company], a vendor added a new status code and our onboarding flow auto-approved [40+] applications without a full identity check. **T:** I [led the incident fix and the follow-up design]. **A:** I paused auto-approval behind a flag within [an hour], then replaced the leaky integration with an anti-corruption layer whose translator treats unknown codes as manual review, added an alert on unknown codes and a nightly contract test. **R:** No unverified approvals since; the next two vendor code changes were caught by the alert [the same day], and a later vendor switch changed one adapter and no domain code.

↩ Usually asked after

More in Domain-Driven Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me