EF-Core-Optimization :👈 👉:Authentication-Entra-ID

ASP.NET Core Database Transaction Management and Concurrency Handling

ASP.NET Core Database Transaction Management and Concurrency Handling

1. Introduction

Database transaction management and concurrency handling are important concepts in ASP.NET Core applications. They help maintain data consistency, prevent incorrect updates, and ensure that multiple users can safely access and modify the same data.

Consider an e-commerce application where two users attempt to purchase the last available product at nearly the same time. Without proper concurrency handling, both users might successfully purchase the same item, resulting in incorrect inventory.

Transaction management ensures that a group of database operations succeeds or fails as a single unit. Concurrency handling ensures that simultaneous operations do not produce inconsistent data.

2. What Is a Database Transaction?

A database transaction is a group of database operations treated as one logical unit of work.

A transaction either:

  • Commits: All operations are successfully saved.
  • Rolls back: Changes made by the transaction are undone.

Example: Transferring ₹1,000 from Account A to Account B involves two operations:

  1. Deduct ₹1,000 from Account A.
  2. Add ₹1,000 to Account B.

Both operations must succeed. If the deduction succeeds but the addition fails, the transaction should roll back the deduction.

3. ACID Properties

Database transactions generally follow four important ACID properties.

Property Meaning Example
Atomicity All operations succeed or none do. Both sides of a bank transfer must complete.
Consistency Data remains valid according to database rules. Account balance cannot violate its defined constraints.
Isolation Concurrent transactions should not interfere incorrectly. Two users updating the same inventory must be handled safely.
Durability Committed changes remain saved. Committed payment information remains stored after a restart.

4. Transaction Flow

The following diagram shows a basic database transaction.

Begin Transaction Execute Database Operations All operations successful? No Rollback Yes Commit

5. Managing Transactions in ASP.NET Core Using EF Core

Entity Framework Core supports transactions through the Database property of the DbContext.

For example:

using Microsoft.EntityFrameworkCore;
public class OrderService
{
    private readonly AppDbContext _context;
    public OrderService(AppDbContext context)
    {
        _context = context;
    }
    public async Task CreateOrderAsync(Order order)
    {
        await using var transaction =
            await _context.Database.BeginTransactionAsync();
        try
        {
            _context.Orders.Add(order);
            await _context.SaveChangesAsync();
            var payment = new Payment
            {
                OrderId = order.Id,
                Amount = order.TotalAmount
            };
            _context.Payments.Add(payment);
            await _context.SaveChangesAsync();
            await transaction.CommitAsync();
        }
        catch
        {
            await transaction.RollbackAsync();
            throw;
        }
    }
}

Explanation

  1. BeginTransactionAsync() starts a database transaction.
  2. The order is inserted into the database.
  3. SaveChangesAsync() executes the insert within the transaction.
  4. The payment is inserted.
  5. The second SaveChangesAsync() executes the payment insert.
  6. CommitAsync() commits both operations.
  7. If an exception occurs before the commit, rollback cancels the transaction's database changes.

Important: EF Core automatically wraps the changes in a single SaveChanges() call in a transaction when the database provider supports transactions. An explicit transaction is useful when multiple saves or other database commands must belong to the same transaction.

6. Transaction Without Explicit BeginTransaction

If all database changes are made in one SaveChangesAsync() call, EF Core normally handles the transaction automatically.

public async Task CreateOrderAsync(Order order)
{
    _context.Orders.Add(order);
    _context.Payments.Add(new Payment
    {
        Order = order,
        Amount = order.TotalAmount
    });
    await _context.SaveChangesAsync();
}

Here, EF Core normally saves both inserts within one transaction. If either database operation fails, the transaction is rolled back.

Use explicit transactions when you need multiple SaveChangesAsync() calls, database commands, or other supported operations to participate in one transaction.

7. Transaction Isolation Levels

Isolation levels determine how one transaction can see changes made by other concurrent transactions.

