Breaking free from legacy ASP.NET MSDTC: A practical migration guide to the Transactional Outbox Pattern on Cloud SQL

How to refactor legacy distributed two-phase commits into fast, resilient, cloud-native workflows without rewriting your core business logic or stored procedures.

When enterprise engineering teams lift and modernize legacy .NET or Java applications onto managed database platforms like Google Cloud SQL for SQL Server, Cloud SQL for PostgreSQL, Amazon RDS, or Azure SQL, one architectural blocker surfaces almost immediately: Microsoft Distributed Transaction Coordinator (MSDTC) and cross-instance Two-Phase Commit (2PC / XA).

For decades, on-premises monolithic applications relied on System.Transactions.TransactionScope (or JTA/XA) to wrap writes across multiple database instances—and sometimes even synchronous HTTP or SOAP calls—inside a single distributed transaction. On managed cloud databases, OS-level distributed transaction coordinators are intentionally unsupported. More importantly, even where self-hosted VMs allow MSDTC, synchronous distributed locks degrade throughput, amplify tail latency, and turn transient downstream blips into full user-facing outages.

This guide provides a complete, step-by-step blueprint for replacing MSDTC with a Decoupled Transactional Outbox Pattern. You will learn how to audit your codebase for hidden MSDTC promotions, preserve existing legacy stored procedures, guarantee at-least-once delivery with strict target idempotency, and run the relay as a stateless, scheduler-driven Cloud Run worker on Google Cloud.

Companion code: Every snippet in this guide comes from a runnable, end-to-end sample: two separate SQL Server instances, an Orders API, an internal relay worker, a mock billing API, and a local Cloud Scheduler stand-in, all started with one docker compose up. See CloudSqlOutboxSample.


Why MSDTC blocks Cloud SQL migrations

To understand why MSDTC breaks during cloud modernization—and why emulating it over a VPC is an anti-pattern—it helps to inspect what happens under the hood when an application spans multiple resources in a single request.

How implicit MSDTC escalation happens in .NET

In .NET applications, developers rarely invoke MSDTC APIs directly. Instead, they wrap service methods in a TransactionScope. As long as execution touches a single SqlConnection, SQL Server manages the transaction locally via Lightweight Transaction Manager (LTM). The moment a second SqlConnection opens against a different database instance (or a second connection opens concurrently before the first closes), LTM silently escalates the transaction to an OS-level MSDTC Two-Phase Commit (OLE TX).

Consider a classic enterprise order-placement method touching a primary commerce database, a secondary regional fulfillment database (via a legacy stored procedure), and an external billing REST API:

// ANTI-PATTERN: Implicitly promotes to MSDTC and holds DB locks across network HTTP I/O.
// Fails on Cloud SQL for SQL Server and other managed database platforms.
public async Task<Guid> PlaceOrderLegacyAsync(PlaceOrderRequest request, CancellationToken ct)
{
    var txOptions = new TransactionOptions
    {
        IsolationLevel = IsolationLevel.ReadCommitted,
        Timeout = TransactionManager.DefaultTimeout
    };

    using var scope = new TransactionScope(
        TransactionScopeOption.Required,
        txOptions,
        TransactionScopeAsyncFlowOption.Enabled);

    // 1. Write core order to Primary Database (Starts as lightweight local transaction)
    var order = new Order
    {
        Id = Guid.NewGuid(),
        CustomerId = request.CustomerId,
        TotalAmount = request.TotalAmount,
        Status = "CONFIRMED",
        CreatedAt = DateTime.UtcNow
    };
    _primaryDb.Orders.Add(order);
    await _primaryDb.SaveChangesAsync(ct);

    // 2. Execute legacy stored procedure on Secondary Fulfillment Instance
    // --> ESCALATION POINT: Opening a connection to a second SQL instance triggers MSDTC!
    // --> Throws TransactionManagerCommunicationException / PlatformNotSupportedException on Cloud SQL.
    await _fulfillmentDb.Database.ExecuteSqlInterpolatedAsync(
        $"EXEC dbo.sp_ProvisionFulfillmentOrder @OrderId={order.Id}, @WarehouseCode={request.WarehouseCode}",
        ct);

    // 3. Synchronous external HTTP call INSIDE the open distributed transaction!
    // --> Exclusive row/page locks remain held on BOTH databases while waiting on external HTTP I/O.
    await _billingApiClient.AuthorizeAndCaptureInvoiceAsync(order.Id, order.TotalAmount, ct);

    scope.Complete();
    return order.Id;
}

Three reasons distributed two-phase commit fails in the cloud

  1. Managed database platform boundaries: Cloud SQL for SQL Server explicitly does not support MSDTC for cross-instance distributed transactions. Managed database services isolate the underlying Windows/Linux host OS, block inbound/outbound DCOM and RPC port ranges required by msdtc.exe, and automate high-availability failovers that cannot reconcile external OS coordinator state files.
  2. Cross-server lock amplification: Two-Phase Commit requires every participating database to hold exclusive locks across both the Prepare phase and the Commit phase. If an external REST call takes 800 ms—or times out after 30 seconds—database locks remain held across multiple instances for the entire duration, starving connection pools and triggering cascading deadlocks.
  3. Multiplicative availability degradation: Synchronous coupling binds the uptime of your primary write API to the product of every downstream dependency. If Primary Cloud SQL, Secondary Cloud SQL, and an external Billing API each offer 99.9% availability, the composite synchronous endpoint drops to 0.999 * 0.999 * 0.999 = 99.7%—tripling unplanned downtime.

