← Back to Backend, page 2

backend-0034 · Hard senior

How does pessimistic locking work in SQL (SELECT FOR UPDATE, NOWAIT, SKIP LOCKED), and how do you use it to avoid lost updates and to build a job queue?

Pessimistic locking takes the lock before the work: SELECT ... FOR UPDATE locks the selected rows until the transaction ends, so other writers wait. This prevents lost updates in read-modify-write code. NOWAIT fails at once if a row is locked, and SKIP LOCKED skips locked rows, which lets several workers take different jobs from one table without blocking each other. Keep the transaction short, lock in a consistent order, and remember that locks cost throughput.

Full answer

Read-modify-write

  • Without a lock: two sessions read counter = 5, both write 6. One increment is lost. Putting the read and write in a transaction is not enough at READ COMMITTED.
  • With SELECT counter FROM t WHERE id = 1 FOR UPDATE, the second session waits until the first commits, then reads the new value. For simple increments the best fix is still one atomic UPDATE ... SET n = n + 1.

Lock modes and options

  • FOR UPDATE: exclusive lock for rows you will change. FOR SHARE: blocks writers, allows other readers that also share.
  • NOWAIT: raise error 55P03 instead of waiting. Good for interactive requests ("this item is being edited").
  • SKIP LOCKED: ignore locked rows. This turns a table into a work queue: each worker runs SELECT ... WHERE status = 'new' ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1, processes, updates the status and commits.
  • Use lock_timeout to bound waiting.

Trade-offs

  • Pessimistic locks block other transactions and can deadlock. Keep the locked section small and in a fixed row order.
  • Never hold row locks while waiting for a user or a remote call. For long human edits use optimistic locking.
  • A queue in the database works for moderate rates. For high throughput use a broker.
javascript
const { Pool } = require('pg');
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

(async () => {
  const pool = new Pool({ max: 12 });
  const clients = await Promise.all(Array.from({ length: 10 }, () => pool.connect()));
  await clients[0].query(`DROP TABLE IF EXISTS bk34_counter; DROP TABLE IF EXISTS bk34_jobs;
    CREATE TABLE bk34_counter (id int PRIMARY KEY, n int); INSERT INTO bk34_counter VALUES (1, 0);
    CREATE TABLE bk34_jobs (id serial PRIMARY KEY, status text NOT NULL DEFAULT 'new'); INSERT INTO bk34_jobs (status) SELECT 'new' FROM generate_series(1, 5);`);
  const counter = async () => (await clients[0].query('SELECT n FROM bk34_counter')).rows[0].n;

  // Ten clients do read, wait a little, write n + 1.
  async function increment(c, lock) {
    await c.query('BEGIN');
    const { rows } = await c.query(`SELECT n FROM bk34_counter WHERE id = 1 ${lock ? 'FOR UPDATE' : ''}`);
    await sleep(30);
    await c.query('UPDATE bk34_counter SET n = $1 WHERE id = 1', [rows[0].n + 1]);
    await c.query('COMMIT');
  }
  await Promise.all(clients.map((c) => increment(c, false)));
  console.log('10 increments, no lock       : counter =', await counter(), '(updates were lost)');
  await clients[0].query('UPDATE bk34_counter SET n = 0');
  await Promise.all(clients.map((c) => increment(c, true)));
  console.log('10 increments, FOR UPDATE    : counter =', await counter());

  // NOWAIT: fail fast when somebody holds the row.
  await clients[0].query('BEGIN'); await clients[0].query('SELECT * FROM bk34_counter WHERE id = 1 FOR UPDATE');
  const nowait = await clients[1].query('SELECT * FROM bk34_counter WHERE id = 1 FOR UPDATE NOWAIT').catch((e) => e.code);
  console.log('NOWAIT on a locked row       :', nowait);
  await clients[0].query('ROLLBACK');

  // SKIP LOCKED: five workers take five different jobs at the same time.
  const taken = await Promise.all(clients.slice(0, 5).map(async (c) => {
    await c.query('BEGIN');
    const { rows } = await c.query("SELECT id FROM bk34_jobs WHERE status = 'new' ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1");
    await sleep(30);                                                   // the job is processed while the row is locked
    await c.query("UPDATE bk34_jobs SET status = 'done' WHERE id = $1", [rows[0].id]);
    await c.query('COMMIT');
    return rows[0].id;
  }));
  console.log('SKIP LOCKED, 5 workers got   :', taken.sort((x, y) => x - y).join(', '), '(each job once)');

  await clients[0].query('DROP TABLE bk34_counter; DROP TABLE bk34_jobs');
  clients.forEach((c) => c.release());
  await pool.end();
})();

Ten pooled connections run at the same time against the local PostgreSQL. The sleeps force the overlap that causes the lost updates, so the result without a lock is below ten every time. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): 10 increments, no lock : counter = 1 (updates were lost) 10 increments, FOR UPDATE : counter = 10 NOWAIT on a locked row : 55P03 SKIP LOCKED, 5 workers got : 1, 2, 3, 4, 5 (each job once)

Key points

  • FOR UPDATE locks rows until commit or rollback.
  • It prevents lost updates in read-modify-write code.
  • NOWAIT fails fast; SKIP LOCKED lets workers share a queue.
  • Keep locked sections short and in a fixed order.
  • Prefer an atomic UPDATE when it is enough.

Common mistakes

  • Holding FOR UPDATE locks during slow external calls.
  • Locking rows in different orders.
  • Using FOR UPDATE where an atomic UPDATE would do.
  • A polling queue table without SKIP LOCKED, so workers block each other.
  • Using database queues at rates where a broker is needed.

Follow-ups

  • What is the difference between FOR UPDATE and FOR NO KEY UPDATE?
  • How do advisory locks differ from row locks?
  • How do you stop a worker's job from being lost if it crashes?

Tips

  • Contrast with optimistic locking.
  • Name the three options.
  • Describe the job queue.