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

πŸ“š Interview question

Where do you draw transaction boundaries when a business operation spans several modules or services? Explain why you keep local transactions small, when you use a saga or eventual consistency instead, and how you design what the user sees while the operation is still in progress.

Transaction boundaries across modules and services: one aggregate or module per local transaction, sagas and process managers, compensation, eventual consistency and the UX of pending states.

Senior Theory Advanced architecture eventual-consistency outbox saga transaction-boundaries ux

🎯 Key points

  • A local ACID transaction should cover one aggregate in one module's data; keep it short
  • Cross-module or cross-service operations use eventual consistency: outbox, events, sagas
  • Distributed transactions (2PC/MSDTC) are fragile and largely unavailable across cloud PaaS services
  • Saga = sequence of local transactions with compensating actions; orchestration vs choreography
  • Compensation is a business action defined with the business (refund, release stock, store credit, manual review), not a rollback, and must be idempotent
  • Model in-progress states explicitly (Pending, Confirmed, Failed); use them as semantic locks so other operations can't act on pending data
  • Push state to users: a CQRS read model updated by saga events, surfaced via SignalR or polling
  • Decide per invariant: must it be true immediately (same aggregate) or eventually (across boundaries)?

⏱ 30-second answer

I draw the local transaction around one aggregate in one module's data and keep it short. If a business operation spans modules or services, I don't stretch the transaction; I make it a sequence of local transactions connected by events through an outbox, coordinated by a saga when steps can fail and need compensation. Compensations are business decisions (refund, release stock, offer store credit, send to manual review), agreed with the business.

The key design question is per invariant: does it have to be true immediately (put it inside one aggregate) or is eventually acceptable (across boundaries)?

Because the operation isn't atomic, I model explicit states like Pending, Confirmed and Failed, keep them in a read model the saga updates (the query side of CQRS), and push changes to the UI with SignalR or polling rather than pretending it's done.

The trade-off: you gain availability and independent scaling, but you must design for intermediate states and compensations.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"My rule is one local transaction per aggregate, inside the module or service that owns it. A database transaction is the cheapest consistency tool we have, but it only works inside one database and it holds locks, so I keep it short and scoped to the data that must change together to protect an invariant. When an operation like 'place order' needs Ordering, Payments and Inventory, I don't try to wrap all three in one transaction. Distributed transactions with two-phase commit are fragile, slow under contention, and mostly not available across Azure PaaS services anyway.

Instead the order is saved as Pending in a local transaction together with an outbox message. Payments and Inventory react, each with its own local transaction, and an orchestrating saga moves the order to Confirmed or runs compensations: refund the payment if stock can't be reserved. For example, at [company] our checkout used one big TransactionScope across [two] databases. Under load it escalated to MSDTC, held locks for seconds, and at peak we saw [deadlocks and timeouts on 3%] of orders. We moved to a saga with explicit states and an outbox, and the order page showed 'We're confirming your order' with a live update. Checkout errors dropped to [0.2%], and the confirmation typically arrived in under [two] seconds.

The mistake I see is designing as if everything is atomic and then hiding the gaps, so users see a 'success' that later silently fails. My senior line is: decide which invariants must hold immediately and put them inside one aggregate; everything else is eventual, and the user should be able to see where it is."


Choosing the consistency mechanism

Scope Mechanism Consistency Notes
One aggregate Local DB transaction (SaveChanges) Immediate Default
Several aggregates, same module, same DB Local transaction possible, but prefer domain events and separate transactions Immediate or eventual Large transactions hurt concurrency
Across modules in one monolith Events through an in-process outbox, or one transaction only as a deliberate exception Eventual (preferred) Keeps extraction possible
Across services Outbox + events, saga Eventual No shared transaction
Distributed transaction (2PC) MSDTC / XA Immediate Avoid: fragile, blocking, limited cloud support

Orchestration vs choreography

Orchestration Choreography
Control Central saga/process manager sends commands Services react to each other's events
Visibility State in one place, easy to query Spread across services
Coupling Orchestrator knows participants Participants know events
Fits 3+ steps, compensations, timeouts 2-3 simple steps