Auditing your codebase for hidden MSDTC dependencies

Before migrating to Cloud SQL, run a systematic discovery pass across your application repositories and live SQL Server instances to locate every explicit or implicit distributed transaction:

# 1. Static codebase scan: Locate TransactionScope, XA, and cross-server SQL patterns
rg -n "TransactionScope|EnlistTransaction|DistributedTransaction|OPENDATASOURCE|OPENQUERY" ./src

# 2. Check EF Core / ADO.NET contexts injected together into the same service constructor
rg -n "DbContext" ./src/Services

On your existing on-premises SQL Server instances, query Dynamic Management Views (DMVs) during peak traffic or run an Extended Events session to verify whether live workloads are enlisting MSDTC (dtc_state or UOW distributed identifiers):

-- Identify active distributed transactions enlisted via MSDTC (non-null UOW)
SELECT
    s.session_id,
    s.login_name,
    s.program_name,
    at.transaction_id,
    at.name AS transaction_name,
    at.transaction_begin_time,
    at.dtc_state,
    st.transaction_uow -- Non-NULL GUID indicates an active MSDTC distributed transaction
FROM sys.dm_tran_active_transactions AS at
INNER JOIN sys.dm_tran_session_transactions AS st
    ON at.transaction_id = st.transaction_id
INNER JOIN sys.dm_exec_sessions AS s
    ON st.session_id = s.session_id
WHERE st.transaction_uow IS NOT NULL;

Tip: Note that same-instance cross-database transactions (two databases hosted inside the exact same Cloud SQL for SQL Server instance using a single SqlConnection) do not require MSDTC and continue to work natively. You only need the Transactional Outbox Pattern when crossing separate database instances, heterogeneous engines (e.g., SQL Server to PostgreSQL or BigQuery), or external APIs and message brokers.


Enter the Transactional Outbox Pattern

The Transactional Outbox Pattern eliminates distributed locks by splitting a cross-system workflow into atomic local persistence followed by idempotent asynchronous relay.

How the three-phase architecture works

Instead of coordinating locks across servers simultaneously, the architecture enforces consistency across three decoupled boundaries:

  • Phase 1 — Synchronous Local ACID Commit (< 15 ms): When a client invokes POST /api/orders, the application opens a single local database transaction on Primary Cloud SQL. Inside that transaction, it writes the Orders business record and inserts an immutable event row (OrderPlacedEvent) into an OutboxMessages table in the same database. Because both tables live in the same database, standard local ACID guarantees ensure the order and its outbox event either both commit or both roll back—with zero split-brain risk.
  • Phase 2 — Decoupled External Relay: Rather than running fragile while(true) background polling threads inside user-facing web containers (which suffer from noisy-neighbor CPU spikes, container scale-down terminations, and lock contention), an external trigger drives a stateless relay worker: Google Cloud Scheduler invokes an internal Cloud Run worker endpoint on a fixed cadence, and the worker claims unlocked pending rows via UPDLOCK, ROWLOCK, READPAST (or FOR UPDATE SKIP LOCKED in PostgreSQL).
  • Phase 3 — Idempotent Multi-Target Fan-Out: The relay guarantees at-least-once delivery, meaning a message can be delivered more than once after a worker crash, an expired lease, or a network timeout. Every downstream database applies an atomic Idempotency Guard (ProcessedEvents table) in its own local transaction alongside your existing legacy stored procedures, while external REST calls pass deterministic Idempotency-Key headers backed by jittered exponential backoff.

When to use Outbox vs. Saga Orchestration

While the Transactional Outbox guarantees reliable event propagation and eventual consistency, some legacy MSDTC workflows involve multi-step business validations that can legitimately reject a transaction mid-flight (for example, reserving limited inventory that might be out of stock). Use this rule of thumb:

Legacy MSDTC Workflow Characteristic Recommended Cloud-Native Replacement Why
Downstream steps must eventually succeed (provisioning tenant DB records, syncing read replicas, audit logs, billing webhooks, notifications) Transactional Outbox Pattern Primary DB is the source of truth; downstream targets simply need guaranteed, idempotent propagation.
Downstream steps can reject business rules (credit limit denial, out-of-stock warehouse reservation requiring primary rollback) Outbox + Choreography/Orchestration Saga Persist primary entity in PENDING state + Outbox event; if downstream emits a failure event, execute an explicit compensating transaction (e.g., Status = CANCELLED).

Step-by-step migration guide: Refactoring MSDTC to Outbox

Let’s walk through refactoring our earlier PlaceOrderLegacyAsync method into a production-hardened Transactional Outbox pipeline on Cloud SQL for SQL Server and .NET 8+.

Step 1: Create the Outbox and Idempotency database schemas

On your Primary Cloud SQL database, create the dbo.OutboxMessages table. Pay close attention to the filtered non-clustered index (WHERE [Status] IN (0, 1)): as your outbox table processes millions of historical rows (Status = 2), a filtered index keeps the active working set tiny in buffer-pool memory so batch-claim queries remain sub-millisecond.