Isolation Level Description
Read Uncommitted Can read changes that another transaction has not committed.
Read Committed Prevents reading uncommitted changes.
Repeatable Read Prevents rows already read from being changed by another transaction until the current transaction completes. Exact behavior depends on the database.
Serializable Provides the strongest standard isolation level by preventing conflicting transaction effects that would violate serial execution.
Snapshot Reads a consistent version of data using row versions, where supported and enabled by the database.

Isolation Level Comparison

Problem Meaning
Dirty Read Reading data changed by a transaction that has not committed.
Non-repeatable Read Reading the same row twice and receiving different committed values.
Phantom Read Repeating a query and finding additional or missing rows because another transaction changed the matching set.

Setting an Isolation Level in EF Core

using System.Data;
using Microsoft.EntityFrameworkCore;
public async Task UpdateDataAsync()
{
    await using var transaction =
        await _context.Database.BeginTransactionAsync(
            IsolationLevel.Serializable);
    try
    {
        // Perform database operations.
        await _context.SaveChangesAsync();
        await transaction.CommitAsync();
    }
    catch
    {
        await transaction.RollbackAsync();
        throw;
    }
}

Important: Higher isolation levels can reduce concurrency and increase blocking or deadlocks. Choose an isolation level according to the consistency requirements and database provider behavior.

8. What Is Concurrency?

Concurrency means multiple users or application processes access or modify the same data at the same time.

For example, suppose a product has 10 items in stock. Two customers attempt to purchase 7 items each.

  • Customer A reads stock = 10.
  • Customer B reads stock = 10.
  • Customer A purchases 7 items.
  • Customer B also purchases 7 items based on the old stock value.

Without concurrency protection, the application could incorrectly accept both orders.

9. Types of Concurrency Handling

There are two main approaches:

9.1 Optimistic Concurrency

Optimistic concurrency assumes that conflicts are relatively uncommon. Multiple users can read the same record, but the application checks whether the record changed before saving an update.

If another user has already modified the record, the update is rejected and the application handles the conflict.

EF Core supports optimistic concurrency through concurrency tokens.

9.2 Pessimistic Concurrency

Pessimistic concurrency assumes that conflicts are possible and uses database locking to prevent conflicting operations while a transaction is working with the data.

For example, a database transaction can acquire an appropriate lock before updating a record. Other transactions that need conflicting access may have to wait.

Pessimistic concurrency is generally implemented using database-specific locking behavior and SQL commands. It is not a single provider-independent EF Core feature.

10. Optimistic Concurrency Using RowVersion

In SQL Server, a rowversion column can be used as a concurrency token.

It is a database-generated binary value that changes when the row is updated. It is not a date or time value.

Step 1: Create the Entity

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int Stock { get; set; }
    public byte[] RowVersion { get; set; }
}

Step 2: Configure RowVersion

protected override void OnModelCreating(
    ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Product>()
        .Property(p => p.RowVersion)
        .IsRowVersion();
}

Alternatively, use the [Timestamp] attribute:

using System.ComponentModel.DataAnnotations;
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    [Timestamp]
    public byte[] RowVersion { get; set; }
}

Use one configuration approach for the same property rather than configuring it redundantly.

Step 3: Update the Product

public async Task UpdateProductAsync(
    int id,
    decimal newPrice)
{
    var product = await _context.Products
        .FirstOrDefaultAsync(p => p.Id == id);
    if (product == null)
    {
        throw new Exception("Product not found.");
    }
    product.Price = newPrice;
    await _context.SaveChangesAsync();
}

How RowVersion Works

EF Core includes the original rowversion value in the update condition. The generated SQL is conceptually similar to:

UPDATE Products
SET Price = @NewPrice
WHERE Id = @Id
  AND RowVersion = @OriginalRowVersion;

If another transaction has already updated the row, its rowversion will have changed. The update affects zero rows, and EF Core throws DbUpdateConcurrencyException.

