Claim work safely from a shared queue
Use one atomic update with locking hints and OUTPUT to claim one ordered queue row per worker.
What you are trying to do
Use SQL Server in a dedicated scratch database with READ_COMMITTED_SNAPSHOT off for this lab, a shared instructor-seeded queue table, and two worker sessions. The shared table and concurrent timing make a pasted script unsafe, so sql is empty.
Work through it
- Confirm the queue has at least two ready rows and a stable order key such as
EnqueuedAt, JobId. Record the database's READ_COMMITTED_SNAPSHOT setting without changing it. - In each worker session, run the same single-statement pattern: a CTE selects
TOP (1)ready row withUPDLOCK, READPAST, ROWLOCK, ordered by the queue keys. An UPDATE changes that row to claimed and usesOUTPUT inserted.JobIdto return the claim. - Start both workers close together. Compare returned IDs and the persisted queue state. Each worker must claim a different row when two are available.
- Repeat with an empty queue and verify that OUTPUT returns no row. Check how cancellation and transaction rollback affect a claim before designing a real worker.
- Treat
ROWLOCKas a request, not a guarantee. If the database uses row versioning, validate the documentedREADPASTrestrictions and required locking hint for that configuration. - Use Microsoft's table-hint reference for the supported combinations and restrictions. Table hints
Check your work
The two-session run returns distinct job IDs when two rows are ready, and each returned row is marked claimed. The empty-queue run returns no claim. The learner names the isolation and database option assumptions used by the test.
Knowledge check
Commands in this lesson
Next lesson Recover a failed transaction safely