-- Run on PRIMARY Database (e.g., CoreCommerceDb on Cloud SQL for SQL Server)
CREATE TABLE [dbo].[OutboxMessages] (
    [Id]            UNIQUEIDENTIFIER NOT NULL CONSTRAINT [PK_OutboxMessages] PRIMARY KEY NONCLUSTERED,
    [SequenceNo]    BIGINT           IDENTITY(1,1) NOT NULL,
    [AggregateType] NVARCHAR(100)    NOT NULL, -- e.g., 'Order'
    [AggregateId]   NVARCHAR(100)    NOT NULL, -- Partition key for strict per-entity FIFO ordering
    [EventType]     NVARCHAR(150)    NOT NULL, -- Routing key, e.g., 'OrderPlacedEvent.v1'
    [Payload]       NVARCHAR(MAX)    NOT NULL, -- Immutable JSON snapshot
    [CorrelationId] NVARCHAR(100)    NULL,     -- W3C TraceParent for OpenTelemetry propagation
    [Status]        TINYINT          NOT NULL CONSTRAINT [DF_Outbox_Status] DEFAULT (0),
                    -- 0 = Pending, 1 = Processing, 2 = Completed, 3 = Failed (DLQ)
    [RetryCount]    INT              NOT NULL CONSTRAINT [DF_Outbox_Retry]  DEFAULT (0),
    [CreatedAt]     DATETIME2(3)     NOT NULL CONSTRAINT [DF_Outbox_Created] DEFAULT (SYSUTCDATETIME()),
    [NextRetryAt]   DATETIME2(3)     NULL,
    [LockedUntil]   DATETIME2(3)     NULL,     -- Lease timeout for crashed worker recovery
    [ProcessedAt]   DATETIME2(3)     NULL,
    [LastError]     NVARCHAR(2000)   NULL
);

-- Clustered index on monotonic IDENTITY prevents B-tree page fragmentation on high-rate INSERTs
CREATE UNIQUE CLUSTERED INDEX [CIX_OutboxMessages_SequenceNo]
    ON [dbo].[OutboxMessages] ([SequenceNo] ASC);

-- Filtered covering index keeps READPAST claim scans O(pending) even with millions of completed rows
CREATE NONCLUSTERED INDEX [IX_OutboxMessages_PendingPoll]
    ON [dbo].[OutboxMessages] ([Status], [NextRetryAt], [SequenceNo])
    INCLUDE ([Id], [AggregateId], [EventType], [RetryCount], [LockedUntil])
    WHERE [Status] IN (0, 1);

Note: Migrating to Cloud SQL for PostgreSQL? Use UUID for id, BIGSERIAL for sequence_no, JSONB for payload, and a partial index CREATE INDEX ix_outbox_pending ON outbox_messages (next_retry_at, sequence_no) WHERE status IN (0, 1);.

Next, on every Secondary or Tertiary relational database that receives asynchronous updates, create the dbo.ProcessedEvents idempotency guard table:

-- Run on EVERY TARGET Database (e.g., FulfillmentDb on Secondary Cloud SQL Instance)
CREATE TABLE [dbo].[ProcessedEvents] (
    [EventId]     UNIQUEIDENTIFIER NOT NULL,
    [EventType]   NVARCHAR(150)    NOT NULL,
    [Consumer]    NVARCHAR(100)    NOT NULL, -- Handler name; part of the key so >1 handler can share one target DB
    [ProcessedAt] DATETIME2(3)     NOT NULL CONSTRAINT [DF_ProcessedEvents_At] DEFAULT (SYSUTCDATETIME()),
    CONSTRAINT [PK_ProcessedEvents] PRIMARY KEY ([EventId], [Consumer])
);

CREATE NONCLUSTERED INDEX [IX_ProcessedEvents_ProcessedAt]
    ON [dbo].[ProcessedEvents] ([ProcessedAt] ASC);

Step 2: Refactor the primary write path to a single local transaction

Now replace TransactionScope in your command service with a local EF Core transaction on PrimaryDbContext.

When connecting to Cloud SQL in production, you should always enable EF Core connection resiliency (EnableRetryOnFailure()). Because EF Core’s retry strategy requires explicit user transactions to execute inside CreateExecutionStrategy().ExecuteAsync(...), wrap the atomic domain write and outbox insert together as follows:

using System.Diagnostics;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;

public sealed record OrderPlacedEvent(
    Guid OrderId,
    string CustomerId,
    string WarehouseCode,
    decimal TotalAmount,
    DateTime OccurredAtUtc);

public sealed class OrderService : IOrderService
{
    private readonly PrimaryDbContext _primaryDb;
    private readonly ILogger<OrderService> _logger;

    public OrderService(PrimaryDbContext primaryDb, ILogger<OrderService> logger)
    {
        _primaryDb = primaryDb;
        _logger = logger;
    }

    public async Task<Guid> PlaceOrderAsync(PlaceOrderRequest request, CancellationToken ct)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(request.CustomerId);
        ArgumentException.ThrowIfNullOrWhiteSpace(request.WarehouseCode);
        if (request.TotalAmount <= 0)
            throw new ArgumentOutOfRangeException(nameof(request.TotalAmount), "Order total must be positive.");

        var strategy = _primaryDb.Database.CreateExecutionStrategy();

