Modern applications rarely perform all their database operations in one place. A single business operation may involve multiple application services, repositories, and database tables.

Consider an order processing system. When a customer places an order, the application may need to:

  • Create an order record.
  • Save order items.
  • Reduce product inventory.
  • Create a payment record.
  • Update the customer's account information.
  • Record an order history entry.

Each operation may belong to a different service or repository. Although separating responsibilities makes the application easier to maintain, it introduces a challenge: how do we ensure that related database changes remain consistent without keeping a transaction open for too long?

A common mistake is to begin a database transaction at the beginning of a service method and keep it open until every operation finishes.

This can create long-running transactions, database locks, connection usage, blocking, and reduced application throughput.

Entity Framework Core provides transaction management through Database.BeginTransactionAsync(), but developers must carefully decide which operations belong inside the transaction.

The goal is to keep the transaction focused on the database changes that must succeed or fail together.

Why Long-Running Transactions Become a Problem

A database transaction provides atomicity. If a group of database operations succeeds, the transaction commits. If an operation fails, the transaction can be rolled back.

However, a transaction also holds database resources while it remains open.

Consider this simplified order processing flow:

SQL
Place Order
    |
    |-- Validate Customer
    |
    |-- Check Product Availability
    |
    |-- Call Payment Service
    |
    |-- Save Order
    |
    |-- Update Inventory
    |
    |-- Send Notification
    |
    |-- Commit Transaction

Suppose the payment service takes four seconds to respond and the notification service takes another two seconds.

If the transaction remains open during these operations, database resources stay occupied even though the application is waiting for external services.

This can lead to:

  • Locks being held longer than necessary.
  • Increased blocking between database operations.
  • Higher connection usage.
  • Greater chances of transaction timeouts.
  • Reduced throughput under concurrent workloads.
  • More complicated recovery when an external service fails.

The important distinction is that not every operation in a business workflow needs to be part of the same database transaction.

Database consistency should be protected without unnecessarily including network calls, user interactions, or unrelated processing.

Understand EF Core's Default Transaction Behavior

Developers sometimes introduce explicit transactions without realizing that EF Core already manages transactions for many operations.

By default, when a relational database provider supports transactions, a single SaveChanges() or SaveChangesAsync() call is transactional.

For example:

C#
public async Task CreateOrderAsync(Order order)
{
    _context.Orders.Add(order);

    await _context.SaveChangesAsync();
}

If saving the changes requires multiple SQL commands and one command fails, EF Core rolls back the transaction so that the changes are not partially applied.

This means a simple operation that performs one SaveChangesAsync() usually does not require an additional manually created transaction.

Explicit transactions become useful when multiple database operations must succeed or fail together across multiple SaveChangesAsync() calls.

For example:

C#
await using var transaction =
    await _context.Database.BeginTransactionAsync();

try
{
    _context.Orders.Add(order);

    await _context.SaveChangesAsync();

    _context.Inventory
        .Where(i => i.ProductId == productId)
        .ExecuteUpdate();

    await transaction.CommitAsync();
}
catch
{
    await transaction.RollbackAsync();
    throw;
}

This example illustrates the transaction boundary, but production code should use a valid inventory update with appropriate quantity checks and concurrency protection.

The important point is that both database operations belong to one transaction because the application requires them to remain consistent.

Keep External Service Calls Outside Database Transactions

One of the most effective ways to reduce transaction duration is to avoid calling external services while a database transaction is open.

Consider the following implementation:

C#
public async Task PlaceOrderAsync(Order order)
{
    await using var transaction =
        await _context.Database.BeginTransactionAsync();

    try
    {
        _context.Orders.Add(order);

        await _context.SaveChangesAsync();

        await _paymentService.ProcessPaymentAsync(order);

        await _notificationService.SendOrderConfirmationAsync(order);

        await transaction.CommitAsync();
    }
    catch
    {
        await transaction.RollbackAsync();
        throw;
    }
}

There are several problems with this approach.

First, the payment service may take several seconds to respond. Second, the notification service may become unavailable. Third, if payment succeeds but the database transaction later rolls back, the payment and database can disagree.

A better approach is to separate the database operation from external communication.

For example, save the order and an event record in one short transaction:

C#
public async Task CreateOrderAsync(Order order)
{
    await using var transaction =
        await _context.Database.BeginTransactionAsync();

    try
    {
        _context.Orders.Add(order);

        _context.OutboxMessages.Add(new OutboxMessage
        {
            Id = Guid.NewGuid(),
            EventType = "OrderCreated",
            Payload = JsonSerializer.Serialize(order),
            CreatedAt = DateTime.UtcNow
        });

        await _context.SaveChangesAsync();

        await transaction.CommitAsync();
    }
    catch
    {
        await transaction.RollbackAsync();
        throw;
    }
}

The transaction now protects two related database changes:

  • The order record.
  • The event that needs to be processed later.