11. Handling DbUpdateConcurrencyException

EF Core throws DbUpdateConcurrencyException when an optimistic concurrency check detects that the expected database row was not updated.

public async Task UpdateProductAsync(
    int id,
    decimal newPrice)
{
    var product = await _context.Products
        .FirstOrDefaultAsync(p => p.Id == id);
    if (product == null)
    {
        throw new Exception("Product not found.");
    }
    product.Price = newPrice;
    try
    {
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException)
    {
        throw new InvalidOperationException(
            "This product was modified by another user. Please reload and try again.");
    }
}

This example informs the caller about the conflict. In a real application, the API can return HTTP 409 Conflict so the client can reload the latest data.

Returning HTTP 409 Conflict

[HttpPut("{id:int}")]
public async Task<IActionResult> UpdateProduct(
    int id,
    UpdateProductRequest request)
{
    try
    {
        await _productService.UpdateProductAsync(
            id,
            request.Price);
        return NoContent();
    }
    catch (DbUpdateConcurrencyException)
    {
        return Conflict(new
        {
            message = "The product was modified by another user. Reload the latest data and try again."
        });
    }
}

12. Resolving Concurrency Conflicts

There are several ways to handle concurrency conflicts.

Option 1: Ask the User to Reload

Return a conflict response and ask the user to reload the latest record before submitting another update.

This is often suitable for administrative forms and editing screens.

Option 2: Client Wins

The application deliberately overwrites the current database values with the client's values after resolving the conflict. This should only be used when the business rules permit it.

Option 3: Database Wins

The application discards the attempted update and reloads the latest database values.

Option 4: Merge Changes

The application compares the current database values with the user's intended changes and combines non-conflicting updates.

Example: Reloading Database Values

try
{
    await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException ex)
{
    foreach (var entry in ex.Entries)
    {
        await entry.ReloadAsync();
    }
    throw new InvalidOperationException(
        "The record changed. The latest database values have been loaded.");
}

This example uses a database-wins approach. It reloads the values but does not automatically retry the user's update.

13. Pessimistic Concurrency and Database Locks

Pessimistic concurrency uses database locks to control access to data while a transaction is running.

For example, SQL Server supports locking hints such as UPDLOCK and HOLDLOCK. Their behavior depends on the transaction and query.

Example SQL Server query:

BEGIN TRANSACTION;
SELECT *
FROM Products WITH (UPDLOCK, HOLDLOCK)
WHERE Id = 10;
UPDATE Products
SET Stock = Stock - 1
WHERE Id = 10
  AND Stock > 0;
COMMIT TRANSACTION;

Important: Locking hints are database-specific. Use parameterized queries, keep transactions short, and verify the locking behavior under the database isolation level being used.

14. Preventing Overselling with an Atomic Update

For inventory operations, an atomic conditional update is often simpler than reading a stock value and then updating it separately.

public async Task<bool> DecreaseStockAsync(
    int productId,
    int quantity)
{
    if (quantity <= 0)
    {
        throw new ArgumentOutOfRangeException(
            nameof(quantity));
    }
    var affectedRows = await _context.Products
        .Where(p => p.Id == productId
                 && p.Stock >= quantity)
        .ExecuteUpdateAsync(setters => setters
            .SetProperty(
                p => p.Stock,
                p => p.Stock - quantity));
    return affectedRows == 1;
}

This approach makes the stock check and stock reduction part of one database statement. If there is insufficient stock, no row is updated.

Important: ExecuteUpdateAsync() executes directly in the database and does not automatically synchronize already tracked entity instances. Reload or clear affected tracked entities when necessary. If the stock update must be combined with other database operations, use an explicit transaction.

15. Transactions Across Multiple DbContext Instances

Sometimes an application uses more than one DbContext instance to access the same relational database transaction.

EF Core relational providers can share a transaction when the contexts share the same database connection and transaction.

