Managing Transactions
1. Starting Transactions
| Command | Description |
|---|---|
MULTI | Begin transaction; subsequent commands queue |
2. Executing Transactions
| Command | Returns |
|---|---|
EXEC | Array of replies, or nil if WATCH key changed |
3. Discarding Transactions
| Command | Description |
|---|---|
DISCARD | Abort queued commands; clears WATCH |
4. Watching Keys
| Command | Description |
|---|---|
WATCH key [key ...] | Mark keys for CAS; EXEC aborts if any modified |
5. Unwatching Keys
| Command | Description |
|---|---|
UNWATCH | Clear all WATCHed keys (auto on EXEC/DISCARD) |
6. Understanding Atomicity Guarantees
| Property | Guarantee |
|---|---|
| Isolation | No other client interleaves between queued commands |
| Atomicity | All or none (subject to WATCH) |
| Durability | Depends 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
| Step | Action |
|---|---|
| 1 | WATCH key |
| 2 | Read state |
| 3 | MULTI + queued writes |
| 4 | EXEC; retry on nil |
9. Handling Transaction Errors
| Error Type | Behavior |
|---|---|
| Queue-time syntax error | EXEC fails; nothing runs |
| Run-time error | Other 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.
| Reason | Detail |
|---|---|
| Simplicity | Errors usually mean programming bugs |
| Performance | No undo log overhead |