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:
Place Order
|
|-- Validate Customer
|
|-- Check Product Availability
|
|-- Call Payment Service
|
|-- Save Order
|
|-- Update Inventory
|
|-- Send Notification
|
|-- Commit TransactionSuppose 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:
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:
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:
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:
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:
OrderApplicationService
|
|-- OrderRepository
|
|-- InventoryService
|
|-- PaymentRecordService
|
|-- OrderHistoryServiceA 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:
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;
}
}
}
Join the conversation! Your thoughts help the community grow.