await using var transaction =
    await context1.Database.BeginTransactionAsync();
try
{
    await context1.SaveChangesAsync();
    await context2.Database.UseTransactionAsync(
        transaction.GetDbTransaction());
    await context2.SaveChangesAsync();
    await transaction.CommitAsync();
}
catch
{
    await transaction.RollbackAsync();
    throw;
}

This is an advanced scenario. Both contexts must be configured to use the same relational connection, and the second context must join the existing transaction correctly. Add the appropriate Microsoft.EntityFrameworkCore.Storage namespace for GetDbTransaction().

16. Distributed Transactions in Microservices

A distributed transaction involves multiple independent services or databases.

Consider an e-commerce system:

  • Order Service stores order details.
  • Payment Service processes payment.
  • Inventory Service updates stock.
  • Shipping Service creates a shipment.

A normal database transaction cannot automatically guarantee atomicity across all these independent services and databases.

Distributed Workflow

Order Service Payment Service Inventory Service Shipping Service Order Completed

In distributed systems, the Saga pattern is commonly used to coordinate a sequence of local transactions.

What Is the Saga Pattern?

A Saga is a sequence of local transactions. Each service commits its own database transaction and publishes or sends an event to continue the workflow.

If a later operation fails, compensating actions are executed to address earlier successful operations.

Step Operation Possible Compensation
1 Create Order Cancel Order
2 Reserve Payment Refund or release payment
3 Reserve Inventory Release inventory
4 Create Shipment Cancel shipment, if possible

Compensation is a new business operation, not a literal rollback of the earlier committed database transaction.

17. What Is the Transactional Outbox Pattern?

The Transactional Outbox pattern helps solve the problem of saving database changes and publishing an event reliably.

For example, an Order Service must:

  1. Save the order in its database.
  2. Publish an OrderCreated event to RabbitMQ.

If the order is saved but the message is not published, another service may never learn about the order.

The Outbox pattern saves both the order and an event record in the same database transaction.

Outbox Flow

Order Service Single Database Transaction Save Order + Save Outbox Event Background Publisher RabbitMQ / Message Broker

The background publisher reads unpublished outbox records and sends them to the message broker. It marks records as published after successful delivery.

In practice, publishing can happen more than once if the publisher crashes after sending a message but before recording success. Consumers should therefore be idempotent and safely handle duplicate messages.

18. Retry Strategies and Transient Failures

Database operations can fail temporarily because of:

  • Temporary network interruptions.
  • Database failovers.
  • Transient service unavailability.
  • Temporary resource pressure.

EF Core providers can support retry strategies through execution strategies.

SQL Server Retry Configuration

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(
        builder.Configuration.GetConnectionString(
            "DefaultConnection"),
        sqlOptions =>
            sqlOptions.EnableRetryOnFailure(
                maxRetryCount: 3,
                maxRetryDelay: TimeSpan.FromSeconds(5),
                errorNumbersToAdd: null
            )
    )
);

This example configures SQL Server's retry-on-failure strategy. The exact transient errors and provider behavior depend on the database environment.

Explicit Transactions with Retry Strategies

When retry-on-failure is enabled, manually initiated transactions should be executed through the provider's execution strategy. Otherwise, EF Core may reject the operation because it cannot safely retry an arbitrary transaction automatically.

var strategy = _context.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async () =>
{
    await using var transaction =
        await _context.Database.BeginTransactionAsync();
    try
    {
        // Perform all operations belonging to this transaction.
        await _context.SaveChangesAsync();
        await transaction.CommitAsync();
    }
    catch
    {
        await transaction.RollbackAsync();
        throw;
    }
});

Important: A retry can repeat an operation whose previous outcome is uncertain. Use idempotency keys, unique constraints, or another reliable deduplication mechanism for operations such as payments and order creation. Do not assume that every failure means the transaction definitely rolled back.

19. Deadlocks

A deadlock occurs when two or more transactions are waiting for resources held by each other, so none can continue.

