← All blogs

FullStack Engineering CourseLesson 10 of 20 18 min

Integration and Migration: Strangler Fig, Anti-Corruption Layer, Multi-Tenancy and Real-Time

Living with older systems

Most real work is not on new systems. It is on systems that already run the business: an old billing platform, a mainframe that holds patient records, a payer's SOAP API, a monolith built fifteen years ago. This lesson covers how to integrate with such systems safely and how to replace them gradually, plus two topics that come up in almost every modern platform: serving many customers from one system (multi-tenancy) and pushing live updates to users.

Why not rewrite everything at once

A complete rewrite ("big bang") looks attractive: start clean, switch over on one day. It usually goes badly:

  • The old system keeps changing while the new one is built, so the target keeps moving.
  • Nobody delivers value to users until the very end, often years later.
  • The old system holds undocumented rules that are discovered only after the switch, in production.
  • The switch-over day carries all the risk at once, with no easy way back.

The safer approach is incremental: replace the old system piece by piece while it keeps running, so each step is small, delivers value and can be reversed.

The Strangler Fig pattern

A strangler fig is a plant that grows around a tree, gradually taking its place until the old tree can be removed. The Strangler Fig pattern does the same with software:

  1. Put a routing layer (a facade) in front of the old system: an API gateway, a reverse proxy such as YARP, or a BFF. At first it sends everything to the old system, and nothing changes for users.
  2. Pick one capability, ideally one bounded context with clear edges (for example, claim status lookups), and build it in the new system.
  3. Change the routing so requests for that capability go to the new system. Keep the ability to switch back.
  4. Repeat, capability by capability, until nothing is routed to the old system.
  5. Switch off and remove the old system.

In .NET, YARP (Yet Another Reverse Proxy) makes the routing layer a normal ASP.NET Core app. Routes can move from the old system to the new one through configuration:

JSON
// Program.cs of the facade: builder.Services.AddReverseProxy().LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
// app.MapReverseProxy();
{
  "ReverseProxy": {
    "Routes": {
      "claim-status": { "ClusterId": "new-claims", "Match": { "Path": "/api/claims/{id}/status" } },
      "everything-else": { "ClusterId": "legacy", "Match": { "Path": "{**catch-all}" } }
    },
    "Clusters": {
      "new-claims": { "Destinations": { "d1": { "Address": "https://claims-api.internal/" } } },
      "legacy":     { "Destinations": { "d1": { "Address": "https://legacy-billing.internal/" } } }
    }
  }
}

Data is the hardest part. While both systems run, they may both need the same data. Common approaches:

  • The new system owns the data for the capability it took over, and publishes events or provides an API that the old system calls.
  • Change data capture (lesson 13) copies changes from the old database into the new system, so the new system can serve reads before it takes over writes.
  • Move reads first and writes later. Reads are lower risk, and they let you compare the two systems' answers before the switch.

Before switching a capability, you can run both systems side by side: send each request to both, return the old system's answer, and log any differences (this is sometimes called shadow traffic). Switch only when the differences are understood.

The Anti-Corruption Layer

When a new system has to talk to an old or external one, the other system's model tends to leak in: its odd field names, codes and assumptions appear throughout the new code. An Anti-Corruption Layer (ACL) is a translation layer that stops this. The new system talks only in its own model; the ACL translates to and from the other system's model at the boundary.

C#
// The legacy billing system's shape: codes, flags and strings, exactly as it returns them.
public sealed record LegacyClaimRecord(string CLM_NO, string STS_CD, string AMT, string SVC_DT, string PYR);

// Our domain's port: the new code only ever sees this.
public interface IClaimHistorySource
{
    Task<ClaimSummary?> GetAsync(ClaimId id, CancellationToken ct);
}

// The ACL: an adapter that translates, so no legacy concepts leak inwards.
public sealed class LegacyBillingAdapter(LegacyBillingClient legacy) : IClaimHistorySource
{
    public async Task<ClaimSummary?> GetAsync(ClaimId id, CancellationToken ct)
    {
        LegacyClaimRecord? r = await legacy.FetchClaimAsync(id.Value.ToString("D10"), ct);   // legacy wants zero-padded IDs
        if (r is null) return null;

        return new ClaimSummary(
            Id: id,
            Status: r.STS_CD switch
            {
                "P" => ClaimStatus.Pending,
                "A" or "AP" => ClaimStatus.Approved,     // two legacy codes mean the same thing to us
                "D" => ClaimStatus.Denied,
                var other => throw new UnknownLegacyCodeException("STS_CD", other)
            },
            Amount: new Money(decimal.Parse(r.AMT, CultureInfo.InvariantCulture) / 100m, "INR"),   // legacy stores cents as text
            ServiceDate: DateOnly.ParseExact(r.SVC_DT, "yyyyMMdd", CultureInfo.InvariantCulture),
            PayerCode: r.PYR.Trim());
    }
}

