ASP.NET Core applications often allow multiple users to view and update the same data. For example, two administrators may edit the same product, multiple employees may update a customer record, or two users may change the same order at nearly the same time.
These situations can create a data consistency problem. One user may save changes without knowing that another user has already modified the same record. If the application accepts both updates without checking the original data, the later update can overwrite the earlier one.
This problem is commonly known as a lost update. It can result in incorrect information, missing changes, and unexpected application behavior.
Optimistic concurrency control helps prevent this problem by checking whether the data has changed since a user originally retrieved it. Entity Framework Core supports optimistic concurrency through concurrency tokens, including SQL Server rowversion columns.
This article explains how optimistic concurrency works, how to configure it in ASP.NET Core with EF Core, how to handle concurrency exceptions, and how to test concurrent updates in a practical application.
Understanding the Lost Update Problem
Consider an application that allows administrators to update product information. A product has a name and a price, and its current price is $100.
Two administrators open the same product at approximately the same time.
Administrator A retrieves the product with a price of $100.
Administrator B also retrieves the product with a price of $100.
Administrator A changes the price to $120 and saves the record.
Administrator B changes the price to $110 and saves the record.
If the application does not check whether the product was changed after it was retrieved, Administrator B's update may overwrite Administrator A's change.
The final price becomes $110, even though Administrator A had already saved $120.
The problem is not that either administrator entered invalid information. Both users worked with a valid version of the record when they opened it. The problem is that the application did not detect that the underlying data changed before the second update was saved.
Optimistic concurrency control prevents this silent overwrite by checking whether the record has changed since it was originally read.
What Is Optimistic Concurrency Control?
Optimistic concurrency assumes that conflicts are relatively uncommon. Instead of locking a database record whenever someone reads it, the application allows multiple users to read and edit the same data.
When a user saves an update, the application checks whether the original record is still the same version that the user retrieved.
If the record has not changed, the update succeeds.
If another user has modified the record, the update is rejected as a concurrency conflict. The application can then ask the user to reload the latest information, compare changes, or decide how to combine them.
This approach is useful for applications where users frequently read data and only occasionally update the same record at the same time.
It avoids keeping database locks open while users are editing forms. A user might open a product page, spend several minutes changing fields, and then save. Holding a database transaction open throughout that entire period would be inefficient and could cause blocking.
Optimistic concurrency instead checks for conflicts when the update is submitted.
Understanding Concurrency Tokens in EF Core
Entity Framework Core uses concurrency tokens to identify whether a database record has changed since it was retrieved.
A concurrency token is a property that EF Core includes in the WHERE condition of an update or delete statement.
For example, suppose a product has an identifier and a row version. When EF Core updates the product, it checks both the identifier and the original row version.
Conceptually, the generated SQL looks like this:
UPDATE Products
SET Name = @NewName,
Price = @NewPrice
WHERE Id = @ProductId
AND RowVersion = @OriginalRowVersion;
The update succeeds only if a record matches both conditions.
If another transaction has already changed the product, the row version will be different. The UPDATE statement affects zero rows, and EF Core detects that the expected record was not updated.
It then throws a DbUpdateConcurrencyException.
This mechanism allows the application to identify conflicting updates without requiring long-running database locks.
Configuring RowVersion in an ASP.NET Core Application
SQL Server provides a rowversion data type that automatically generates a new binary value whenever a row containing that column is inserted or updated.
This makes rowversion a convenient concurrency token.
Consider the following Product entity:
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
public byte[] RowVersion { get; set; } = [];
}
The RowVersion property stores the version value generated by SQL Server. The application should not calculate or manually update this value.
Next, configure the property as a row version using the Timestamp attribute:
using System.ComponentModel.DataAnnotations;
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; } = [];
}
The Timestamp attribute tells EF Core that the property is a concurrency token and is generated by the database.
You can configure the same behavior through Fluent API:
protected override void OnModelCreating(
ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>()
.Property(x => x.RowVersion)
.IsRowVersion();
}
Both approaches configure the property as a database-generated concurrency token. Fluent API is useful when the application keeps entity classes free from persistence-specific attributes or centralizes database configuration.
After creating the migration, EF Core generates a rowversion column in the SQL Server database.
dotnet ef migrations add AddProductRowVersion
dotnet ef database update
The migration should create the appropriate rowversion column. SQL Server manages the value automatically, so the application does not need to generate a new version when saving a product.
One important detail is that SQL Server rowversion is not a date or time value. It is an automatically generated binary version value. It should be used for change detection, not for recording when a product was updated.
Implementing an Update Endpoint
After configuring the concurrency token, the application can use it when updating records.
A common approach is to return the row version when retrieving a product and require the client to send that original version when submitting an update.
First, define a response model:
public class ProductResponse
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
public string RowVersion { get; set; } = string.Empty;
}
The row version is represented as a Base64 string because JSON does not have a native binary data type.
The API can retrieve the product and return its version:
[HttpGet("{id}")]
public async Task<IActionResult> GetProduct(int id)
{
var product = await _dbContext.Products
.AsNoTracking()
.FirstOrDefaultAsync(x => x.Id == id);
if (product == null)
{
return NotFound();
}
var response = new ProductResponse
{
Id = product.Id,
Name = product.Name,
Price = product.Price,
RowVersion = Convert.ToBase64String(
product.RowVersion)
};
return Ok(response);
}
When the client retrieves a product, it receives both the product information and its current row version.
For example, the response might look like this:
{
"id": 10,
"name": "Laptop",
"price": 1000,
"rowVersion": "AAAAAAAAB9E="
}
The client should keep this value while the user edits the product. When the user submits the update, the client sends the same version it originally received.
The update request model can contain the version:
public class UpdateProductRequest
{
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
public string RowVersion { get; set; } = string.Empty;
}
The controller can then compare the original version with the current database version during the update.
[HttpPut("{id}")]
public async Task<IActionResult> UpdateProduct(
int id,
UpdateProductRequest request)
{
var product = await _dbContext.Products
.FirstOrDefaultAsync(x => x.Id == id);
if (product == null)
{
return NotFound();
}
byte[] originalRowVersion;
try
{
originalRowVersion =
Convert.FromBase64String(request.RowVersion);
}
catch (FormatException)
{
return BadRequest("Invalid row version.");
}
_dbContext.Entry(product)
.Property(x => x.RowVersion)
.OriginalValue = originalRowVersion;
product.Name = request.Name;
product.Price = request.Price;
try
{
await _dbContext.SaveChangesAsync();
return NoContent();
}
catch (DbUpdateConcurrencyException)
{
return Conflict(
"The product was modified by another user. Reload the latest data before updating.");
}
}
The important part is assigning the client's original version to EF Core's OriginalValue.
EF Core uses this value when generating the update statement. If the database record still has the same version, the update succeeds. If another user has modified the record, the update affects no rows and EF Core throws DbUpdateConcurrencyException.
The endpoint catches that exception and returns HTTP 409 Conflict.
This tells the client that the update could not be completed because the resource changed after the client retrieved it.
The example uses a tracked entity loaded from the database, but the original version supplied by the client is used for the concurrency check. The client must not be allowed to choose arbitrary fields or versions without appropriate validation and authorization.
Handling DbUpdateConcurrencyException
A concurrency exception should not be treated as an ordinary database failure. It represents a specific situation: the data being updated no longer matches the version expected by the application.
The application should handle this situation in a way that helps the user understand what happened.
For example, an API can return HTTP 409 Conflict with a message explaining that another user updated the record.
A more useful response can also include the latest server-side version of the resource.
catch (DbUpdateConcurrencyException exception)
{
var entry = exception.Entries.Single();
var databaseValues =
await entry.GetDatabaseValuesAsync();
if (databaseValues == null)
{
return NotFound(
"The product was deleted by another user.");
}
var currentProduct =
(Product)databaseValues.ToObject();
return Conflict(new
{
Message = "The product was modified by another user.",
CurrentProduct = new
{
currentProduct.Id,
currentProduct.Name,
currentProduct.Price,
RowVersion = Convert.ToBase64String(
currentProduct.RowVersion)
}
});
}
This example retrieves the latest database values after a concurrency conflict.
There are two important possibilities.
The first is that the record still exists but has been modified. The application can return the latest version so that the client can display the updated information.
The second is that another user deleted the record. In this case, GetDatabaseValuesAsync returns null, and the application can return HTTP 404 Not Found.
The application should not automatically overwrite the latest database values with the user's old values unless that behavior is explicitly required. Doing so can recreate the lost update problem that optimistic concurrency was intended to prevent.
For more complex applications, the API may return the current record and let the client compare the original values with the updated values. The user can then decide which changes should be retained.
Understanding Client-Side Concurrency Handling
Returning HTTP 409 is only part of the solution. The client application must also handle the response correctly.
Suppose an administrator opens a product with a price of $100. Another administrator changes the price to $120 and saves it. The first administrator then tries to save a price of $110.
The API detects the conflict and returns HTTP 409.
The client should not simply display a generic server error. It should explain that the product was updated by someone else and provide an option to reload the latest information.
For a web application, the user might see a message such as:
"The product has been updated by another user. Reload the latest version before making further changes."
For a mobile application, the app can retrieve the current product and refresh the editing screen.
Some applications may support a comparison screen that displays the user's changes alongside the latest database values. This is especially useful for collaborative editing systems, administrative dashboards, and business applications where users frequently update shared records.
The correct conflict-resolution strategy depends on the data. Automatically combining changes may be safe for some independent fields, but it can be dangerous when fields depend on one another.
Using ETags and If-Match Headers
Concurrency information does not have to be sent through a custom JSON property. HTTP provides a standard mechanism for conditional requests using entity tags.
An ETag represents a particular version of a resource. The server sends it when returning the resource, and the client sends it back through the If-Match header when attempting an update.
For example, the server may return:
HTTP/1.1 200 OK
ETag: "AAAAAAAAB9E="
Content-Type: application/json
The client then sends an update with:
PUT /api/products/10 HTTP/1.1
If-Match: "AAAAAAAAB9E="
Content-Type: application/json
The server checks whether the supplied ETag matches the current resource version.
If the version is still current, the update can proceed. If it is outdated, the server should reject the conditional update with HTTP 412 Precondition Failed.
This approach is useful when the API wants to follow standard HTTP conditional request semantics.
The distinction between the two response codes is important:
HTTP 409 Conflict indicates that the request conflicts with the current state of the resource.
HTTP 412 Precondition Failed indicates that a request condition, such as If-Match, was not satisfied.
A production implementation should validate the ETag format, handle missing preconditions according to the API contract, and use a consistent response strategy.
ETags should also be treated as opaque values. Clients should return them unchanged rather than trying to interpret their contents.
Optimistic Concurrency With Databases Other Than SQL Server
The rowversion approach shown earlier is specific to SQL Server.
Other databases and providers may use different concurrency mechanisms. EF Core also supports application-managed concurrency tokens.
For example, an application can use a GUID property as a concurrency token:
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
public Guid Version { get; set; }
}
Configure the property as a concurrency token:
protected override void OnModelCreating(
ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>()
.Property(x => x.Version)
.IsConcurrencyToken();
}
When updating a product, the application must generate a new version value:
product.Name = request.Name;
product.Price = request.Price;
product.Version = Guid.NewGuid();
await _dbContext.SaveChangesAsync();
EF Core uses the original Version value in the update condition and writes the new value when the update succeeds.
If another update has changed the version first, the original version no longer matches and EF Core raises a concurrency exception.
Application-managed tokens give developers more control over when a version changes. For example, an application may decide that certain internal fields should not cause a concurrency conflict.
However, the application must update the token correctly every time a relevant change occurs. If a code path changes important data without changing the version, concurrency detection can become unreliable.
Testing Optimistic Concurrency
Concurrency behavior should be tested with separate database contexts because each context needs its own view of the original data.
A useful test follows this sequence:
Create a product and save it to the database.
Create two separate DbContext instances.
Retrieve the same product through both contexts.
Modify and save the product through the first context.
Modify and save the product through the second context.
Verify that the second save throws DbUpdateConcurrencyException.
A simplified test using an SQL Server test database might look like this:
[Fact]
public async Task UpdateProduct_ShouldDetectConcurrencyConflict()
{
await using var setupContext = CreateDbContext();
var product = new Product
{
Name = "Laptop",
Price = 1000
};
setupContext.Products.Add(product);
await setupContext.SaveChangesAsync();
await using var contextA = CreateDbContext();
await using var contextB = CreateDbContext();
var productA = await contextA.Products
.SingleAsync(x => x.Id == product.Id);
var productB = await contextB.Products
.SingleAsync(x => x.Id == product.Id);
productA.Price = 1100;
await contextA.SaveChangesAsync();
productB.Price = 1200;
await Assert.ThrowsAsync<DbUpdateConcurrencyException>(
async () =>
{
await contextB.SaveChangesAsync();
});
}
The first context retrieves the product and updates its price to $1,100. SQL Server generates a new rowversion value when that update is saved.
The second context still holds the original rowversion value. When it tries to save the price of $1,200, EF Core includes the old version in the update condition. Because the database now contains a different version, the update affects no rows and EF Core throws DbUpdateConcurrencyException.
This test verifies the actual database concurrency behavior. Use a relational test database that supports the configured concurrency mechanism. EF Core's InMemory provider does not reproduce SQL Server rowversion behavior and should not be used to validate this particular scenario.
Common Mistakes to Avoid
Not returning the concurrency token to the client
If the API uses a row version but does not return it when retrieving the resource, the client cannot provide the original version during an update.
The application may then need to reload the record immediately before updating it, which does not protect against changes that occur between that read and the update.
Return the concurrency token with the resource and require clients to preserve it until the update is submitted.
Updating the concurrency token manually when using SQL Server rowversion
SQL Server generates rowversion values automatically. The application should not assign a new value to a rowversion property.
Use the database-generated value returned after saving the entity.
Using only application-level checks
Checking whether a record changed before calling SaveChangesAsync is not enough.
Another transaction can update the record after the check but before the update executes. This creates another race condition.
The database update must include the original concurrency token, and the database must enforce the comparison atomically.
Automatically retrying every concurrency exception
Retrying a failed update with the latest database version may seem convenient, but it can overwrite another user's changes.
Retry only when the business operation is safe to repeat and the application has a clear conflict-resolution strategy.
Using the InMemory provider for relational concurrency tests
The EF Core InMemory provider is useful for some isolated tests, but it does not behave like a relational database and does not reproduce SQL Server rowversion behavior.
Use SQL Server or an appropriate relational test database when verifying database-generated concurrency tokens.
Best Practices
Use optimistic concurrency for records that may be edited by multiple users.
Use SQL Server rowversion when working with SQL Server and database-generated version tracking is appropriate.
Return the concurrency token when retrieving a resource and require the client to send the original version during updates.
Use database constraints and concurrency tokens instead of relying only on application-level checks.
Return HTTP 409 for general update conflicts or HTTP 412 when using failed HTTP preconditions such as If-Match.
Provide the latest database values when they help clients resolve conflicts.
Avoid automatically overwriting newer data without a clear business rule.
Use separate DbContext instances in concurrency tests.
Test with the same type of relational database behavior used in production.
Keep concurrency handling consistent across controllers, services, and repository operations.
Conclusion
Optimistic concurrency control helps ASP.NET Core applications prevent one user's changes from silently overwriting another user's updates. Instead of locking records while users edit them, the application checks whether the original data version is still current when the update is submitted.
Entity Framework Core provides built-in concurrency support through concurrency tokens. SQL Server rowversion is a convenient option because the database automatically generates a new value whenever a row changes.
For a complete implementation, return the concurrency token to the client, require it during updates, handle DbUpdateConcurrencyException, and provide a clear conflict response. ETags and If-Match headers offer another approach when the API needs to use standard HTTP conditional request behavior.
By implementing optimistic concurrency correctly and testing it with separate database contexts, developers can build applications that protect shared data and handle simultaneous updates more reliably.
Join the conversation! Your thoughts help the community grow.