Example

  • Transaction A locks Account 1 and requests Account 2.
  • Transaction B locks Account 2 and requests Account 1.
  • Both transactions wait for the other to release its lock.
Transaction A Transaction B Locks Account 1 Locks Account 2 Each transaction waits for the other's lock

Most relational databases detect deadlocks and select one transaction as the victim. The victim transaction is rolled back.

How to Prevent Deadlocks

  • Access tables and rows in a consistent order.
  • Keep transactions short.
  • Avoid unnecessary locks.
  • Create suitable indexes to reduce the number of rows scanned and locked.
  • Avoid waiting for external API calls while holding database locks.
  • Retry deadlock victims when the operation is safe to retry.
  • Inspect database deadlock reports to identify the actual cause.

20. DbContext and Concurrency

DbContext is not thread-safe. Do not run multiple parallel database operations on the same context instance.

Incorrect example:

var productsTask = _context.Products.ToListAsync();
var ordersTask = _context.Orders.ToListAsync();
await Task.WhenAll(productsTask, ordersTask);

Both queries use the same DbContext concurrently. This can cause an error because EF Core does not support multiple active operations on one context instance.

Correct approach: Execute operations sequentially on the same context:

var products = await _context.Products.ToListAsync();
var orders = await _context.Orders.ToListAsync();

If independent parallel operations are genuinely required, use separate context instances, commonly created through IDbContextFactory<TContext>.

public class DashboardService
{
    private readonly IDbContextFactory<AppDbContext> _factory;
    public DashboardService(
        IDbContextFactory<AppDbContext> factory)
    {
        _factory = factory;
    }
    public async Task LoadDashboardAsync()
    {
        await using var context1 =
            await _factory.CreateDbContextAsync();
        await using var context2 =
            await _factory.CreateDbContextAsync();
        var productsTask = context1.Products.ToListAsync();
        var ordersTask = context2.Orders.ToListAsync();
        await Task.WhenAll(productsTask, ordersTask);
    }
}

21. Using Transactions with Stored Procedures

Stored procedures can perform multiple database operations. They can also manage their own transactions, depending on how they are written.

Example SQL Server stored procedure:

CREATE PROCEDURE TransferAmount
    @FromAccountId INT,
    @ToAccountId INT,
    @Amount DECIMAL(18,2)
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;
    BEGIN TRY
        BEGIN TRANSACTION;
        UPDATE Accounts
        SET Balance = Balance - @Amount
        WHERE Id = @FromAccountId
          AND Balance >= @Amount;
        IF @@ROWCOUNT = 0
            THROW 50001, 'Insufficient balance or source account not found.', 1;
        UPDATE Accounts
        SET Balance = Balance + @Amount
        WHERE Id = @ToAccountId;
        IF @@ROWCOUNT = 0
            THROW 50002, 'Destination account not found.', 1;
        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        IF XACT_STATE() <> 0
            ROLLBACK TRANSACTION;
        THROW;
    END CATCH
END;

This is a SQL Server-specific example. A production implementation should also validate that the amount is positive, prevent transferring to the same account if prohibited, and enforce suitable constraints and business rules.

22. Best Practices for Transaction Management

  • Keep database transactions as short as possible.
  • Use explicit transactions only when multiple operations must be atomic.
  • Use optimistic concurrency for ordinary record editing where conflicts are relatively uncommon.
  • Use atomic conditional updates for inventory and other counter-like operations.
  • Choose isolation levels based on actual consistency requirements.
  • Handle DbUpdateConcurrencyException explicitly.
  • Handle deadlocks and transient errors with safe retry policies.
  • Never assume a failed network call means a transaction was rolled back.
  • Do not call external APIs or message brokers while holding a database transaction open unless the design specifically requires it.
  • Use the Outbox pattern for reliable event publishing.
  • Use Saga workflows for multi-service business processes.
  • Use unique constraints to protect important business invariants.
  • Use cancellation tokens for long-running asynchronous database operations.
  • Monitor transaction duration, lock waits, deadlocks, and database performance.

