
Why Redis MULTI/EXEC Doesn't Roll Back: Redis vs SQL Transactions
- كاتب موثّق
- Redis 8
محتويات المقال
DECRBY and an INCRBY in a Redis transaction, and its author read "transaction" the way SQL taught them: both or neither. Mona's balance had been written as 250.5 by an old import script. In a test on Redis 8.4 with StackExchange.Redis 2.10.1, ExecuteAsync() returned true, the debit's task threw ERR value is not an integer or out of range, and the credit was applied anyway: Karim went from 40 to 140 while Mona stayed at 250.5.
The common misconception
MULTI/EXEC works like a SQL transaction, so if one command fails, everything rolls back.
MULTI and Redis refuses to run any of the commands, which looks exactly like a rollback. Redis's own docs promise that if EXEC is called, all the operations are performed. And StackExchange.Redis comments its example with "if false: it was rolled back". Each of those statements is true. None of them says that a command which fails while running takes the others down with it.
What actually happens
MULTI queues, EXEC runs everything
MULTI, Redis doesn't execute commands; it answers QUEUED and stores them. EXEC runs the whole queue, and Redis guarantees that no request from another client is served in the middle. If the connection drops before EXEC, nothing runs. So a Redis transaction gives you isolation and an all-or-nothing start. It doesn't promise an all-or-nothing result.
Two kinds of errors, two outcomes
EXEC. In the test, a DECRBY with a missing argument produced EXECABORT Transaction discarded because of previous errors., and Karim's balance stayed at 40.
WRONGTYPE or a value that isn't an integer, is different. The docs put it in bold: "even when a command fails, all the other commands in the queue are processed". EXEC returns one reply per command, with the error in its slot, and it's up to the client to look. In the hook, that slot was the debit. On why Redis doesn't undo the rest, the docs are short: "Redis does not support rollbacks of transactions since supporting rollbacks would have a significant impact on the simplicity and performance of Redis." DISCARD exists, but it only drops a queue that hasn't run yet; it isn't a .
You can't read and decide inside MULTI
GET inside MULTI returns QUEUED; its value arrives with EXEC, after every decision has been made. So "debit only if the balance is enough" can't be written inside the transaction. Redis's answer is WATCH: read the keys first, then run MULTI/EXEC, and if a watched key changed in between, EXEC returns a null reply and runs nothing. That's , the same idea as a version check in SQL. In the test, a second client changed Mona's balance between WATCH and EXEC, and EXEC returned nil with no changes applied. StackExchange.Redis shares connections between callers, so it doesn't expose WATCH directly; you add conditions with AddCondition, and ExecuteAsync() returns false when one fails. That false is the "rolled back" in its docs: nothing ran.
Scripts are atomic, not undoable
INCRBY for Karim and then DECRBY on Mona's 250.5 failed with the same error, and Karim kept the 100 points. Functions, available since Redis 7, run with the same atomic semantics, so the rule is the same: check everything, then write.
Make the transfer all-or-nothing
using StackExchange.Redis;static async Task TransferAsync( IDatabase db, string from, string to, long points){ var tx = db.CreateTransaction(); // MULTI ... EXEC var debit = tx.StringDecrementAsync(from, points); var credit = tx.StringIncrementAsync(to, points); if (!await tx.ExecuteAsync()) return; // Test: returned true await Task.WhenAll(debit, credit); // Test: the debit threw // "ERR value is not an integer or out of range" for "250.5", // yet the credit was applied: Karim 40 -> 140, Mona unchanged}using StackExchange.Redis;static async Task<bool> TransferAsync( IDatabase db, string from, string to, long points){ // Check everything before the first write: a script can't roll back const string script = """ local a = tonumber(redis.call('GET', KEYS[1])) local b = tonumber(redis.call('GET', KEYS[2]) or '0') local n = tonumber(ARGV[1]) if not a or not b or a % 1 ~= 0 or b % 1 ~= 0 or a < n then return 0 end redis.call('DECRBY', KEYS[1], n) redis.call('INCRBY', KEYS[2], n) return 1 """; var result = await db.ScriptEvaluateAsync(script, [from, to], [points]); return (int)result == 1; // Test: false for "250.5", nothing written}false for 250.5 and for a balance of 50, without touching either key, and moved the points when Mona had 250. Both key names travel in KEYS, which the docs require so scripts work in a cluster too.
MULTI/EXEC | |||
|---|---|---|---|
WATCH before MULTI | |||
ROLLBACK |
How to apply it in your project
Find every transaction and check its replies Search for MULTI,CreateTransactionand your client's equivalents. For each one, confirm the code inspects every command's result, not only the return value ofEXEC.Validate before the first write Move multi-key business rules into a script or a function that reads, checks types and limits, and only then writes. Keep it short, since it blocks the server while it runs. Use WATCH for read-then-decide logic When the decision has to happen in application code, watch the keys you read, and retry the whole read-decide-write cycle when EXECreturns null orExecuteAsync()returnsfalse.Prefer functions for shared logic Scripts sent with EVALlive in a cache that can be flushed or lost on restart or failover. Functions, loaded withFUNCTION LOADand called withFCALL, are persisted and replicated with the data.
Key takeaways
MULTI/EXECguarantees no interleaving and that queued commands start together, not that they all succeed.Queue-time errors discard the transaction; run-time errors don't, and the other commands still apply. Redis has no rollback: in the test, a failed debit still let a 100-point credit through, in both a transaction and a Lua script. Atomic means nobody sees the middle; correctness comes from checking everything before the first write. Use WATCH,SET ... IFEQor a script with checks first, and inspect every reply.
التعليقات (0)