Benefits of an ACL:

  • The domain model stays clean, and the legacy quirks are in one place.
  • When the old system is replaced, only the adapter changes.
  • Translation rules are easy to test with recorded examples of real legacy data.

Fail clearly on values you do not recognise, as the switch above does, rather than guessing. An unknown status code from an old system is a question for the business, not something to map silently to a default.

Use the same idea for every external integration, not only legacy ones: a payer API, a clearing house, an EHR (electronic health record) system. Each gets its own adapter behind a port that speaks your language.

Multi-tenancy

A multi-tenant system serves many customers (tenants), such as several hospital groups, from one deployment, while keeping each tenant's data separate. The main design choice is how to isolate their data:

ModelHowIsolationCost and operationsFits
Shared database, shared tablesEvery row has a TenantId columnLowest: one missing filter can expose another tenant's dataCheapest; one schema to migrateMany small tenants
Shared database, schema per tenantEach tenant has its own schema in one databaseMediumMigrations run per schemaA moderate number of tenants
Database per tenantEach tenant has its own database (Azure SQL elastic pools help with cost)High: separate backups, restores and encryption keysMore databases to manage; migrations run per databaseLarge or regulated tenants, data residency rules
Deployment per tenantEach tenant gets its own copy of the whole systemHighestMost expensiveCustomers who demand full isolation

Many platforms mix models: most tenants share, and large or regulated tenants get their own database. Whatever the model, a few rules always apply:

  • Resolve the tenant once per request, from a trusted source: a claim in the user's token, or the host name. Never from a value the client can freely change, such as a query string.
  • Enforce isolation in one central place, not in every query. In EF Core, a global query filter adds the tenant condition to every query automatically.
  • Add a second line of defence in the database, such as SQL Server row-level security, so a bug in application code still cannot return another tenant's rows.
  • Include the tenant in cache keys, blob paths, message properties and logs.
  • Watch for noisy neighbours: one tenant's heavy usage slowing down everyone else. Use per-tenant rate limits and quotas.
C#
public interface ITenantContext { Guid TenantId { get; } }

public sealed class ClaimsDbContext(DbContextOptions<ClaimsDbContext> options, ITenantContext tenant) : DbContext(options)
{
    public DbSet<Claim> Claims => Set<Claim>();

    protected override void OnModelCreating(ModelBuilder model)
    {
        // Every query on Claims gets "WHERE TenantId = @current" added automatically.
        model.Entity<Claim>().HasQueryFilter(c => c.TenantId == tenant.TenantId);
    }

    public override Task<int> SaveChangesAsync(CancellationToken ct = default)
    {
        foreach (var entry in ChangeTracker.Entries<Claim>().Where(e => e.State == EntityState.Added))
            entry.Entity.TenantId = tenant.TenantId;          // new rows always get the current tenant
        return base.SaveChangesAsync(ct);
    }
}

Be careful with IgnoreQueryFilters(), which turns the filter off. Allow it only in a few reviewed places, such as platform administration, and log every use.

Real-time updates: polling, SSE, WebSockets and SignalR

Users increasingly expect screens to update by themselves: a claim status that changes from Submitted to Approved without a refresh, a progress bar for a file import. There are four ways to do this:

TechniqueHow it worksDirectionGood forWatch out for
PollingThe client asks every few secondsClient to serverRare updates, simple setupsWasted requests; updates arrive late
Long pollingThe server holds each request open until there is newsServer to client (emulated)Old environments without better optionsMany open requests; awkward to implement
Server-Sent Events (SSE)One long-lived HTTP response; the server writes events into it as they happenServer to client onlyNotifications, progress, live status, streaming AI responsesOne direction only; text only
WebSocketsA persistent two-way connection, upgraded from HTTPBoth waysChat, collaborative editing, live dashboards with user inputStateful connections; harder to scale and to pass through some proxies

SSE is often all you need for pushing status updates. It is plain HTTP, browsers reconnect automatically (through the EventSource API), and .NET 10 adds built-in support for returning it from minimal APIs. The idea is simple enough to write directly:

C#
app.MapGet("/api/v1/claims/{id:int}/events", async (int id, HttpContext http, IClaimStatusFeed feed, CancellationToken ct) =>
{
    http.Response.Headers.ContentType = "text/event-stream";
    http.Response.Headers.CacheControl = "no-cache";

    await foreach (ClaimStatusChanged change in feed.WatchAsync(id, ct))   // completes when the client disconnects
    {
        await http.Response.WriteAsync($"event: status\ndata: {JsonSerializer.Serialize(change)}\n\n", ct);
        await http.Response.Body.FlushAsync(ct);                            // send it now, do not buffer
    }
});
JavaScript
// Browser
const source = new EventSource(`/api/v1/claims/${claimId}/events`);
source.addEventListener("status", (e) => showStatus(JSON.parse(e.data)));   // reconnects automatically

SignalR is ASP.NET Core's library for real-time communication. It uses WebSockets when it can, and falls back to SSE or long polling when it cannot. It adds hubs (server classes that clients call and that can call clients), groups (send to everyone watching one claim or one tenant) and automatic reconnection:

C#
public sealed class ClaimsHub : Hub
{
    // Clients join a group per claim they are viewing.
    public Task WatchClaim(int claimId) => Groups.AddToGroupAsync(Context.ConnectionId, $"claim-{claimId}");
}

builder.Services.AddSignalR();
app.MapHub<ClaimsHub>("/hubs/claims");

// Anywhere in the app, for example in the event handler for ClaimStatusChanged:
public sealed class NotifyWatchers(IHubContext<ClaimsHub> hub)
{
    public Task HandleAsync(ClaimStatusChanged e, CancellationToken ct) =>
        hub.Clients.Group($"claim-{e.ClaimId}").SendAsync("statusChanged", e, ct);
}

Scaling real-time connections needs care:

  • Each connection lives on one server. With several instances, a message raised on server A must reach users connected to server B. Use a backplane (Redis for SignalR), or Azure SignalR Service, which holds the connections for you and scales to very large numbers.
  • Configure the load balancer for long-lived connections: WebSocket support, and longer idle timeouts.
  • Authenticate connections like any request, and check authorisation when a client joins a group: a user must not be able to watch another tenant's claims.
  • Treat real-time messages as hints, not the source of truth. After a reconnect, the client should reload the current state, because messages sent while it was disconnected are lost.

Check your understanding

QuestionShort answer
Why avoid a big-bang rewrite?The target keeps moving, value comes only at the end, hidden rules surface late, and the switch-over carries all the risk.
How does the Strangler Fig pattern work?A routing facade sends traffic to the old system, and capabilities move to the new system one at a time until the old one can be removed.
What is shadow traffic for?Sending requests to both systems and comparing answers, to find differences before switching.
What does an Anti-Corruption Layer do?Translates between another system's model and yours at the boundary, so its concepts do not leak into your domain.
Shared tables or a database per tenant?Shared tables are cheapest but rely on filters for isolation; a database per tenant isolates strongly and suits large or regulated tenants.
Where should the tenant ID come from?A trusted source, such as a token claim or the host name, never a value the client can freely set.
How does EF Core help with multi-tenancy?A global query filter adds the tenant condition to every query; row-level security in the database adds a second layer.
SSE or WebSockets?SSE for one-way server-to-client updates over plain HTTP; WebSockets when the client must also send messages over the same connection.
What does SignalR add?Hubs, groups, automatic transport fallback and reconnection.
How do real-time updates work across several instances?Through a backplane such as Redis, or Azure SignalR Service, which holds the connections.

Summary

  • Replace old systems incrementally with the Strangler Fig pattern: a routing facade, one capability at a time, with a way back.
  • Move reads before writes, and compare old and new answers before switching.
  • Protect your domain with an Anti-Corruption Layer for every legacy or external system, and fail clearly on unknown values.
  • Choose a tenant isolation model per tenant size and regulation, resolve the tenant from a trusted source, and enforce isolation centrally and in the database.
  • Push updates with SSE when they flow one way, and SignalR or WebSockets when they flow both ways; plan for scale-out, authorisation and reconnects.

The next lesson is about how architecture decisions are made and communicated: C4 diagrams, architecture decision records and RFCs, NFR and design reviews, threat modelling with STRIDE, and cost management (FinOps).

Found this useful? Share it: LinkedIn X

Comments