        // Execute local ACID commit inside Cloud SQL transient-fault retry strategy
        return await strategy.ExecuteAsync(async () =>
        {
            // Start every attempt from a clean change tracker: if a previous attempt failed
            // transiently, its entities are still tracked as Added and would be inserted twice.
            _primaryDb.ChangeTracker.Clear();

            await using var localTx = await _primaryDb.Database.BeginTransactionAsync(ct);

            var utcNow = DateTime.UtcNow;
            var order = new Order
            {
                Id = Guid.NewGuid(),
                CustomerId = request.CustomerId.Trim(),
                TotalAmount = request.TotalAmount,
                Status = "CONFIRMED",
                CreatedAt = utcNow
            };

            var domainEvent = new OrderPlacedEvent(
                OrderId: order.Id,
                CustomerId: order.CustomerId,
                WarehouseCode: request.WarehouseCode.Trim(),
                TotalAmount: order.TotalAmount,
                OccurredAtUtc: utcNow);

            var outboxMessage = new OutboxMessage
            {
                Id = Guid.NewGuid(),
                AggregateType = "Order",
                AggregateId = order.Id.ToString(),
                EventType = "OrderPlacedEvent.v1",
                Payload = JsonSerializer.Serialize(domainEvent),
                // Capture W3C traceparent so async relay spans link to the original HTTP trace
                CorrelationId = Activity.Current?.Id,
                Status = OutboxStatus.Pending,
                CreatedAt = utcNow
            };

            _primaryDb.Orders.Add(order);
            _primaryDb.OutboxMessages.Add(outboxMessage);

            // Single local database round-trip commit (< 15ms); zero MSDTC escalation!
            await _primaryDb.SaveChangesAsync(ct);
            await localTx.CommitAsync(ct);

            _logger.LogInformation(
                "Committed Order {OrderId} with OutboxMessage {OutboxId} locally.",
                order.Id, outboxMessage.Id);

            return order.Id;
        });
    }
}

Notice what disappeared from the hot HTTP request path:

  • Zero connections to FulfillmentDb during the user’s request.
  • Zero blocking calls to external Billing REST APIs while holding database locks.
  • Zero TransactionScope MSDTC promotion.

Step 3: Build a pluggable Strategy Dispatcher for downstream handlers

To prevent your relay engine from turning into a giant switch statement as you migrate dozens of MSDTC workflows, decouple the relay loop from domain side-effects using the Strategy Pattern (IOutboxEventHandler). Supporting multiple handlers per EventType lets a single OrderPlacedEvent.v1 fan out cleanly to both a Secondary Database handler and an External Billing API handler:

public interface IOutboxEventHandler
{
    string SupportedEventType { get; }
    string ConsumerName { get; }
    Task HandleAsync(OutboxMessage message, CancellationToken ct);
}

Step 4: Implement idempotent target database and legacy stored procedure handlers

One of the biggest myths during Cloud SQL migrations is that adopting an event-driven outbox forces you to rewrite hundreds of battle-tested SQL Server stored procedures. You do not need to rewrite your target stored procedures. Simply invoke them inside a local transaction on the target database, guarded by dbo.ProcessedEvents:

using System.Text.Json;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;

public sealed class OrderFulfillmentSyncHandler : IOutboxEventHandler
{
    private readonly FulfillmentDbContext _fulfillmentDb;
    private readonly ILogger<OrderFulfillmentSyncHandler> _logger;

    public OrderFulfillmentSyncHandler(
        FulfillmentDbContext fulfillmentDb,
        ILogger<OrderFulfillmentSyncHandler> logger)
    {
        _fulfillmentDb = fulfillmentDb;
        _logger = logger;
    }

    public string SupportedEventType => "OrderPlacedEvent.v1";
    public string ConsumerName => nameof(OrderFulfillmentSyncHandler);

    public async Task HandleAsync(OutboxMessage message, CancellationToken ct)
    {
        var evt = JsonSerializer.Deserialize<OrderPlacedEvent>(message.Payload)
            ?? throw new InvalidOperationException($"Malformed payload for OutboxMessage {message.Id}.");

        var strategy = _fulfillmentDb.Database.CreateExecutionStrategy();

        await strategy.ExecuteAsync(async () =>
        {
            // The relay reuses this scoped DbContext for every message in a batch (and for every
            // retry attempt), so start each attempt from an empty change tracker.
            _fulfillmentDb.ChangeTracker.Clear();

            await using var targetTx = await _fulfillmentDb.Database.BeginTransactionAsync(ct);

            // 1. Fast idempotency check inside local target transaction
            bool alreadyApplied = await _fulfillmentDb.ProcessedEvents
                .AnyAsync(p => p.EventId == message.Id && p.Consumer == ConsumerName, ct);

            if (alreadyApplied)
            {
                _logger.LogInformation(
                    "OutboxMessage {OutboxId} already applied on FulfillmentDb; skipping duplicate.",
                    message.Id);
                return;
            }

            // 2. Execute existing legacy Stored Procedure with strict parameterization (prevents SQLi)
            await _fulfillmentDb.Database.ExecuteSqlInterpolatedAsync(
                $"EXEC dbo.sp_ProvisionFulfillmentOrder @OrderId={evt.OrderId}, @WarehouseCode={evt.WarehouseCode}",
                ct);

            // 3. Record EventId in ProcessedEvents inside the SAME local target transaction
            _fulfillmentDb.ProcessedEvents.Add(new ProcessedEvent
            {
                EventId = message.Id,
                EventType = message.EventType,
                Consumer = ConsumerName,
                ProcessedAt = DateTime.UtcNow
            });

            try
            {
                await _fulfillmentDb.SaveChangesAsync(ct);
                await targetTx.CommitAsync(ct);
            }
            catch (DbUpdateException ex) when (IsPrimaryKeyViolation(ex))
            {
                // Race-condition safety: Another concurrent replica committed the exact same EventId first
                await targetTx.RollbackAsync(ct);
                _fulfillmentDb.ChangeTracker.Clear();
                _logger.LogInformation(
                    "Concurrent duplicate detected via PK constraint for OutboxMessage {OutboxId}; treating as success.",
                    message.Id);
            }
        });
    }

