Preventing overselling and double booking in SQL Server: atomic conditional UPDATE with @@ROWCOUNT, CHECK constraints, unique constraints and filtered unique indexes for slots, serializable or UPDLOCK/HOLDLOCK range checks for overlapping intervals, and idempotent retries from .NET.
Overselling comes from check-then-act: read stock, decide in code, then write, with another request in between. Make the decision and the write one atomic statement: UPDATE Stock SET Quantity -= @n WHERE ProductId = @id AND Quantity >= @n and check @@ROWCOUNT; 0 means sold out. Back it with CHECK (Quantity >= 0).
For discrete slots (seat 14C, the 10:00 appointment) a unique constraint on the slot is simplest: the second insert fails with 2627/2601. For overlapping intervals (a room from 2 pm to 4 pm) there is no single key, so check and insert in one transaction with UPDLOCK, HOLDLOCK (serializable range locks) on an indexed range.
Trade-off: constraints are the strongest and cheapest; range locks are correct but can deadlock, so retry idempotently.
"The root cause is almost always the same: the app reads the stock, checks it in C#, and writes back, and under load two requests both see 'one left'. Read committed doesn't prevent that and neither does RCSI. So the rule I follow is to push the decision into the database, either as a single atomic statement or as a constraint.
For a counter like stock, I write one conditional update:
UPDATE Stock SET Quantity = Quantity - @n WHERE ProductId = @id AND Quantity >= @n, and then check rows affected. SQL Server takes the U and X locks on that row, so two concurrent updates are serialised and the second sees the new quantity. If it affects zero rows, it's sold out. I add aCHECK (Quantity >= 0)as a backstop so a future bug can't go negative. For example, at [company] a flash sale oversold [N] units in [minutes] because of a read-then-write in the service; switching to the conditional update fixed it with no other changes, and it was faster because it was one round trip.For booking discrete things, seats or fixed time slots, a unique constraint is the cleanest:
UNIQUE (EventId, SeatId), and I translate error 2627 or 2601 into 'seat taken'. If cancelled bookings stay in the table, I use a filtered unique index on active rows only. The hard case is overlapping intervals, like room bookings with arbitrary start and end times, because there's no single key to make unique. There I check for overlaps and insert in one transaction withUPDLOCK, HOLDLOCKon the range query, backed by an index on (RoomId, StartsAt), so SQL Server takes key-range locks and a competing insert waits. That can deadlock under contention, so the caller retries 1205, and the request carries an idempotency key. The mistake I see is fixing this with a C#lockor a distributed lock in Redis: the database is the source of truth, so the invariant belongs there."
| Problem | Technique | Failure signal |
|---|---|---|
| Counter (stock, seats left, credit) | Atomic conditional UPDATE + CHECK |
@@ROWCOUNT = 0 |
| Discrete slot (seat, fixed appointment) | Unique constraint / filtered unique index | Error 2627 / 2601 |
| Overlapping intervals | UPDLOCK, HOLDLOCK range check + insert |
Overlap found; 1205 deadlock to retry |
| Multi-step checkout | Reservation row with expiry, then confirm | Reservation expired |
| Attempt | Problem |
|---|---|
C# lock |
Only one process; you run several instances |
| Redis distributed lock | Not atomic with the database write; lock expiry races |
| Serializable for the whole app | Deadlocks everywhere |
SELECT then UPDATE in a transaction at read committed |
S locks are released after the read; still races |
A ticketing system used a unique index on (EventId, SeatId) where Status <> 'Cancelled' for seated events and a conditional update for general-admission counts. During an on-sale of [20,000] tickets in [6] minutes it sold exactly the capacity, with [about 3%] of attempts receiving 'just sold' responses instead of oversells.
Checks that the candidate can write T-SQL that is correct under concurrency and picks the cheapest technique that enforces the invariant.
Green flags
UPDATE and checks @@ROWCOUNTUPDLOCK, HOLDLOCK with an index for intervalsRed flags
Request A: SELECT Quantity -> 1 Request B: SELECT Quantity -> 1
Request A: UPDATE Quantity = 0 Request B: UPDATE Quantity = 0
=> sold 2, had 1
Under read committed, the S lock from the SELECT is released straight away. Under RCSI there's no S lock at all. Nothing connects the read to the later write.
A single UPDATE reads and writes the row under a U lock converting to X. A second concurrent UPDATE on the same row waits on the U lock, then re-evaluates the predicate against the committed value. With RCSI it still re-reads the current committed row for updates, so the pattern stays correct. The predicate Quantity >= @n is the business rule.
CHECK (Quantity >= 0) makes overselling impossible even if someone writes a bad update later.UNIQUE (EventId, SeatId) uses a unique index; concurrent inserts of the same key are serialised by key locks and the loser gets 2627 (constraint) or 2601 (unique index).CREATE UNIQUE INDEX ... WHERE Status IN ('Held','Confirmed'). Remember filtered indexes need the right SET options (ANSI_NULLS, QUOTED_IDENTIFIER on), which SqlClient sets by default.Two intervals overlap when existing.Start < new.End AND existing.End > new.Start. With UPDLOCK, HOLDLOCK (serializable) on the SELECT, SQL Server takes key-range locks covering the rows and gaps it scanned in IX_Bookings_Room_Start. A competing transaction for the same room requesting the same range waits until the first commits, then sees its row. Without an index the scan covers the whole table and the range locks serialise all bookings.
Common gotcha: StartsAt < @end with an index on (RoomId, StartsAt) locks every earlier booking for that room. Bound it with StartsAt > DATEADD(hour, -@maxDurationHours, @start) so the range is small.
Checkout often needs payment between 'hold' and 'confirm'. Insert a reservation row (atomic decrement or unique slot) with ExpiresAt, confirm it after payment, and release expired holds with a background job. This keeps transactions short and never holds locks during payment.
Map @@ROWCOUNT = 0 and SQL errors 2627/2601 to a domain result (409 Conflict), not an exception page. Retry 1205 with backoff. Use an idempotency key so a retried request after a timeout doesn't book twice.
UPDLOCK, HOLDLOCK and inspect sys.dm_tran_locks for RangeS-U locks.Schema and the three patterns.
CREATE TABLE dbo.Stock (
ProductId int PRIMARY KEY,
Quantity int NOT NULL CONSTRAINT CK_Stock_NonNegative CHECK (Quantity >= 0));
CREATE TABLE dbo.SeatBookings (
BookingId bigint IDENTITY PRIMARY KEY,
EventId int NOT NULL,
SeatId varchar(8) NOT NULL,
Status varchar(10) NOT NULL CHECK (Status IN ('Held','Confirmed','Cancelled')),
IdempotencyKey uniqueidentifier NOT NULL UNIQUE);
-- Only one active booking per seat; cancelled rows stay for history
CREATE UNIQUE INDEX UX_SeatBookings_Active ON dbo.SeatBookings (EventId, SeatId)
WHERE Status IN ('Held','Confirmed');
CREATE TABLE dbo.RoomBookings (
BookingId bigint IDENTITY PRIMARY KEY,
RoomId int NOT NULL,
StartsAt datetime2(0) NOT NULL,
EndsAt datetime2(0) NOT NULL,
CONSTRAINT CK_RoomBookings_Range CHECK (EndsAt > StartsAt AND DATEDIFF(hour, StartsAt, EndsAt) <= 12));
CREATE INDEX IX_RoomBookings_Room_Start ON dbo.RoomBookings (RoomId, StartsAt) INCLUDE (EndsAt);
GO
-- 1. Counter: one atomic statement
CREATE OR ALTER PROCEDURE dbo.ReserveStock @ProductId int, @Qty int
AS
SET NOCOUNT ON;
UPDATE dbo.Stock SET Quantity -= @Qty
WHERE ProductId = @ProductId AND Quantity >= @Qty;
SELECT CAST(@@ROWCOUNT AS bit) AS Reserved; -- 0 = sold out
GO
-- 2. Discrete slot: just insert; the filtered unique index decides
-- INSERT dbo.SeatBookings (EventId, SeatId, Status, IdempotencyKey) VALUES (@e, @s, 'Held', @k);
-- error 2601 => seat already taken
-- 3. Intervals: range-locked check and insert in one transaction
CREATE OR ALTER PROCEDURE dbo.BookRoom @RoomId int, @StartsAt datetime2(0), @EndsAt datetime2(0)
AS
SET NOCOUNT ON;
SET XACT_ABORT ON;
BEGIN TRAN;
IF EXISTS (
SELECT 1 FROM dbo.RoomBookings WITH (UPDLOCK, HOLDLOCK)
WHERE RoomId = @RoomId
AND StartsAt > DATEADD(hour, -12, @StartsAt) -- bounded by the max duration: small range lock
AND StartsAt < @EndsAt
AND EndsAt > @StartsAt)
BEGIN
ROLLBACK;
SELECT CAST(0 AS bit) AS Booked;
RETURN;
END
INSERT dbo.RoomBookings (RoomId, StartsAt, EndsAt) VALUES (@RoomId, @StartsAt, @EndsAt);
COMMIT;
SELECT CAST(1 AS bit) AS Booked;
Calling it from .NET with Dapper and mapping the outcomes:
namespace Ticketing.Data;
using System.Data;
using Dapper;
using Microsoft.Data.SqlClient;
public enum SeatResult { Booked, Taken }
public sealed class SeatBookingStore(string connectionString)
{
public async Task<SeatResult> HoldSeatAsync(int eventId, string seatId, Guid idempotencyKey, CancellationToken ct)
{
await using var conn = new SqlConnection(connectionString);
try
{
await conn.ExecuteAsync(new CommandDefinition(
"INSERT dbo.SeatBookings (EventId, SeatId, Status, IdempotencyKey) VALUES (@eventId, @seatId, 'Held', @idempotencyKey);",
new { eventId, seatId = new DbString { Value = seatId, IsAnsi = true, Length = 8 }, idempotencyKey },
cancellationToken: ct));
return SeatResult.Booked;
}
catch (SqlException ex) when (ex.Number is 2601 or 2627)
{
// Either the seat is taken, or this exact request already succeeded (idempotency key).
var mine = await conn.ExecuteScalarAsync<int>(new CommandDefinition(
"SELECT COUNT(*) FROM dbo.SeatBookings WHERE IdempotencyKey = @idempotencyKey;",
new { idempotencyKey }, cancellationToken: ct));
return mine == 1 ? SeatResult.Booked : SeatResult.Taken;
}
}
}
UPDATE and check rows affected.UPDLOCK, HOLDLOCK on the read.lock or SemaphoreSlim. Why it is wrong: It doesn't span instances or other writers. Instead: Put the invariant in the database.The senior instinct is 'make the database enforce the invariant': a constraint first, an atomic statement second, explicit range locking only when the rule can't be expressed either way. It is also worth naming the product decision: under a flash sale, some users will lose the race; the system must say so quickly and never oversell.
| Technique | When it fits | Cost | When not to |
|---|---|---|---|
| Unique / filtered unique index | Discrete, enumerable slots | One index | Arbitrary intervals |
Atomic conditional UPDATE |
Counters and state transitions | None beyond the write | Rules spanning several rows |
UPDLOCK, HOLDLOCK range check |
Overlapping intervals | Range locks, deadlocks, retries | Hot ranges at very high concurrency (consider slot tables) |
| Slot table (pre-generated time slots) | Fixed-granularity bookings at scale | Many rows, generation job | Truly arbitrary durations |
Key-range locks protect the gap between index keys so no other session can insert a row that would change the result of a range read. They appear only under SERIALIZABLE (or the HOLDLOCK hint). Modes such as RangeS-S, RangeS-U and RangeI-N combine a range part and a key part. They prevent phantoms and make upserts safe, but they need a suitable index (otherwise far more is locked), increase blocking, and are a common cause of deadlocks.
A race condition is a bug where the result depends on the timing of concurrent operations. Classic forms are read-modify-write (count++ from two threads), check-then-act (if (!dict.ContainsKey(k)) dict.Add(k, v)), and unsafe publication. In .NET they also appear with non-thread-safe collections (a shared Dictionary or List corrupted under concurrent writes), in async code that interleaves at await points even on one thread, and in databases as lost updates when two requests read, modify and save the same row. Fixes: atomic operations, locks, concurrent collections, immutability, single-writer designs, and in databases optimistic concurrency tokens, unique constraints and idempotency.
Isolation levels decide which anomalies a transaction can see. Read uncommitted takes no shared locks, so dirty reads are possible (it's what NOLOCK does). Read committed, the default, only reads committed data, using short-lived S locks, or row versions when RCSI is on, but a re-read can change (non-repeatable read). Repeatable read holds S locks to the end of the transaction, so rows you read can't change, but new rows can appear (phantoms). Serializable adds key-range locks so ranges can't change either. Snapshot gives a transaction-consistent view from row versions.
The trade-off: each step up holds more locks for longer, which means more blocking and deadlocks. Pick the lowest level that is correct, and solve specific races with targeted locks or constraints.
How to tell it (STAR)
**S:** In a flash sale of [500] units, we sold [N] more than we had and had to refund customers. **T:** I had to make sure the next sale could not oversell. **A:** I reproduced it with a load test: our service read the stock, checked it in C#, and wrote it back, so concurrent requests all saw stock available. I replaced it with one conditional UPDATE that only decrements when enough stock remains and checks rows affected, added a CHECK constraint as a backstop, and made the API return a clear 'sold out'. **R:** The next sale of [N] units sold exactly the capacity, with [0] oversells, and the endpoint got faster because it went from [3] round trips to [1].
Last updated 23 Nov 2026.