SERIALIZABLE Transactions Retry On Conflicts

Run SERIALIZABLE transactions that can fail with SQLSTATE 40001, and retry the whole unit of work on serialization conflicts.

SqlResilience

Code

snippet
-- SERIALIZABLE:最严格隔离级别,冲突时返回 SQLSTATE 40001
SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SHOW transaction_isolation;

-- 一个读取并写回余额的事务
BEGIN;
SELECT balance FROM accounts WHERE id = 1;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;

-- 并发执行相同逻辑时,其中一个可能失败:
-- ERROR: could not serialize access due to read/write dependencies
-- SQLSTATE: 40001 (serialization_failure)

-- 客户端重试模板:失败后回滚并重跑整个事务
-- Retry the whole transaction on serialization conflicts
-- attempt = 0
-- loop:
--   BEGIN ISOLATION LEVEL SERIALIZABLE
--   ... 业务读写 ...
--   COMMIT
--   on serialization_failure and attempt < 3:
--     ROLLBACK; sleep; attempt += 1; retry

-- 事务内也可以显式指定隔离级别(必须是事务首条语句)
BEGIN;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SELECT balance FROM accounts WHERE id = 1;
COMMIT;

-- 对比:READ COMMITTED 不会抛 40001,但快照可能不同
SHOW default_transaction_isolation;

What the code does

Several statements share this file — SELECT / UPDATE, with accounts among the objects involved.

Mechanically, the statements are built from: a WHERE clause narrowing which rows one statement affects.

Using it

The accounts table is the working surface here.

Key statements

UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
SELECT balance FROM accounts WHERE id = 1;

Interactive Tools for This Topic

FAQ

Which relations are involved here?
`accounts`.