A background worker can read the outbox message and call the payment or notification service outside the original transaction.

This pattern is known as the transactional outbox pattern.

It helps prevent a situation where the application saves an order but loses the corresponding event because the process crashes before sending it.

The background worker should implement retries, message status tracking, and idempotent processing because an event may be delivered more than once.

For payment workflows, the application should also define when an order becomes confirmed. Creating an order and completing payment are separate business states and should not be treated as the same operation.

Coordinate Multiple Application Services Through an Orchestrator

In a layered application, multiple services may need to participate in one database transaction.

For example:

Code
OrderApplicationService
    |
    |-- OrderRepository
    |
    |-- InventoryService
    |
    |-- PaymentRecordService
    |
    |-- OrderHistoryService

A common mistake is allowing every service to create and commit its own transaction.

If each service commits independently, a failure in a later operation can leave earlier database changes permanently saved.

For example, the order might be created successfully, inventory might be reduced, and then payment record creation might fail.

The application now contains partially completed business data.

A better design places transaction ownership in the application service or another clearly defined unit-of-work coordinator.

The lower-level services perform database operations but do not independently commit the overall business transaction.

For example:

C#
public class OrderApplicationService
{
    private readonly AppDbContext _context;
    private readonly InventoryService _inventoryService;
    private readonly OrderHistoryService _historyService;

    public OrderApplicationService(
        AppDbContext context,
        InventoryService inventoryService,
        OrderHistoryService historyService)
    {
        _context = context;
        _inventoryService = inventoryService;
        _historyService = historyService;
    }

    public async Task CreateOrderAsync(
        Order order,
        CancellationToken cancellationToken)
    {
        await using var transaction =
            await _context.Database.BeginTransactionAsync(
                cancellationToken);

        try
        {
            _context.Orders.Add(order);

            await _context.SaveChangesAsync(cancellationToken);

            await _inventoryService.ReduceStockAsync(
                order.Items,
                cancellationToken);

            await _historyService.RecordOrderAsync(
                order.Id,
                cancellationToken);

            await transaction.CommitAsync(cancellationToken);
        }
        catch
        {
            await transaction.RollbackAsync(cancellationToken);
            throw;
        }
    }
}

This approach assumes that the inventory and history services use the same DbContext instance and database transaction.

If they use separate contexts or different databases, the transaction coordination must be designed differently.

Also, ReduceStockAsync() should use conditional database updates or concurrency controls to prevent inventory from becoming negative when multiple orders are processed simultaneously.

The main architectural principle is simple: transaction ownership should be clear, and participating services should not commit independently.

Share a Database Transaction Across Multiple DbContext Instances Carefully

Some applications use multiple DbContext classes for different database areas.

For example:

  • OrderDbContext manages orders.
  • InventoryDbContext manages stock.
  • AuditDbContext manages audit records.

If all contexts connect to the same relational database, they can participate in the same transaction when the provider supports shared connections and transactions.

A simplified example is:

C#
await using var connection =
    new SqlConnection(connectionString);

await connection.OpenAsync(cancellationToken);

var options = new DbContextOptionsBuilder<OrderDbContext>()
    .UseSqlServer(connection)
    .Options;

await using var orderContext = new OrderDbContext(options);

await using var transaction =
    await orderContext.Database.BeginTransactionAsync(
        cancellationToken);

var inventoryOptions =
    new DbContextOptionsBuilder<InventoryDbContext>()
        .UseSqlServer(connection)
        .Options;

await using var inventoryContext =
    new InventoryDbContext(inventoryOptions);

await inventoryContext.Database.UseTransactionAsync(
    transaction.GetDbTransaction(),
    cancellationToken);

try
{
    orderContext.Orders.Add(order);

    await orderContext.SaveChangesAsync(cancellationToken);

    inventoryContext.InventoryItems
        .Where(i => i.ProductId == productId);

    // Perform the required inventory update here.

    await inventoryContext.SaveChangesAsync(cancellationToken);

    await transaction.CommitAsync(cancellationToken);
}
catch
{
    await transaction.RollbackAsync(cancellationToken);
    throw;
}

This example demonstrates how a second context can enlist in the transaction created by the first context.

The actual inventory update must be implemented before saving. Both contexts must use the same compatible relational connection, and the provider must support the required transaction behavior.

This technique can be useful when different application modules use separate DbContext types but share the same database.

However, it introduces additional coupling and resource management requirements.

If the contexts connect to different databases, sharing a local database transaction is generally not possible. Cross-database coordination requires a different architecture, such as a distributed transaction where supported or an eventual consistency pattern.

Handle Execution Strategies When Retrying Transactions

Modern applications often enable connection resiliency to handle temporary database connectivity failures.

For SQL Server, developers can configure retry behavior:

C#
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(
        connectionString,
        sqlOptions =>
        {
            sqlOptions.EnableRetryOnFailure(
                maxRetryCount: 5,
                maxRetryDelay: TimeSpan.FromSeconds(10),
                errorNumbersToAdd: null);
        }));

However, there is an important detail.

When retrying execution strategies are enabled, manually starting a transaction with BeginTransactionAsync() and executing operations directly can produce an exception.

EF Core needs to know how to retry the complete transaction as one unit.

Use the execution strategy returned by CreateExecutionStrategy():

C#
var strategy = _context.Database.CreateExecutionStrategy();

await strategy.ExecuteAsync(async () =>
{
    await using var transaction =
        await _context.Database.BeginTransactionAsync();

    _context.Orders.Add(order);

    await _context.SaveChangesAsync();

    await _context.OrderHistory.AddAsync(
        new OrderHistory
        {
            OrderId = order.Id,
            Status = "Created"
        });

    await _context.SaveChangesAsync();

    await transaction.CommitAsync();
});

This allows the configured execution strategy to retry the complete transactional operation when a retryable failure occurs.

However, retrying a transaction requires additional care.

If the connection fails while committing, the application may not know whether the database committed the transaction successfully. Retrying blindly can create duplicate records or repeat business operations.

Use stable identifiers, unique constraints, and idempotent operation design. For important transactions, consider EF Core's transaction execution verification mechanisms to determine whether an operation committed before retrying it.

Also, avoid performing external side effects inside the retry delegate. If the delegate runs again, an email, payment request, or external API call could be repeated.

The transactional outbox pattern is a better option for coordinating external work.

Use Savepoints for Recoverable Operations

EF Core supports savepoints when a SaveChanges() operation runs inside an existing transaction.

A savepoint represents a point inside the transaction to which the database can roll back without discarding the entire transaction.

This can be useful when an application performs multiple database operations and needs to recover from a specific failure.

For example, a transaction might create an order and then attempt an optional database operation.

A savepoint can provide a recovery point before the optional operation.

However, savepoints should not be used as a replacement for clear transaction boundaries.

There is also an important SQL Server consideration: when Multiple Active Result Sets (MARS) is enabled, EF Core does not create automatic savepoints. If a save operation fails, the transaction may be left in an uncertain state.

Check the provider documentation and connection configuration before relying on savepoint behavior.

Monitor Transaction Duration in Production

Keeping transactions short requires visibility into how long they remain open.

Monitor:

  • Transaction duration.
  • Database command duration.
  • Lock waits and blocking.
  • Deadlocks.
  • Connection pool utilization.
  • Transaction timeout errors.
  • Failed commits and rollbacks.

For SQL Server, Extended Events and database monitoring tools can help identify long-running transactions and blocking sessions.

EF Core also provides transaction logging and diagnostic interception capabilities that can be used to observe transaction lifecycle events.

A structured log might contain information such as:

Code
TransactionStarted
TransactionId: 8f21a
Operation: CreateOrder

DatabaseCommandCompleted
Duration: 42ms

DatabaseCommandCompleted
Duration: 31ms

TransactionCommitted
Duration: 96ms

The exact logging implementation depends on the application's logging and monitoring infrastructure.

Avoid logging sensitive database values or exposing customer information in diagnostic events.

The purpose is to understand transaction boundaries and identify operations that unnecessarily extend their duration.

Common Mistakes to Avoid

MistakeBetter approach
Starting a transaction for every database operationUse EF Core's default SaveChanges transaction where sufficient
Calling external APIs inside a transactionUse an outbox or another asynchronous workflow
Allowing each service to commit independentlyCentralize transaction ownership
Keeping transactions open during lengthy processingMove non-database work outside the transaction
Sharing multiple DbContexts without a shared transactionExplicitly enlist contexts when supported
Retrying a transaction without considering duplicate operationsUse idempotency and commit verification
Assuming separate databases share one local transactionUse an appropriate distributed or eventual consistency design
Ignoring blocking and transaction durationMonitor database locks and transaction lifecycle

Summary

EF Core transactions help maintain database consistency when several operations must succeed or fail together. However, keeping transactions open while multiple application services perform unrelated work can reduce database performance and increase contention.

The best approach is to define clear transaction boundaries and keep only the necessary database operations inside them.

Use EF Core's default SaveChangesAsync() transaction behavior when it is sufficient. Introduce explicit transactions when multiple database changes need to be atomic. Keep external API calls, notifications, and lengthy processing outside the transaction.

When several services participate in the same database operation, centralize transaction ownership and ensure that participating DbContext instances share the appropriate transaction.

For workflows involving external systems or multiple databases, consider patterns such as the transactional outbox and eventual consistency instead of trying to hold one database transaction across the entire business process.

A well-designed transaction should protect data consistency without unnecessarily holding database resources. This balance is essential for building reliable and scalable EF Core applications.