Two users editing the same row at the same time is the classic lost update problem: both read the row, both change it, and the last save silently overwrites the first user's change. There are two main strategies. Optimistic concurrency (most common for business applications) - Assume conflicts are rare. Do not lock while users edit; detect conflicts at save time using a version column. - SQL Server: add a rowversion column; EF Core: public class Customer { public int Id { get; set; } public string Name { get; set; } = ""; [Timestamp] public byte[] RowVersion { get; set; } = []; } - The update includes the original version in the WHERE clause: UPDATE Customers SET Name = @name WHERE Id = @id AND RowVersion = @originalVersion - If another user saved first, no rows are updated and EF Core throws DbUpdateConcurrencyException. - The API returns 409 Conflict (or 412 when using ETag and If-Match headers), and the UI shows the latest values and lets the user reload, overwrite or merge. try { await db.SaveChangesAsync(ct); } catch (DbUpdateConcurrencyException) { return Conflict(new { message = "This record was changed by someone else. Please reload." }); } Pessimistic concurrency - Assume conflicts are likely; lock the row when reading for update so others must wait. - SQL Server: SELECT ... FROM Customers WITH (UPDLOCK, ROWLOCK) WHERE Id = @id inside a transaction; or SELECT ... FOR UPDATE in PostgreSQL and MySQL. - Locks must be held only for the duration of a short database transaction — never while a user is thinking on a screen. For long "checkout" style edits, use an application-level lock with expiry (a "being edited by X" flag). When to use which Optimistic: - Low to moderate contention, typical forms and CRUD screens, web applications with stateless requests, and high scalability needs (no locks held). - When retrying or asking the user to resolve conflicts is acceptable. Pessimistic: - High contention on the same rows (inventory counters during flash sales, seat booking, sequential number generation), or when retries are expensive or unacceptable. - Short critical sections inside the server where correctness is essential. - Trade-offs: blocking, reduced throughput and possible deadlocks. Other useful technique - Atomic conditional updates for counters and state transitions avoid both read-then-write races and long locks: UPDATE Seats SET Available = Available - 1 WHERE SlotId = @id AND Available > 0; Summary: "For a user editing the name X, I would use optimistic concurrency with a rowversion and handle the 409 in the UI. I would use pessimistic locking only for short, high-contention operations where conflicts are frequent."
Ravindra Wadile · · 0 likes