What users see

State UI
Pending "We're confirming your order" with progress, no second submit
Confirmed Confirmation + email
Failed / compensated Clear message, money refunded, next step

Production example

Replacing a cross-database TransactionScope with a saga, outbox and explicit order states cut checkout errors from [3%] to [0.2%] at peak and removed MSDTC from the platform, with a median confirmation time of [1.4 s].

πŸ” What the interviewer is checking

Checks whether the candidate scopes transactions correctly, knows why distributed transactions are avoided, and can design sagas, compensation and user-visible states.

Green flags

  • One aggregate per local transaction, short transactions
  • Outbox + saga with compensations and timeouts
  • Classifies invariants as immediate vs eventual with the business
  • Designs pending/failed states in the UI

Red flags

  • Proposes 2PC or TransactionScope across services
  • Treats compensation as a rollback
  • Hides intermediate states from users

πŸ“š Learn in depth

1. What a transaction buys and costs

An ACID transaction gives atomicity and isolation within one resource manager (one database). The cost is locks (or row versions) held for its duration, so longer transactions mean more blocking and deadlocks. Spanning two resources needs a coordinator and two-phase commit: prepare, then commit. If the coordinator fails between phases, participants hold locks until it recovers (in-doubt transactions).

2PC                                     Saga
Coordinator ──prepare──► DB1, DB2        Order(Pending) ──evt──► Payment(Taken) ──evt──► Stock(Reserved)
           ◄──ready────                         β–²                                            β”‚
           ──commit───►                         └── Order(Confirmed) ◄──────────evtβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
locks held across the network           failure: Stock(Failed) ──► Payment(Refunded) ──► Order(Cancelled)

TransactionScope in .NET escalates to a distributed transaction when a second connection or resource enlists. .NET 7+ supports distributed transactions on Windows only, and Azure SQL Database supports elastic transactions only between Azure SQL databases, not with Service Bus or other services.

2. Aggregates define the immediate boundary

In DDD, the aggregate is the consistency boundary: invariants inside it hold at the end of every transaction. Rules that span aggregates ("a customer's total open orders under their credit limit") are either redesigned (move the rule into one aggregate), checked with a reservation, or accepted as eventually consistent with a compensating action.

3. Making the steps reliable

Each saga step is a local transaction plus a message. The outbox makes "save and publish" atomic; the inbox (processed message ids) makes handling idempotent. Without them you get lost or duplicated steps.

4. Compensation is business logic

You can't roll back an email that was sent or a payment that settled. Compensations are new business actions: refund, release, send a correction. They must be idempotent and can themselves fail, so the saga needs retries, timeouts and an escalation path (a human task queue).

5. Isolation anomalies in sagas

Sagas lack isolation: other operations can see intermediate state. Countermeasures:

  • Semantic locks: a Pending state that other operations respect.
  • Commutative updates: increments rather than overwrites.
  • Reread values / version checks before committing a step.
  • Pivot transaction: order steps so that the step after which you can't compensate comes last among the risky ones.

6. Designing the UX

Eventual consistency is a product decision. Options: optimistic UI with a pending marker, a status page with live updates (SignalR or polling), an email on completion. Set expectations with numbers from production (p95 time to confirm).

Try it yourself

  1. Write a TransactionScope over two SQL connections and watch it escalate (on Windows) or throw (on Linux).
  2. Model an order saga with states and compensations as a state machine on paper.
  3. Implement an outbox table and a relay; kill the process between save and publish and confirm nothing is lost.
  4. Add an inbox to a consumer and replay the same message twice.
  5. Measure p50/p95 time from OrderPlaced to OrderConfirmed with distributed tracing in Application Insights.

πŸ’» Code

A minimal orchestrated saga state kept by Ordering. Each handler runs in its own local transaction with the outbox.

namespace Ordering.Domain;

public enum OrderStatus { Pending, PaymentTaken, Confirmed, Cancelled }

