Hacker News new | ask | show | jobs
by taspeotis 3115 days ago
> we haven't yet come across an elegant (and not too over-engineered) way to replace this.

It's built into some RDBMS. SQL Server has READPAST [1, 2], so you can do:

    BEGIN TRANSACTION;
    DELETE TOP (1) QueueTable WITH (READPAST) OUTPUT deleted.* ORDER BY QueueId;
    -- Do your work
    COMMIT TRANSACTION;
And if your process dies midway through, the transaction is rolled back and the row is immediately visible to another worker.

[1] https://docs.microsoft.com/en-us/sql/t-sql/queries/hints-tra... READPAST is primarily used to reduce locking contention when implementing a work queue that uses a SQL Server table. A queue reader that uses READPAST skips past queue entries locked by other transactions to the next available queue entry, without having to wait until the other transactions release their locks.

[2] https://docs.microsoft.com/en-us/sql/t-sql/queries/output-cl...

1 comments

Also known as SKIP LOCKED (Oracle, PostgreSQL, MySQL).