Redis: The In-Memory Data Store
Redis: The In-Memory Data Store
Redis (Remote Dictionary Server) is an open-source, in-memory data structure store, used as a database, cache, and message broker.
π Key Data Structures
- Strings: Simple key-value pairs.
- Lists: Ordered collections of strings (perfect for queues).
- Sets: Unordered collections of unique strings.
- Hashes: Maps between string fields and string values.
- Sorted Sets: Sets where every member is associated with a score (great for leaderboards).
- Streams: Append-only log data structures (Kafka-like features).
π©οΈ Persistence Options
Redis is in-memory but offers two main persistence mechanisms:
- RDB (Redis Database): Performs point-in-time snapshots of your dataset at specified intervals.
- AOF (Append Only File): Logs every write operation received by the server. Itβs more durable but slower and results in larger files.
π· Messaging Patterns
Pub/Sub
A fire-and-forget messaging system where publishers send messages to channels, and subscribers receive them in real-time. Caveat: Messages are not stored; if a subscriber is down, they miss the message.
Streams
Introduced in Redis 5.0, Streams allow for persistent message storage, consumer groups, and acknowledgment, making it a lightweight alternative to Kafka.
π Scalability & High Availability
Redis Sentinel
Provides high availability for Redis without Cluster. It monitors masters and slaves, and performs automatic failover if a master isnβt working as expected.
Redis Cluster
Automatically shards your data across multiple Redis nodes. It provides a way to run a Redis installation where data is automatically split across multiple nodes.
π οΈ Advanced Operations: Lua Scripting
Redis allows you to run Lua scripts directly on the server. These scripts are atomicβno other script or Redis command will run while a script is executing.
-- Simple script to increment a key if it exists
if redis.call("EXISTS", KEYS[1]) == 1 then
return redis.call("INCR", KEYS[1])
else
return nil
endπ‘ Best Practice: Redlock
When using Redis as a distributed lock, use the Redlock algorithm to ensure safety across multiple independent Redis instances.