Database Management Redis Subjective
Oct 05, 2025

How do Redis transactions work with MULTI/EXEC?

Detailed Explanation
Redis transactions group commands for atomic execution: **Basic Transaction:** MULTI SET account:1 100 SET account:2 200 DECRBY account:1 50 INCRBY account:2 50 EXEC **With WATCH (Optimistic Locking):** WATCH account:1 account:2 MULTI DECRBY account:1 50 INCRBY account:2 50 EXEC # Returns null if watched keys changed **Python Example:** import redis r = redis.Redis() # Basic transaction pipe = r.pipeline() pipe.multi() pipe.set('key1', 'value1') pipe.set('key2', 'value2') pipe.incr('counter') results = pipe.execute() # With watch with r.pipeline() as pipe: while True: try: pipe.watch('balance') current_balance = int(pipe.get('balance') or 0) if current_balance >= 100: pipe.multi() pipe.decrby('balance', 100) pipe.incr('purchases') pipe.execute() break else: pipe.unwatch() raise ValueError("Insufficient balance") except redis.WatchError: # Retry if key was modified continue **Key Points:** • All commands queued, executed atomically • WATCH provides optimistic concurrency control • DISCARD cancels transaction • Commands don't see intermediate results
Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback