Redis Transactions
Redis transactions enable the execution of multiple commands as a single atomic operation. Commands are queued and executed sequentially without interruption.
MULTI
SET user:name "alice"
INCR user:visits
GET user:name
EXEC
Transaction Behavior
Syntax errors during queueing abort the entire transaction. Runtime errors during execution skip the faulty command but proceed with others, requiring manual rollback for atomicity.
MULTI
SET counter 100
INCRBY counter "invalid" // Runtime error; skipped during EXEC
EXEC // Returns OK for SET, error for INCRBY
Locking Mechanisms
Optimistic Locking with WATCH
WATCH monitors keys for changes before transaction execution. If a watched key is modified, the transaction is aborted.
WATCH inventory:item123
MULTI
DECR inventory:item123
EXEC // Aborts if inventory:item123 changed after WATCH
Distributed Locking with SETNX
SETNX creates a mutual exclusion lock. Combined with EXPIRE, it ensures locks are released even after client failures.
SETNX lock:resource "owner" // Returns 1 if lock acquired
EXPIRE lock:resource 30 // Auto-release after 30 seconds
// Perform critical operation
DEL lock:resource // Manual release
Data Expiration Strategies
Redis employs three strategies to remove expired keys:
- Timed Deletion: Immediate removal upon expiration. CPU-intensive.
- Lazy Deletion: Removal upon key access. Memory-intensive.
- Periodic Deletion: Scheduled scans balancing CPU and memory usage.
Expiration times are stored in a dedicated dictionary, and periodic deletion uses randomized sampling to limit CPU impact.
Memory Eviction Policies
When memory limits are exceeded, Redis evicts keys using policies configurable via maxmemory-policy:
- volatile-lru: Evict least recently used expired keys
- allkeys-lfu: Evict least frequently used keys
- noeviction: Reject new writes (default)
Eviction success depends on available candidates and policy effectiveness.
Key Configuration Parameters
maxmemory 2gb
maxmemory-policy volatile-lru
maxmemory-samples 5
loglevel notice
timeout 300