Database / REDIS
How does Redis handle atomicity for multi-key operations?
A single Redis command, even one touching multiple keys (like MSET or SUNIONSTORE), is always atomic on its own — because command execution is single-threaded, nothing else can run in the middle of it. The harder case is atomicity across a sequence of separate commands, where Redis offers a few different tools depending on what's actually needed.
| Tool | Use When |
| MULTI/EXEC | A fixed, known sequence of commands needs to run uninterrupted. |
| WATCH + MULTI/EXEC | The sequence depends on first reading a value (check-then-act), needing optimistic locking. |
| Lua scripting (EVAL) | Complex conditional logic across multiple keys needs to run as one atomic unit, including branching not expressible as a flat command list. |
Lua scripts are the most powerful option here: the entire script executes as a single atomic step from Redis's perspective, with no other command interleaved anywhere in the middle, which lets you express logic (loops, conditionals, computed values feeding into further commands) that plain MULTI/EXEC can't, since MULTI/EXEC only queues a fixed list without letting one command's result influence the next command in the same transaction.
More Related questions...
