The Ultimate Redis Guide: In‑Depth Overview of Architecture, Data Types, and Advanced Features

This comprehensive Redis guide covers its role as a core component in large‑scale architectures, explains common use cases, walks through installation and configuration options, details all primary data structures with commands and examples, and explores persistence, transactions, Lua scripting, replication, Sentinel, and cluster modes.

Architect Chen
Architect Chen
Architect Chen
The Ultimate Redis Guide: In‑Depth Overview of Architecture, Data Types, and Advanced Features

Redis is an open‑source, in‑memory key‑value store written in C that also supports optional persistence. It is widely used as a fast cache, distributed lock, atomic counter, rate limiter, pub/sub system, leaderboard, shopping‑cart store, and more.

Typical Use Cases

Cache to reduce database load.

Distributed lock (most common implementation).

Atomic counters for page views, likes, etc.

Distributed rate limiting using INCR and EXPIRE.

Pub/sub messaging.

Leaderboards, shopping carts, and other ordered data.

Configuration Highlights

bind 127.0.0.1
port 6379
timeout 300
loglevel notice
databases 16
daemonize yes
logfile /usr/local/redis/redis.log
maxclients 128
maxmemory <bytes>
appendonly no
appendfilename appendonly.aof
rdbcompression yes
dbfilename dump.rdb
slaveof <masterip> <masterport>
appendfsync everysec
requirepass 123456

Data Types and Core Commands

String

SET key value

– set a key‑value pair. GET key – retrieve the value. INCR key – atomically increment an integer. DECR key – atomically decrement an integer. STRLEN key – get the length of the string. INCRBY key increment – increase by a specific amount.

Strings are ideal for counters, shared sessions, and simple distributed locks using the SET key value NX EX ttl pattern.

List

LPUSH key v1 v2 …

– push elements to the head. RPUSH key v1 v2 … – push elements to the tail. LPOP key – pop from head. RPOP key – pop from tail. LRANGE key start stop – read a range of elements. LLEN key – get list length. LREM key count value – remove elements by value. LTRIM key start stop – trim to a sub‑range. RPOPLPUSH src dst – pop from tail of src and push to head of dst.

Lists are useful for user feeds, comment streams, message queues, and stack implementations.

Set

SADD key member1 member2 …

– add members (no duplicates). SMEMBERS key – return all members. SISMEMBER key member – check membership. SCARD key – count members. SREM key member – remove a member. SRANDMEMBER key – return a random member. SPOP key – remove and return a random member.

Sets are ideal for deduplication, computing intersections/unions, and tracking unique visitors.

Sorted Set (ZSet)

ZADD key score1 member1 [score2 member2 …]

– add members with scores. ZREM key member1 member2 … – remove members. ZCARD key – number of members. ZCOUNT key min max – count members in a score range. ZRANGE key start end – get members ordered by increasing score. ZREVRANGE key start end – get members ordered by decreasing score. ZINCRBY key increment member – increment a member's score.

Sorted sets power leaderboards, ranking, and time‑sorted feeds.

Hash

HSET key field value

– set a field. HGET key field – get a field. HMSET key field1 val1 field2 val2 … – set multiple fields. HMGET key field1 field2 … – get multiple fields. HGETALL key – get all field‑value pairs. HDEL key field – delete a field. HLEN key – number of fields. HINCRBY key field increment – increment numeric field. HINCRBYFLOAT key field inc – increment float field. HSETNX key field value – set if not exists.

Hashes are perfect for representing objects such as a shopping‑cart: HSET cart:{userId} {productId} 1, HINCRBY cart:{userId} {productId} 1, HLEN cart:{userId}, HGETALL cart:{userId}.

Persistence Mechanisms

RDB – point‑in‑time snapshots stored as compact binary files.

AOF – append‑only log of every write command; provides better durability.

Hybrid – combines RDB snapshots with AOF for fast restarts and minimal data loss (default since Redis 4.0).

Transactions

Redis transactions are built with MULTI, EXEC, DISCARD, WATCH. They guarantee command ordering and isolation but do not provide automatic rollback – if a command fails, subsequent commands still run.

Lua Scripting (Redis 2.6+)

Lua scripts run atomically on the server, allowing complex multi‑key operations. Below is a simplified distributed‑lock script (lock) and its counterpart (unlock).

-- lock script
if redis.call('exists', KEYS[1]) == 0 then
    redis.call('hincrby', KEYS[1], ARGV[2], 1)
    redis.call('pexpire', KEYS[1], ARGV[1])
    return nil
else
    if redis.call('hexists', KEYS[1], ARGV[2]) == 1 then
        redis.call('hincrby', KEYS[1], ARGV[2], 1)
        redis.call('pexpire', KEYS[1], ARGV[1])
        return nil
    else
        return redis.call('pttl', KEYS[1])
    end
end
-- unlock script
if redis.call('hexists', KEYS[1], ARGV[3]) == 0 then
    return nil
end
local counter = redis.call('hincrby', KEYS[1], ARGV[3], -1)
if counter > 0 then
    redis.call('pexpire', KEYS[1], ARGV[2])
    return 0
else
    redis.call('del', KEYS[1])
    redis.call('publish', KEYS[2], ARGV[1])
    return 1
end

Replication (Master‑Slave)

Slaves replicate the master’s data. The synchronization process:

Slave sends SYNC to master.

Master creates an RDB snapshot, streams the snapshot plus queued writes.

Slave loads the snapshot and replays queued commands.

After initialization, master forwards every write to slaves.

Sentinel (High Availability)

Sentinel monitors masters and slaves, performs automatic failover when a master goes down, and updates client configurations. Multiple Sentinel instances exchange heartbeat PING messages every second.

Cluster (Sharding)

Redis Cluster shards data across up to 16,384 slots. Each node owns a subset of slots and may have replicas. Clients are routed to the node responsible for the key’s slot, enabling horizontal scaling without data duplication.

Each node maintains a slot range (0‑16383) and a cluster configuration that maps slots to node IDs. The cluster automatically rebalances slots when nodes are added or removed.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

cacheRedisPersistenceReplicationSentinelClusterData StructuresLua scripting
Architect Chen
Written by

Architect Chen

Sharing over a decade of architecture experience from Baidu, Alibaba, and Tencent.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.