intermediateLocking — Optimistic vs Pessimistic

An e-commerce site has a flash sale — 1000 users trying to buy the last item simultaneously. Which locking strategy do you use?

Pessimistic locking is appropriate here — high-conflict scenario (1000 users competing for 1 item). Implementation: BEGIN; SELECT * FROM inventory WHERE product_id = 42 FOR UPDATE NOWAIT; -- Check: if 0 stock, ROLLBACK and return 'sold out'; -- If stock > 0: UPDATE inventory SET stock = stock - 1 WHERE product_id = 42; INSERT INTO orders ...; COMMIT; Use NOWAIT to fail fast rather than queuing 999

This is a Pro chapter

Sign in, then upgrade to Pro or Power to unlock this and the full Databases Mastery library.

An e-commerce site has a flash sale — 1000 users trying to buy the last item simultaneously. Which locking strategy do you use?

Next Step

Continue to What is the difference between ROW_NUMBER(), RANK(), and DENSE_RANK()?← Back to all SQL questions