Course contentsShow
← C#
Lesson 1368 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Handling Concurrent Updates

Implement optimistic locking and state merging for multi-user document collaboration.

In this lesson, you will learn how to prevent data loss in multi-user Blazor applications by implementing optimistic locking and state merging.

The Conflict Problem

When two users edit the same document simultaneously in a Blazor app, the "last-write-wins" scenario often causes one user's changes to be silently overwritten. To solve this, we use Optimistic Locking. We treat the data as if conflicts are rare, but we verify the integrity of the record before every save.

Implementing Version Tracking

To implement this, add a RowVersion (or Timestamp) property to your data model. When a user fetches a document, they receive the current version number. When they send an update back to the server, they must include that original version number.

public class Document {
    public int Id { get; set; }
    public string Content { get; set; }
    public int Version { get; set; } // Used for concurrency checks
}

On the server, your update logic checks if the version in the database matches the version submitted by the user:

public async Task<bool> UpdateDocument(Document updatedDoc) {
    var current = await _db.Documents.FindAsync(updatedDoc.Id);
    
    if (current.Version != updatedDoc.Version) {
        // CONFLICT DETECTED: The document was modified by someone else
        return false; 
    }

    current.Content = updatedDoc.Content;
    current.Version++; // Increment version
    return await _db.SaveChangesAsync() > 0;
}

State Merging

When the update returns false, instead of showing a generic error, we initiate a State Merge. We fetch the newest version from the database and compare it with the user’s unsaved local changes.

In your Blazor component, you can display a "Conflict Detected" UI that shows:

  1. The incoming server version.
  2. The user's local version.
  3. An option to "Overwrite" or "Merge and Save."

By checking the Version property rather than locking the database rows, you keep the application responsive and performant, which is critical for a smooth user experience in real-time Blazor environments.

Key Takeaway: Optimistic locking allows multiple users to edit simultaneously, using a version token to ensure that updates are rejected if the underlying data has changed since the user last fetched it.