Skip to content

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

  1. Strings: Simple key-value pairs.
  2. Lists: Ordered collections of strings (perfect for queues).
  3. Sets: Unordered collections of unique strings.
  4. Hashes: Maps between string fields and string values.
  5. Sorted Sets: Sets where every member is associated with a score (great for leaderboards).
  6. 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.