📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

You sell limited stock (or book seats, rooms or appointments) and under load you oversell. Write the T-SQL that prevents overselling and double booking: an atomic conditional UPDATE, a unique constraint for seat or slot booking, and serializable range locking for overlapping bookings. When do you use each?

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.

Senior Sql Advanced concurrency constraints double-booking overselling sql-server t-sql

🎯 Key points

  • Check-then-act in app code races under read committed, and RCSI reads take no locks at all
  • Atomic: UPDATE ... SET Qty -= @n WHERE Id = @id AND Qty >= @n; check @@ROWCOUNT
  • CHECK (Quantity >= 0) as a backstop
  • Discrete slots: unique constraint on (EventId, SeatId); catch 2627/2601
  • Filtered unique index for 'active' bookings only
  • Intervals: UPDLOCK, HOLDLOCK (serializable) range check with an index on the range columns
  • Retry 1205 with exponential backoff and jitter; idempotency key per request
  • Reservations with expiry for checkout flows

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 a CHECK (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 with UPDLOCK, HOLDLOCK on 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# lock or a distributed lock in Redis: the database is the source of truth, so the invariant belongs there."


Choosing the technique

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

Why the obvious fixes fail

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate can write T-SQL that is correct under concurrency and picks the cheapest technique that enforces the invariant.

Green flags

  • Writes the conditional UPDATE and checks @@ROWCOUNT
  • Uses unique or filtered unique indexes for slots
  • Uses UPDLOCK, HOLDLOCK with an index for intervals
  • Mentions retries with idempotency keys

Red flags

  • Relies on application-side checks or in-process locks
  • Thinks a transaction alone prevents the race
  • Makes the whole app serializable

📚 Learn in depth

1. Why check-then-act races

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.

2. The atomic conditional update

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.

3. Constraints as the source of truth

  • 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).
  • Filtered 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.

4. Intervals and key-range locks

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.

5. Reservations for multi-step flows

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.

6. From .NET

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.

Try it yourself

  1. Write the read-then-write version and hammer it with 50 parallel tasks in a console app; count oversells. Then switch to the conditional update.
  2. Create the filtered unique index and insert the same seat twice concurrently; catch 2601.
  3. Run two overlapping room bookings in two SSMS windows with UPDLOCK, HOLDLOCK and inspect sys.dm_tran_locks for RangeS-U locks.
  4. Remove the index on (RoomId, StartsAt) and measure how bookings for different rooms now block each other.

💻 Code

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;
        }
    }
}

⚠ Common mistakes

  • Mistake: SELECT the stock, check in C#, then UPDATE. Why it is wrong: Another request can change it between the read and the write (lost update). Instead: One conditional UPDATE and check rows affected.
  • Mistake: Wrapping read-then-write in a read committed transaction and assuming it's safe. Why it is wrong: S locks are released immediately; RCSI takes none. Instead: Atomic statement, or UPDLOCK, HOLDLOCK on the read.
  • Mistake: Using a C# lock or SemaphoreSlim. Why it is wrong: It doesn't span instances or other writers. Instead: Put the invariant in the database.
  • Mistake: A unique constraint that includes cancelled bookings. Why it is wrong: A cancelled seat can never be rebooked. Instead: A filtered unique index on active statuses.
  • Mistake: Serializable range checks without an index. Why it is wrong: The range lock covers the table and serialises unrelated bookings. Instead: Index the range columns and bound the range.
  • Mistake: No retry or idempotency. Why it is wrong: Range locks can deadlock, and a client retry after a timeout can double-book. Instead: Retry 1205 and use an idempotency key.
  • Mistake: Holding the stock lock during payment. Why it is wrong: Locks span a slow external call. Instead: Reservation with expiry, confirm after payment.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions HOLDLOCK or serializable range locks. Why: Checks understanding of the key-range locks behind the interval check.
    How to answer

    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.

  2. When: Candidate talks about race conditions in general. Why: Checks how the candidate finds races before customers do.
    How to answer

    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.

  3. When: Candidate claims a higher isolation level would fix overselling. Why: Checks which anomalies each isolation level actually prevents.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Flash sale oversells limited stock
Situation
An e-commerce site on [Azure SQL Database] ran a flash sale of [500] units of a product; [N] requests per second at the start. The service read stock, checked it in C#, then updated it.
Signals
Stock went negative in reports; [N] more orders than units; customer complaints and refunds; Application Insights showed the stock endpoint p95 jumping while CPU was fine.
Investigation
Reproduced with a k6 load test against staging: the oversell happened at around [50] concurrent requests. Reviewed the code path (read-modify-write in EF Core with no concurrency token). Confirmed with `SET STATISTICS IO` and Query Store that each order made [3] round trips to the database.
Resolution
Immediate: paused the sale and manually reconciled orders. Real fix: a single conditional `UPDATE ... WHERE Quantity >= @n` with an `@@ROWCOUNT` check (via `ExecuteUpdateAsync` in EF Core), a `CHECK (Quantity >= 0)` constraint and a 'sold out' response.
Prevention
Load test with oversell assertion before every sale; the constraint as a backstop; a code review rule that inventory changes must be single statements; alert if any stock row would violate the check (error 547 count).

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].

More in Transactions and Locking

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me