public sealed class Order
{
    public Guid Id { get; private init; }
    public OrderStatus Status { get; private set; } = OrderStatus.Pending;
    public string? FailureReason { get; private set; }

    public static Order Place(Guid id) => new() { Id = id };

    public void MarkPaymentTaken()
    {
        if (Status != OrderStatus.Pending) return;       // idempotent: ignore duplicates
        Status = OrderStatus.PaymentTaken;
    }

    public void Confirm()
    {
        if (Status != OrderStatus.PaymentTaken) return;
        Status = OrderStatus.Confirmed;
    }

    public bool Cancel(string reason)
    {
        if (Status is OrderStatus.Confirmed or OrderStatus.Cancelled) return false;
        var needsRefund = Status == OrderStatus.PaymentTaken;
        Status = OrderStatus.Cancelled;
        FailureReason = reason;
        return needsRefund;                                // caller sends RefundPayment if true
    }
}
namespace Ordering.Application;

using Ordering.Domain;

public sealed record StockReservationFailed(Guid OrderId, string Reason);
public sealed record RefundPayment(Guid OrderId);

public interface IOrderRepository { Task<Order> GetAsync(Guid id, CancellationToken ct); }
public interface IOutbox { void Enqueue(object message); }
public interface IUnitOfWork { Task SaveChangesAsync(CancellationToken ct); }

// One local transaction: update the order and enqueue the compensation together.
public sealed class StockReservationFailedHandler(IOrderRepository orders, IOutbox outbox, IUnitOfWork uow)
{
    public async Task HandleAsync(StockReservationFailed e, CancellationToken ct)
    {
        var order = await orders.GetAsync(e.OrderId, ct);
        if (order.Cancel(e.Reason))
            outbox.Enqueue(new RefundPayment(order.Id));
        await uow.SaveChangesAsync(ct);
    }
}

⚠ Common mistakes

  • Mistake: Wrapping calls to several services or databases in one TransactionScope. Why it is wrong: It escalates to a distributed transaction that is fragile, blocks on locks and is unsupported for most cloud services. Instead: Use local transactions plus an outbox and a saga.
  • Mistake: Making transactions as large as possible "for safety". Why it is wrong: Long transactions hold locks and cause blocking and deadlocks. Instead: Scope a transaction to one aggregate's invariants.
  • Mistake: Treating compensation as a rollback. Why it is wrong: Side effects such as payments and emails can't be undone. Instead: Design explicit, idempotent business compensations and an escalation path.
  • Mistake: Showing "success" before the saga finishes. Why it is wrong: Users act on something that may later fail, causing support load and distrust. Instead: Show a pending state and notify on completion.
  • Mistake: Publishing events outside the local transaction. Why it is wrong: Crashes lose or duplicate saga steps. Instead: Outbox for publishing, inbox or idempotent handlers for consuming.
  • Mistake: Ignoring saga isolation anomalies. Why it is wrong: Concurrent operations act on intermediate state, e.g. shipping a pending order. Instead: Use semantic locks (states), version checks and careful step ordering.
  • Mistake: No timeouts in the saga. Why it is wrong: A lost reply leaves orders pending forever. Instead: Schedule timeout messages and alert on sagas stuck past their SLA.

πŸ› Senior insight: trade-offs

The real work is classifying invariants with the business. I ask: "If these two things are inconsistent for ten seconds, what's the cost?" Usually the answer is "nothing, if the user can see it's in progress". Only the invariants with a real cost of temporary inconsistency go inside one aggregate and one transaction. That conversation also surfaces the compensations the business already performs manually today.

Inside a modular monolith I'll occasionally accept one database transaction across two modules as a deliberate, documented exception, but I know it blocks future extraction, so it goes in an ADR.

