Redis Cheatsheet Implementation: From Data Structures to Category Filtering#

Our team recently added Redis to a new project. A few junior devs kept forgetting commands. The docs are too long, CLI help is too brief. So I built a cheatsheet tool and organized Redis data structures and command categories properly.

Five Core Redis Data Structures#

Redis is fast not just because of in-memory storage, but because of its data structure design. Each type maps to specific use cases:

1. String#

The most basic type. Can store strings, integers, floats, even binary data (images, serialized objects).

# Basic operations
SET user:1 "John"
GET user:1
# "John"

# Numeric operations
SET counter 100
INCR counter  # 101
INCRBY counter 10  # 111
DECR counter  # 110

# With expiration
SETEX session:abc 3600 "token123"  # expires in 1 hour

# Set if not exists (distributed lock pattern)
SETNX lock:resource "uuid-123"  # returns 1 if successful

Internal encodings:

  • int: integer values
  • embstr: strings ≤44 bytes
  • raw: strings >44 bytes

2. Hash#

Key-value collection, ideal for storing objects. Compared to serializing the entire object as a String, Hash lets you update individual fields.

# Store user info
HSET user:1 name "John" age 30 email "john@example.com"
HGET user:1 name  # "John"
HGETALL user:1
# 1) "name"
# 2) "John"
# 3) "age"
# 4) "30"
# 5) "email"
# 6) "john@example.com"

# Increment field
HINCRBY user:1 age 1  # age → 31

# Check field existence
HEXISTS user:1 phone  # 0 (doesn't exist)

Performance tip: HGETALL is slow with many fields. Use HSCAN for iteration.

3. List#

Doubly linked list. Supports insertion/pop from both ends. Great for queues, stacks, timelines.

# Queue (FIFO)
LPUSH queue:task "task1"  # push left
RPOP queue:task  # pop right → "task1"

# Stack (LIFO)
LPUSH stack:item "a" "b" "c"
LPOP stack:item  # "c"

# Blocking pop (message queue pattern)
BLPOP queue:task 5  # wait 5 seconds, return immediately if data, nil on timeout

# View list contents
LRANGE queue:task 0 -1  # return all elements

Gotcha: LRANGE start and stop are inclusive. 0 -1 means first to last.

4. Set#

Unordered collection with automatic deduplication. Supports intersection, union, difference.

SADD tags:article:1 "redis" "database" "nosql"
SADD tags:article:2 "redis" "cache"

# Intersection (common tags)
SINTER tags:article:1 tags:article:2  # {"redis"}

# Union
SUNION tags:article:1 tags:article:2  # {"redis", "database", "nosql", "cache"}

# Difference (only in article:1)
SDIFF tags:article:1 tags:article:2  # {"database", "nosql"}

# Random lottery
SRANDMEMBER lottery:users 3  # randomly pick 3 users
SPOP lottery:users 1  # pick 1 and remove

Real-world uses: mutual friends, tagging systems, lotteries.

5. Sorted Set#

Set with scores, automatically sorted. Perfect for leaderboards, weighted queues.

# Add members
ZADD leaderboard 100 "player1" 200 "player2" 150 "player3"

# Ascending by score
ZRANGE leaderboard 0 -1 WITHSCORES
# 1) "player1"
# 2) "100"
# 3) "player3"
# 4) "150"
# 5) "player2"
# 6) "200"

# Descending ranking
ZREVRANGE leaderboard 0 9 WITHSCORES  # Top 10

# Query rank
ZRANK leaderboard "player2"  # 2 (0-indexed)
ZSCORE leaderboard "player2"  # 200

# Score range query
ZRANGEBYSCORE leaderboard 100 200  # members with score [100, 200]

Performance: Insert/delete/query are all O(log N). Uses Skip List internally.

Command Categories and Filtering#

Our cheatsheet organizes 140+ commands into 9 categories:

const categories = [
  { id: 'keys', name: 'Keys' },
  { id: 'strings', name: 'Strings' },
  { id: 'hashes', name: 'Hashes' },
  { id: 'lists', name: 'Lists' },
  { id: 'sets', name: 'Sets' },
  { id: 'sorted_sets', name: 'Sorted Sets' },
  { id: 'pubsub', name: 'Pub/Sub' },
  { id: 'transactions', name: 'Transactions' },
  { id: 'server', name: 'Server' },
]

Filtering logic:

const filteredCommands = useMemo(() => {
  return redisCommands.filter(cmd => {
    const matchesCategory = selectedCategory === 'all' || cmd.category === selectedCategory
    const matchesSearch = !searchQuery ||
      cmd.command.toLowerCase().includes(searchQuery.toLowerCase()) ||
      cmd.description.includes(searchQuery)
    return matchesCategory && matchesSearch
  })
}, [searchQuery, selectedCategory])

useMemo caches the filtered results, avoiding recalculation on every render.

Commonly Used but Easily Forgotten Commands#

Key Management#

# Check key type
TYPE user:1  # "hash"

# Set expiration
EXPIRE user:1 3600  # expires in 1 hour
TTL user:1  # remaining time (seconds)
PERSIST user:1  # remove expiration

# Safe key iteration (never use KEYS!)
SCAN 0 MATCH user:* COUNT 100  # return 100 matching keys at a time

Warning: KEYS * blocks Redis in production. Always use SCAN.

Transactions#

MULTI  # start transaction
SET counter 0
INCR counter
INCR counter
EXEC  # execute, returns ["OK", 1, 2]

# Or discard
DISCARD

Redis transactions have no rollback! If a command fails, subsequent commands still execute.

Pub/Sub#

# Terminal 1: subscribe
SUBSCRIBE news

# Terminal 2: publish
PUBLISH news "Hello World"

Subscription is blocking. The client can’t execute other commands until it receives messages.

Performance Data#

Local benchmark shows time complexity for common operations:

Operation Complexity Notes
GET/SET O(1) Fastest
HGET/HSET O(1) Single field operation
LPUSH/RPUSH O(1) Insert at ends
SADD O(1) Single member add
ZADD O(log N) Skip list insert
LLEN O(1) List length
SCARD O(1) Set size
ZCARD O(1) Sorted Set size

Real-World Use Cases#

Based on these data structures:

  1. Caching: String + expiration
  2. Distributed lock: SETNX + expiration + Lua script release
  3. Rate limiting: Sorted Set (timestamp as score)
  4. Leaderboard: Sorted Set
  5. Likes/Mutual friends: Set
  6. Message queue: List + BLPOP
  7. Shopping cart: Hash (field=product ID, value=quantity)
  8. Timeline: List (newest first)

The Final Tool#

Based on this organization, I built an online cheatsheet: Redis Cheatsheet

Features:

  • 140+ common commands
  • 9 category filters
  • Real-time search
  • One-click copy

Understanding command patterns beats rote memorization.


Related: SQL Builder | Regex Tester