Redis Transactions

Redis transactions allow executing multiple commands as a single unit. This lesson covers transaction usage and caveats.

What is a Transaction?

A transaction is a collection of commands that are executed sequentially without interruption by other commands.

MULTI → Command 1 → Command 2 → Command 3 → EXEC

Basic Commands

MULTI: Start a Transaction

REDIS
MULTI
OK

EXEC: Execute the Transaction

REDIS
MULTI
OK

SET name "Alice"
QUEUED

SET age 25
QUEUED

EXEC
1) OK
2) OK

DISCARD: Cancel the Transaction

REDIS
MULTI
OK

SET name "Bob"
QUEUED

DISCARD
OK

Transaction Properties

Command Queue

Commands in a transaction are not executed immediately but placed in a queue:

REDIS
MULTI
OK

SET a 1
QUEUED

SET b 2
QUEUED

GET a
QUEUED

EXEC
1) OK
2) OK
3) "1"

Atomicity

Commands in a transaction are either all executed or none executed:

REDIS
MULTI
OK

SET a 1
QUEUED

SET b 2
QUEUED

EXEC
1) OK
2) OK
⚠️ Note: Redis transactions do not support rollback. If a command fails within a transaction, other commands still execute.

WATCH: Optimistic Locking

WATCH monitors keys. If any watched key is modified before the transaction executes, the transaction is canceled.

Basic Usage

REDIS
# Watch a key
WATCH mykey
OK

# Start a transaction
MULTI
OK

# Modify the key
SET mykey "new_value"
QUEUED

# Execute the transaction
EXEC
(nil)  # Returns nil if the transaction was canceled (key was modified)

Implementing Optimistic Locking

Example: Optimistic Lock

BASH
# Client 1
WATCH balance
GET balance
MULTI
SET balance 900
EXEC

# Client 2 (before Client 1 executes EXEC)
SET balance 800
▶ Try it Yourself

Use Cases

1. Inventory Deduction

Example: Decrease Stock

BASH
# Decrease stock (atomic operation)
MULTI
DECR stock:product:123
INCR sold:product:123
EXEC
▶ Try it Yourself

2. Money Transfer

Example: Transfer

BASH
# Transfer: send 100 from user A to user B
MULTI
DECRBY balance:user:a 100
INCRBY balance:user:b 100
EXEC
▶ Try it Yourself

3. Batch Operations

Example: Batch Set

BASH
# Set multiple keys
MULTI
SET user:1:name "Alice"
SET user:1:age 25
SET user:1:email "alice@example.com"
EXEC
▶ Try it Yourself

Transactions vs Scripts

Lua scripts are more powerful than transactions, supporting conditional logic and loops:

REDIS
# Atomic operation: deduct only if balance is sufficient
EVAL "
  local balance = tonumber(redis.call('GET', KEYS[1]) or 0)
  if balance >= tonumber(ARGV[1]) then
    redis.call('DECRBY', KEYS[1], ARGV[1])
    return 1
  else
    return 0
  end
" 1 balance:user:a 100

Transaction vs Script Comparison

Feature Transaction Lua Script
Atomicity
Conditional logic
Loops
Performance Good Better
Complexity Simple More complex

Important Notes

⚠️ No rollback: Redis transactions do not support rollback. If a command fails, other commands still execute.

⚠️ Command errors: Syntax errors cancel the entire transaction. Runtime errors do not affect other commands.

💡 Lua scripts recommended: For complex atomic operations, Lua scripts are recommended.

❓ FAQ

Q Do Redis transactions support rollback?
A No. Redis transactions do not support rollback. Use Lua scripts if you need rollback behavior.
Q What does WATCH do?
A WATCH implements optimistic locking. It monitors keys and cancels the transaction if any watched key is modified.
Q Are commands in a transaction executed atomically?
A Yes. Commands in a transaction are executed sequentially without interruption by other commands.

📖 Summary

📝 Exercises

  1. Transaction practice: Use MULTI/EXEC to execute multiple commands
  2. Optimistic lock practice: Use WATCH to implement a simple optimistic lock
  3. Lua script practice: Use EVAL to execute a Lua script

Next Lesson

In the next lesson, we will learn Redis Persistence, covering RDB and AOF persistence methods.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