23. Common Mistakes to Avoid

Mistake Why It Is a Problem Better Approach
Keeping transactions open too long Increases lock duration and blocking. Keep the transaction limited to necessary database work.
Ignoring concurrency exceptions Updates can fail without proper conflict handling. Handle and resolve concurrency conflicts.
Using Serializable everywhere Can reduce concurrency and increase blocking. Choose the lowest isolation level that meets the requirement.
Using the same DbContext in parallel tasks DbContext is not thread-safe. Use separate context instances for parallel operations.
Publishing events before database commit Consumers may receive an event for data that is later rolled back. Use the Transactional Outbox pattern.
Blindly retrying payments A previous attempt may have succeeded despite a communication failure. Use idempotency and reliable payment status checks.
Assuming an EF Core transaction covers multiple databases A normal local transaction does not automatically coordinate independent databases. Use an appropriate distributed workflow such as Saga.

24. Real-World Example: E-Commerce Order Processing

Consider an order that needs to reduce inventory and create an order record.

Local Database Transaction

public async Task<bool> PlaceOrderAsync(
    int productId,
    int quantity)
{
    if (quantity <= 0)
    {
        throw new ArgumentOutOfRangeException(
            nameof(quantity));
    }
    await using var transaction =
        await _context.Database.BeginTransactionAsync();
    try
    {
        var product = await _context.Products
            .FirstOrDefaultAsync(p => p.Id == productId);
        if (product == null || product.Stock < quantity)
        {
            await transaction.RollbackAsync();
            return false;
        }
        product.Stock -= quantity;
        var order = new Order
        {
            ProductId = productId,
            Quantity = quantity,
            CreatedAt = DateTime.UtcNow
        };
        _context.Orders.Add(order);
        await _context.SaveChangesAsync();
        await transaction.CommitAsync();
        return true;
    }
    catch
    {
        await transaction.RollbackAsync();
        throw;
    }
}

This example groups the stock update and order insertion into one local transaction. However, the initial stock read and later update can still be vulnerable to concurrent purchases unless suitable concurrency protection is added.

For a high-concurrency inventory system, prefer an atomic conditional stock update and create the order in the same transaction.

public async Task<bool> PlaceOrderSafelyAsync(
    int productId,
    int quantity)
{
    if (quantity <= 0)
    {
        throw new ArgumentOutOfRangeException(
            nameof(quantity));
    }
    await using var transaction =
        await _context.Database.BeginTransactionAsync();
    try
    {
        var affectedRows = await _context.Products
            .Where(p => p.Id == productId
                     && p.Stock >= quantity)
            .ExecuteUpdateAsync(setters => setters
                .SetProperty(
                    p => p.Stock,
                    p => p.Stock - quantity));
        if (affectedRows == 0)
        {
            await transaction.RollbackAsync();
            return false;
        }
        _context.Orders.Add(new Order
        {
            ProductId = productId,
            Quantity = quantity,
            CreatedAt = DateTime.UtcNow
        });
        await _context.SaveChangesAsync();
        await transaction.CommitAsync();
        return true;
    }
    catch
    {
        await transaction.RollbackAsync();
        throw;
    }
}

This version prevents two transactions from successfully reducing stock below zero, provided the database statement and transaction execute normally. The order insert and stock reduction commit or roll back together.

25. Transaction Management vs Concurrency Handling

Feature Transaction Management Concurrency Handling
Purpose Ensure a group of operations succeeds or fails together. Prevent conflicting simultaneous updates.
Main concern Atomicity and consistency. Conflicting access to shared data.
Common techniques Commit, rollback, isolation levels. RowVersion, concurrency tokens, locks, atomic updates.
EF Core support BeginTransactionAsync, CommitAsync, RollbackAsync. IsConcurrencyToken, IsRowVersion, DbUpdateConcurrencyException.
Example Save an order and its payment record together. Prevent two users from purchasing unavailable stock.