    private static bool IsPrimaryKeyViolation(DbUpdateException ex) =>
        ex.InnerException is SqlException { Number: 2627 or 2601 };
}

Why is catching SqlException 2627 / 2601 (Primary Key violation) alongside AnyAsync so effective? Because even if two concurrent relay workers evaluate AnyAsync at the exact same microsecond under READ COMMITTED isolation, SQL Server’s PK_ProcessedEvents constraint guarantees only one transaction can commit—automatically rolling back the duplicate stored procedure execution on the losing connection!

Step 5: Harden external REST calls with Polly resilience and Idempotency-Key headers

For external HTTP/gRPC integrations (such as payment capture, ERP webhooks, or identity provisioning), database transactions cannot roll back an HTTP call once bytes leave your VPC. Instead, combine .NET’s Microsoft.Extensions.Http.Resilience (powered by Polly v8) with a deterministic Idempotency-Key HTTP header derived from OutboxMessage.Id:

using System.Net.Http.Json;
using System.Text.Json;

public sealed class OrderBillingWebhookHandler : IOutboxEventHandler
{
    private readonly HttpClient _httpClient;
    private readonly ILogger<OrderBillingWebhookHandler> _logger;

    public OrderBillingWebhookHandler(
        HttpClient httpClient,
        ILogger<OrderBillingWebhookHandler> logger)
    {
        _httpClient = httpClient;
        _logger = logger;
    }

    public string SupportedEventType => "OrderPlacedEvent.v1";
    public string ConsumerName => nameof(OrderBillingWebhookHandler);

    public async Task HandleAsync(OutboxMessage message, CancellationToken ct)
    {
        var evt = JsonSerializer.Deserialize<OrderPlacedEvent>(message.Payload)
            ?? throw new InvalidOperationException($"Malformed payload for OutboxMessage {message.Id}.");

        using var req = new HttpRequestMessage(HttpMethod.Post, "/v1/invoices/capture")
        {
            Content = JsonContent.Create(new
            {
                orderId = evt.OrderId,
                amount = evt.TotalAmount,
                occurredAtUtc = evt.OccurredAtUtc
            })
        };

        // Deterministic idempotency header ensures retries never double-charge the customer
        req.Headers.Add("Idempotency-Key", $"{ConsumerName}:{message.Id}");

        using var resp = await _httpClient.SendAsync(req, ct);
        resp.EnsureSuccessStatusCode();

        _logger.LogInformation(
            "Billing invoice captured for Order {OrderId} (OutboxMessage {OutboxId}).",
            evt.OrderId, message.Id);
    }
}

Register your HttpClient in Program.cs using standard resilience defaults (decorrelated jitter exponential backoff, circuit breaking, and per-attempt timeouts) and pull endpoint URLs/credentials from configuration or Secret Manager—never hardcoding secrets in source code:

// Program.cs: Register resilient external HTTP client and outbox strategy handlers
builder.Services
    .AddHttpClient<OrderBillingWebhookHandler>(client =>
    {
        var baseUrl = builder.Configuration["Integrations:BillingApiBaseUrl"]
            ?? throw new InvalidOperationException("Missing BillingApiBaseUrl configuration.");
        client.BaseAddress = new Uri(baseUrl);
    })
    .AddStandardResilienceHandler(options =>
    {
        options.Retry.MaxRetryAttempts = 3;
        options.Retry.UseJitter = true;
        options.Retry.BackoffType = Polly.DelayBackoffType.Exponential;
        options.CircuitBreaker.SamplingDuration = TimeSpan.FromSeconds(30);
    });

builder.Services.AddScoped<IOutboxEventHandler, OrderFulfillmentSyncHandler>();
// Resolve the typed client through its factory so the handler receives the configured HttpClient
// (BaseAddress + resilience pipeline); AddScoped<IOutboxEventHandler, OrderBillingWebhookHandler>() would bypass it.
builder.Services.AddScoped<IOutboxEventHandler>(sp => sp.GetRequiredService<OrderBillingWebhookHandler>());

Running the relay: Scheduled pull with Cloud Scheduler

A subtle pitfall in many tutorial implementations of the Outbox Pattern is running a BackgroundService (while (!stoppingToken.IsCancellationRequested)) inside the same ASP.NET Core web pods that serve user traffic. In production Kubernetes or serverless deployments, in-process polling threads cause three operational headaches:

  1. If you scale your web API to 20 replicas during peak traffic, 20 background loops hammer the OutboxMessages table simultaneously.
  2. Container scale-down events can terminate in-flight background threads mid-batch.
  3. Heavy JSON deserialization or downstream retries steal CPU and thread-pool capacity from latency-sensitive user APIs.

Instead, decouple the relay trigger externally: a managed scheduler invokes a dedicated, stateless relay worker that scales independently of your user-facing API.

Scheduled pull with UPDLOCK and READPAST

Scheduled pull is the fastest, lowest-overhead migration path for teams moving from on-premises Windows Server to Cloud SQL + Cloud Run or GKE. An external scheduler (Cloud Scheduler or a Kubernetes CronJob) invokes a dedicated, stateless relay worker endpoint on a fixed interval. Both fire at most once per minute, so each invocation keeps draining batches until the outbox is empty or a time budget runs out (see the controller below).

