Managing Transactions

1. Starting Transactions

CommandDescription
MULTIBegin transaction; subsequent commands queue

2. Executing Transactions

CommandReturns
EXECArray of replies, or nil if WATCH key changed

Example: Atomic two-key update

MULTI
INCR account:a:balance
DECR account:b:balance
EXEC

3. Discarding Transactions

CommandDescription
DISCARDAbort queued commands; clears WATCH

4. Watching Keys

CommandDescription
WATCH key [key ...]Mark keys for CAS; EXEC aborts if any modified

5. Unwatching Keys

CommandDescription
UNWATCHClear all WATCHed keys (auto on EXEC/DISCARD)

6. Understanding Atomicity Guarantees

PropertyGuarantee
IsolationNo other client interleaves between queued commands
AtomicityAll or none (subject to WATCH)
DurabilityDepends on AOF fsync policy

7. Implementing Optimistic Locking

Example: Safe counter update with WATCH

jedis.watch("balance");
int b = Integer.parseInt(jedis.get("balance"));
Transaction t = jedis.multi();
t.set("balance", String.valueOf(b - 100));
List<Object> res = t.exec();   // null if balance changed

8. Combining with WATCH for Check-and-Set

StepAction
1WATCH key
2Read state
3MULTI + queued writes
4EXEC; retry on nil

9. Handling Transaction Errors

Error TypeBehavior
Queue-time syntax errorEXEC fails; nothing runs
Run-time errorOther commands still execute; reply contains the error

10. Understanding No Rollback Behavior

Warning: Redis transactions do NOT roll back on runtime errors. Validate types/inputs before queuing.
ReasonDetail
SimplicityErrors usually mean programming bugs
PerformanceNo undo log overhead