brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: MySQL FOR UPDATE SKIP LOCKED lets workers grab different rows

Mysql
~/tips/tip-mysql-select-for-update-skip-locked

FOR UPDATE SKIP LOCKED;

Makes a locking read skip rows that another transaction has locked, instead of waiting.

A table used as a job queue has an annoying habit: two workers ask for the next job, and one of them sits there waiting for the other’s row lock. MySQL has a modifier that removes the waiting.

START TRANSACTION;
SELECT id, payload FROM jobs
WHERE status = 'pending'
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED;
UPDATE jobs SET status = 'processing' WHERE id = 42;
COMMIT;

Normally a locking read waits when another transaction holds a lock on a row it wants. With SKIP LOCKED it never waits. Rows that are locked are silently left out of the result, so each worker running this query gets a different job. The id in the UPDATE is the one the SELECT returned.

The sibling option is NOWAIT. It also refuses to wait, but it fails with an error (3572, “Do not wait for lock”) instead of skipping. For a queue, skipping is what you want.

Caveats, straight from the manual: results of a SKIP LOCKED query are an inconsistent view of the data, so it is for work queues and not for reports. Both options only work on row-level locks, inside a transaction (autocommit off), and they are unsafe for statement-based replication. They go with FOR UPDATE or FOR SHARE, not the older LOCK IN SHARE MODE. Support starts in MySQL 8.0.

Further reading: MySQL locking reads: NOWAIT and SKIP LOCKED

More Mysql tips mysql_config_editor set --login-path=shop \ SET PERSIST max_connections = 300; ALTER TABLE orders ADD COLUMN note VARCHAR(100), ALGORITHM=INSTANT; ALTER USER 'appuser'@'192.0.2.10' SELECT * FROM sys.schema_unused_indexes All Mysql tips (8) All topics

Link