To allow multiple worker pods to claim batches concurrently without blocking each other—and without holding database transactions open while calling downstream servers—use an atomic UPDATE TOP (@BatchSize) ... WITH (UPDLOCK, ROWLOCK, READPAST) OUTPUT INSERTED.* lease query:

  • UPDLOCK and ROWLOCK: Acquires row-level update locks immediately during the index scan, preventing two pods from reading the same row and deadlocking on conversion to an exclusive lock.
  • READPAST: Instructs SQL Server to skip any row currently locked by another worker pod instead of blocking!
  • LockedUntil: Sets a lease expiration timestamp (e.g., UTC + 2 minutes). If a worker pod crashes mid-flight, stale Processing (1) rows automatically become eligible for reclaiming once their lease expires.

Here is the complete, concurrency-safe OutboxRelayService implementation:

using Microsoft.EntityFrameworkCore;

public sealed record RelayBatchSummary(int Claimed, int Succeeded, int Retried, int DeadLettered)
{
    public static RelayBatchSummary Empty { get; } = new(0, 0, 0, 0);

    public static RelayBatchSummary operator +(RelayBatchSummary a, RelayBatchSummary b) =>
        new(a.Claimed + b.Claimed, a.Succeeded + b.Succeeded, a.Retried + b.Retried, a.DeadLettered + b.DeadLettered);
}

public sealed class OutboxRelayService : IOutboxRelayService
{
    private const int MaxRetries = 5;
    private readonly PrimaryDbContext _primaryDb;
    private readonly ILookup<string, IOutboxEventHandler> _handlersByType;
    private readonly ILogger<OutboxRelayService> _logger;

    public OutboxRelayService(
        PrimaryDbContext primaryDb,
        IEnumerable<IOutboxEventHandler> handlers,
        ILogger<OutboxRelayService> logger)
    {
        _primaryDb = primaryDb;
        _handlersByType = handlers.ToLookup(h => h.SupportedEventType, StringComparer.OrdinalIgnoreCase);
        _logger = logger;
    }

    public async Task<RelayBatchSummary> ProcessBatchAsync(int batchSize = 50, CancellationToken ct = default)
    {
        var utcNow = DateTime.UtcNow;
        var leaseExpiry = utcNow.AddMinutes(2);

        // 1. Atomically claim up to @batchSize unlocked rows in a single round-trip.
        //    PostgreSQL equivalent: UPDATE outbox_messages SET status = 1 ... WHERE id IN (
        //      SELECT id FROM outbox_messages WHERE ... ORDER BY sequence_no LIMIT @batchSize FOR UPDATE SKIP LOCKED)
        //    RETURNING *;
        const string claimSql = """
            ;WITH ClaimCandidates AS (
                SELECT TOP ({0}) *
                FROM [dbo].[OutboxMessages] WITH (UPDLOCK, ROWLOCK, READPAST)
                WHERE (
                        [Status] = 0
                        AND ([NextRetryAt] IS NULL OR [NextRetryAt] <= {1})
                      )
                   OR (
                        [Status] = 1
                        AND [LockedUntil] < {1} -- Reclaim abandoned leases from crashed pods
                      )
                ORDER BY [SequenceNo] ASC
            )
            UPDATE ClaimCandidates
            SET [Status] = 1,
                [LockedUntil] = {2}
            OUTPUT
                INSERTED.[Id],
                INSERTED.[SequenceNo],
                INSERTED.[AggregateType],
                INSERTED.[AggregateId],
                INSERTED.[EventType],
                INSERTED.[Payload],
                INSERTED.[CorrelationId],
                INSERTED.[Status],
                INSERTED.[RetryCount],
                INSERTED.[CreatedAt],
                INSERTED.[NextRetryAt],
                INSERTED.[LockedUntil],
                INSERTED.[ProcessedAt],
                INSERTED.[LastError];
            """;

        var claimedBatch = await _primaryDb.OutboxMessages
            .FromSqlRaw(claimSql, batchSize, utcNow, leaseExpiry)
            .AsNoTracking()
            .ToListAsync(ct);

        if (claimedBatch.Count == 0)
            return RelayBatchSummary.Empty;

        // OUTPUT returns rows in no guaranteed order; restore SequenceNo order before dispatching.
        claimedBatch.Sort((a, b) => a.SequenceNo.CompareTo(b.SequenceNo));

        int succeeded = 0, retried = 0, deadLettered = 0;

        // 2. Execute downstream handlers OUTSIDE any Primary DB transaction!
        foreach (var message in claimedBatch)
        {
            var matchingHandlers = _handlersByType[message.EventType].ToList();
            if (matchingHandlers.Count == 0)
            {
                await MarkDeadLetterAsync(message.Id, $"No IOutboxEventHandler registered for '{message.EventType}'.", ct);
                deadLettered++;
                continue;
            }

            try
            {
                foreach (var handler in matchingHandlers)
                {
                    await handler.HandleAsync(message, ct);
                }

                await MarkCompletedAsync(message.Id, ct);
                succeeded++;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error relaying OutboxMessage {OutboxId} (Attempt {Attempt}).",
                    message.Id, message.RetryCount + 1);

                bool movedToDlq = await ScheduleRetryOrDeadLetterAsync(message, ex.Message, ct);
                if (movedToDlq) deadLettered++;
                else retried++;
            }
        }