Option When it fits Cost When not to
Single local transaction Invariant within one aggregate Low Data owned by different modules/services
Choreographed events 2-3 simple steps, no complex compensation Low-medium; hard to see flow Many steps, timeouts, compensations
Orchestrated saga Multi-step with compensations and timeouts Medium; orchestrator to maintain Trivial flows
Distributed transaction Legacy on-prem, same-vendor resources High fragility Cloud PaaS, high throughput

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions an orchestrated saga with outbox and inbox Why: Checks they can walk the failure points of a real saga
    How to answer

    Each service changes its own data and writes outgoing messages in one transaction (outbox), and dedups incoming messages (inbox). A saga orchestrator persists the order's progress: on OrderPlaced it sends ReserveStock; on StockReserved it sends CapturePayment; on PaymentCaptured it completes. If payment fails it sends the compensation ReleaseStock.

    At every step a crash either committed nothing (the message is redelivered) or committed everything (the outbox resends). Duplicates hit the inbox. Missing replies trigger scheduled timeouts, and late replies after a timeout get their own handling, such as refunding a late capture. Poison messages dead-letter with alerts.

    The trade-off: reliability without distributed transactions, paid for with eventual consistency, more states and more operational tooling.

  2. When: Candidate says the aggregate is the consistency boundary Why: Checks their understanding of aggregate design and invariants
    How to answer

    An aggregate is a cluster of entities and value objects that must stay consistent together, with one entity as the aggregate root. Outside code talks only to the root, so the root can enforce the invariants: rules that must be true whenever the transaction commits (an order's total equals its lines; a booking never exceeds capacity).

    Keep aggregates small: draw the boundary around real invariants, not around every relationship. Reference other aggregates by id (CustomerId), not by object, so loading an order does not drag in the customer. Change one aggregate per transaction; when another aggregate must react, publish a domain event and update it in a separate transaction. The trade-off is eventual consistency between aggregates in exchange for low contention and clear ownership.

  3. When: Candidate distinguishes in-process and cross-service events Why: Checks domain vs integration events and dispatch timing
    How to answer

    A domain event records something meaningful that happened inside one bounded context, such as OrderPlaced. It is raised by an aggregate, handled in-process by other parts of the same model, and uses domain types freely. An integration event is a published contract for other services or modules: serialised, versioned and owned by the publisher.

    • Domain events are dispatched inside the unit of work (just before or as part of SaveChanges), so their side effects commit or roll back together.
    • Integration events must only leave after the commit. You write them to an outbox table in the same transaction, and a relay publishes them to Azure Service Bus.

    The trade-off: domain events give you strong consistency in one context; integration events give you decoupling at the cost of eventual consistency and at-least-once delivery.

πŸ›  Real-world problems: how you handle them

Checkout TransactionScope escalating to MSDTC under load
Situation
An [online retailer's] checkout wrote to an Orders database and a Payments database inside one `TransactionScope`, running on Windows VMs, at around [80] orders a minute at peak.
Signals
At sales peaks, [3%] of checkouts failed with timeouts and deadlock errors (1205), in-doubt transactions appeared after a VM restart, and p95 checkout latency was over [4 s].
Investigation
I captured deadlock graphs from the `system_health` Extended Events session, traced checkout in Application Insights to see lock waits, confirmed MSDTC escalation in the event logs, and mapped which invariants actually needed atomicity.
Resolution
Immediate: reduced the transaction scope and added retries for deadlock victims. Long-term: an ADR moving to an orchestrated saga: order saved as `Pending` with an outbox message, Payments and Inventory handling commands in local transactions, compensations for refunds, and an order status page updated through SignalR.
Prevention
An analyser rule and code review checklist banning `TransactionScope` across connections, saga timeouts with alerts on orders pending more than [5 minutes], and dashboards for saga completion time.

How to tell it (STAR)

**S:** At [company] checkout used one `TransactionScope` over two databases, and at peak [3%] of orders failed with deadlocks and timeouts. **T:** I owned the fix and needed agreement from the payments team. **A:** I used deadlock graphs and Application Insights traces to show the distributed transaction was the cause, ran a workshop to sort invariants into immediate and eventual, and wrote an ADR for a saga with an outbox and explicit order states. I worked with UX on a 'confirming your order' screen. **R:** Checkout errors fell from [3%] to [0.2%], MSDTC was removed, and median confirmation time was [1.4 s].

More in Senior-Level Architecture

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me