26. Interview Questions and Answers

Q1. What is a database transaction?

A transaction is a group of database operations treated as one unit. All operations are committed together or rolled back when the transaction fails.

Q2. What are ACID properties?

ACID stands for Atomicity, Consistency, Isolation, and Durability. These properties help maintain database reliability and consistency.

Q3. Does EF Core automatically create transactions?

Yes. EF Core normally wraps a single SaveChanges() call in a transaction when the provider supports transactions. Explicit transactions are useful when multiple operations or multiple save calls must be atomic together.

Q4. What is the difference between Commit and Rollback?

Commit permanently applies the transaction's changes. Rollback cancels the transaction's uncommitted changes.

Q5. What is optimistic concurrency?

Optimistic concurrency allows multiple users to work with data but checks whether the record changed before saving an update. Conflicts are detected when an update is attempted.

Q6. What is pessimistic concurrency?

Pessimistic concurrency uses database locks to prevent conflicting operations while a transaction is working with particular data.

Q7. What is RowVersion?

In SQL Server, RowVersion is a database-generated binary value that changes whenever the row is updated. EF Core can use it as a concurrency token.

Q8. What is DbUpdateConcurrencyException?

It is an EF Core exception raised when an optimistic concurrency check detects that the expected database row was not updated.

Q9. What is a deadlock?

A deadlock occurs when transactions wait for resources held by each other, preventing progress. The database generally detects the deadlock and rolls back one transaction.

Q10. What is the difference between Repeatable Read and Serializable?

Repeatable Read protects rows already read from being changed by another transaction until the current transaction completes. Serializable provides stronger protection against concurrent changes to the matching data set. Exact behavior depends on the database engine.

Q11. What is the Saga pattern?

Saga is a distributed transaction coordination pattern that uses a sequence of local transactions and compensating actions to manage multi-service business workflows.

Q12. What is the Transactional Outbox pattern?

It stores business data and an event record in the same local database transaction. A background publisher later sends the event to a message broker.

Q13. Can we use the same DbContext in multiple threads?

No. DbContext is not thread-safe. Use separate context instances for independent parallel operations.

Q14. How do you prevent overselling in an e-commerce application?

Use an atomic conditional database update that reduces stock only when sufficient stock exists. Combine the update and order creation in a transaction.

Q15. What happens if a transaction fails after some SQL statements execute?

If the statements belong to an active transaction, a rollback cancels their uncommitted database changes.

Q16. Should we keep a database transaction open while calling an external API?

Generally, no. External calls can be slow or fail, extending lock duration. Prefer short local transactions and reliable messaging patterns such as the Outbox and Saga patterns.

Q17. Can EF Core handle distributed transactions automatically?

No. A normal EF Core transaction is generally a local database transaction. Cross-service workflows usually need explicit distributed coordination, such as Saga.

Q18. What is the difference between a concurrency token and a transaction?

A transaction groups operations into one atomic unit. A concurrency token detects whether data has changed since it was read. They solve different problems and can be used together.

27. Recommended Learning Resources

28. Final Summary

  • Transactions ensure that multiple database operations succeed or fail together.
  • ACID properties help maintain reliable database operations.
  • EF Core supports automatic transactions for individual SaveChanges calls and explicit transactions for larger units of work.
  • Optimistic concurrency detects conflicting updates using concurrency tokens such as SQL Server RowVersion.
  • Pessimistic concurrency uses database locks to control access.
  • Atomic conditional updates are useful for inventory and other high-concurrency operations.
  • Deadlocks should be prevented through short transactions and consistent resource access order.
  • Distributed workflows can use Saga and Transactional Outbox patterns.
  • DbContext must not be used concurrently by multiple threads.
🔙
EF-Core-Optimization :👈 👉:Authentication-Entra-ID