        return new RelayBatchSummary(claimedBatch.Count, succeeded, retried, deadLettered);
    }

    private Task MarkCompletedAsync(Guid id, CancellationToken ct) =>
        _primaryDb.OutboxMessages
            .Where(m => m.Id == id)
            .ExecuteUpdateAsync(s => s
                .SetProperty(m => m.Status, OutboxStatus.Completed)
                .SetProperty(m => m.ProcessedAt, DateTime.UtcNow)
                .SetProperty(m => m.LockedUntil, (DateTime?)null)
                .SetProperty(m => m.LastError, (string?)null), ct);

    private async Task<bool> ScheduleRetryOrDeadLetterAsync(OutboxMessage msg, string error, CancellationToken ct)
    {
        int nextAttempt = msg.RetryCount + 1;
        string truncatedError = error.Length > 1900 ? error[..1900] : error;

        if (nextAttempt >= MaxRetries)
        {
            await MarkDeadLetterAsync(msg.Id, truncatedError, ct);
            return true;
        }

        // Exponential backoff: 2^attempt seconds (2s, 4s, 8s, 16s...)
        var nextRetryUtc = DateTime.UtcNow.AddSeconds(Math.Pow(2, nextAttempt));

        await _primaryDb.OutboxMessages
            .Where(m => m.Id == msg.Id)
            .ExecuteUpdateAsync(s => s
                .SetProperty(m => m.Status, OutboxStatus.Pending)
                .SetProperty(m => m.RetryCount, nextAttempt)
                .SetProperty(m => m.NextRetryAt, nextRetryUtc)
                .SetProperty(m => m.LockedUntil, (DateTime?)null)
                .SetProperty(m => m.LastError, truncatedError), ct);

        return false;
    }

    private Task MarkDeadLetterAsync(Guid id, string reason, CancellationToken ct) =>
        _primaryDb.OutboxMessages
            .Where(m => m.Id == id)
            .ExecuteUpdateAsync(s => s
                .SetProperty(m => m.Status, OutboxStatus.Failed)
                .SetProperty(m => m.LockedUntil, (DateTime?)null)
                .SetProperty(m => m.LastError, reason), ct);
}

Expose the worker trigger endpoint on an internal Cloud Run service restricted by Google Cloud OIDC Bearer Token authentication and IAM (roles/run.invoker) so only your Cloud Scheduler service account can invoke it:

using System.Diagnostics;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("internal/outbox")]
[Authorize(Policy = "CloudSchedulerOidc")] // Enforces signed Google OIDC JWT verification
public sealed class OutboxRelayController : ControllerBase
{
    private readonly IOutboxRelayService _relayService;

    public OutboxRelayController(IOutboxRelayService relayService) =>
        _relayService = relayService;

    [HttpPost("process")]
    public async Task<ActionResult<RelayBatchSummary>> ProcessAsync(
        [FromQuery] int batchSize = 50,
        [FromQuery] int maxDurationSeconds = 45,
        CancellationToken ct = default)
    {
        int clampedBatch = Math.Clamp(batchSize, 1, 250);

        // Cloud Scheduler fires at most once per minute, so keep draining while batches come back
        // full, within a time budget that stays below the job's attempt deadline and the Cloud Run
        // request timeout.
        var budget = TimeSpan.FromSeconds(Math.Clamp(maxDurationSeconds, 1, 300));
        var stopwatch = Stopwatch.StartNew();

        var total = RelayBatchSummary.Empty;
        RelayBatchSummary batch;
        do
        {
            batch = await _relayService.ProcessBatchAsync(clampedBatch, ct);
            total += batch;
        }
        while (batch.Claimed == clampedBatch && stopwatch.Elapsed < budget);

        return Ok(total);
    }
}

Finally, create the Cloud Scheduler job. Its OIDC token audience is the relay’s Cloud Run URL, and only its service account is allowed to invoke the service:

gcloud run services add-iam-policy-binding outbox-relay --region=REGION \
  --member="serviceAccount:outbox-scheduler@PROJECT_ID.iam.gserviceaccount.com" \
  --role="roles/run.invoker"

gcloud scheduler jobs create http outbox-relay-tick --location=REGION \
  --schedule="* * * * *" \
  --uri="https://RELAY_URL/internal/outbox/process?batchSize=50&maxDurationSeconds=45" \
  --http-method=POST \
  --oidc-service-account-email="outbox-scheduler@PROJECT_ID.iam.gserviceaccount.com" \
  --oidc-token-audience="https://RELAY_URL" \
  --attempt-deadline=90s

Under sustained load, each run keeps draining for up to its time budget. When the outbox is idle, a new event waits at most one scheduler tick (about a minute) before it propagates.


Production hardening: Retries, poison messages, and observability

Moving from synchronous distributed transactions to asynchronous eventual consistency shifts failure handling from immediate user-visible HTTP 500s to background operational resilience. Ensure these four production guardrails are in place before cutover.

1. Poison messages and Dead-Letter Queue (DLQ) isolation

A malformed payload or permanent business constraint violation (a poison message) must never block subsequent valid events in your outbox. As shown in Figure 4 and OutboxRelayService above:

  • Cap transient retries (MaxRetries = 5) with exponential NextRetryAt delays.
  • Transition exhausted messages to Status = 3 (Failed / DLQ) with the truncated exception diagnostic stored in LastError.
  • Provide an authenticated SRE replay command that resets Status = 0, RetryCount = 0, NextRetryAt = NULL once the downstream schema bug or third-party outage is resolved. Thanks to dbo.ProcessedEvents, replaying an event that partially succeeded on Database B before failing on API C will cleanly skip Database B and only execute API C!

2. Distributed tracing propagation across the outbox boundary

When a request crosses an asynchronous database table, default APM traces split into two disconnected traces. Storing Activity.Current?.Id (W3C traceparent) in OutboxMessages.CorrelationId during Phase 1 allows the Phase 2 relay worker to restore parent context before invoking handlers:

using System.Diagnostics;

private static readonly ActivitySource OutboxActivitySource = new("Enterprise.Outbox.Relay");

// Inside OutboxRelayService before calling handler.HandleAsync(...)
ActivityContext.TryParse(message.CorrelationId, traceState: null, isRemote: true, out var parentContext);
using var activity = OutboxActivitySource.StartActivity(
    $"OutboxRelay {message.EventType}",
    ActivityKind.Consumer,
    parentContext);

activity?.SetTag("messaging.message.id", message.Id.ToString());
activity?.SetTag("messaging.destination.name", message.EventType);

With Cloud Trace and OpenTelemetry, engineers see a single end-to-end waterfall spanning the synchronous API commit, queue dwell time, secondary stored procedure latency, and external HTTP call.

3. Outbox archival and table-bloat prevention

Never allow dbo.OutboxMessages or dbo.ProcessedEvents to grow unbounded. Schedule a nightly off-peak maintenance job that purges completed outbox records (Status = 2) older than 7 days and ProcessedEvents keys older than 30 days in small lock-escalation-safe batches (< 5,000 rows per transaction so SQL Server never escalates row locks to a full table lock):

-- Batched cleanup stored procedure (prevents >5,000 row lock escalation in SQL Server)
CREATE OR ALTER PROCEDURE [dbo].[sp_PurgeCompletedOutboxMessages]
    @RetentionDays INT = 7,
    @BatchSize     INT = 4000
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @CutoffUtc DATETIME2(3) = DATEADD(DAY, -@RetentionDays, SYSUTCDATETIME());
    DECLARE @DeletedRows INT = 1;

    WHILE (@DeletedRows > 0)
    BEGIN
        DELETE TOP (@BatchSize)
        FROM [dbo].[OutboxMessages] WITH (ROWLOCK, READPAST)
        WHERE [Status] = 2 -- Completed
          AND [ProcessedAt] < @CutoffUtc;

        SET @DeletedRows = @@ROWCOUNT;
        IF (@DeletedRows > 0) WAITFOR DELAY '00:00:00.100'; -- Yield I/O briefly between batches
    END
END;

4. Essential SLO metrics to export to Cloud Monitoring

Instrument and alert on three golden outbox signals in Google Cloud Monitoring:

  • Outbox Lag (oldest_pending_age_seconds): DATEDIFF(SECOND, MIN(CreatedAt), SYSUTCDATETIME()) WHERE Status = 0. Alert if lag exceeds 3x your normal relay cadence.
  • Dead-Letter Count (outbox_dlq_total): COUNT(*) WHERE Status = 3. Any non-zero increment should trigger an actionable alert for engineering triage.
  • Idempotency Deduplication Rate (idempotent_skips_total): Tracks how frequently duplicate deliveries are caught by ProcessedEvents. A sudden spike signals worker lease timeouts (LockedUntil too short for your batch size) or relay workers crashing mid-batch.

Build vs. adopt: Evaluating existing .NET Outbox frameworks

Building a lightweight, table-backed outbox (~250 lines of C# as shown above) gives enterprise teams complete control over legacy stored procedures, custom schemas, and zero third-party broker lock-in during a phased Cloud SQL migration. However, if your application already standardizes on a messaging bus, evaluate battle-tested open-source frameworks with native Transactional Outbox modules:

  • MassTransit Transactional Outbox (GitHub): Integrates directly with EF Core (AddEntityFrameworkOutbox<PrimaryDbContext>) and supports both Bus Outbox and Consumer Inbox/Outbox deduplication across RabbitMQ, Kafka, Azure Service Bus, and Google Cloud Pub/Sub.
  • CAP (dotnetcore/CAP): Lightweight CNCF-landscape open-source .NET library purpose-built for distributed transactions and event-bus outbox persistence across SQL Server, PostgreSQL, MySQL, Kafka, and RabbitMQ, complete with a built-in operational dashboard.
  • NServiceBus Outbox: Commercial enterprise messaging platform offering deterministic message deduplication and transactional outbox guarantees without MSDTC.

Migration checklist and next steps

Use this phased checklist to retire MSDTC safely across your portfolio without disrupting production SLAs:

  1. Inventory distributed transactions: Scan repositories for TransactionScope, XA data sources, and cross-instance Linked Servers, and confirm active distributed UOWs via sys.dm_tran_session_transactions.
  2. Classify consistency boundaries: Separate same-instance cross-database queries (which require no changes on Cloud SQL) from cross-instance / cross-API writes (candidates for Outbox or Saga).
  3. Deploy schemas non-disruptively: Add dbo.OutboxMessages to primary databases and dbo.ProcessedEvents to target databases ahead of cutover.
  4. Refactor one vertical slice behind a feature flag: Convert your highest-contention MSDTC endpoint to Phase 1 local ACID commit + Cloud Scheduler relay while preserving existing target stored procedures.
  5. Verify fault-injection resilience: Test downstream DB downtime, duplicate event replay, and external HTTP 503 timeouts in staging to validate zero data loss and zero duplicate side-effects.
  6. Cut over to Cloud SQL: With OS-level MSDTC dependencies eliminated, migrate your databases cleanly using Google Cloud Database Migration Service (DMS) or native backup/restore onto managed Cloud SQL.

Further reading and reference links

2 Likes