Lab 14: Redis Data Structures

Time: 40 minutes | Level: Practitioner | DB: Redis 7

Redis is an in-memory data structure store. Unlike traditional databases, it natively understands Strings, Hashes, Lists, Sets, Sorted Sets — and many operations are O(1). This makes it ideal for caching, session storage, leaderboards, and real-time analytics.


Step 1 — Setup and Connection

docker run -d --name redis-lab redis:7
sleep 2
docker exec -it redis-lab redis-cli

# Verify connection
PING
# PONG

# Clear all data (dev only!)
FLUSHALL

📸 Verified Output:

PONG
OK

Step 2 — Strings: The Foundation

Strings are the simplest Redis type — a key maps to a byte sequence (binary-safe, up to 512MB).

📸 Verified Output:

💡 Redis strings are binary-safe — they can store JSON, images, serialized objects, anything. The limit is 512MB per value.


Step 3 — Hashes: Object Storage

Hashes map string fields to string values — perfect for storing objects without serializing the whole thing.

📸 Verified Output:

💡 Hashes are more memory-efficient than storing the same data as separate string keys. user:1:name + user:1:email + user:1:age costs 3 key overhead; HSET user:1 name email age costs 1.


Step 4 — Lists: Ordered Sequences

Lists are ordered sequences of strings — insertion order preserved. Support both stack (LIFO) and queue (FIFO) patterns.

📸 Verified Output (LRANGE after pushes):

💡 Lists are ideal for message queues (RPUSH + BLPOP) and activity feeds (LPUSH + LRANGE 0 N). For a task queue, have producers RPUSH and workers BLPOP.


Step 5 — Sets: Unique Collections

Sets are unordered collections of unique strings. O(1) add/remove/check, O(N) set operations.

📸 Verified Output:


Step 6 — Sorted Sets: Ranked Data

Sorted Sets are like Sets but each member has a score (float). Members are always sorted by score. Perfect for leaderboards, priority queues, time-series.

📸 Verified Output:


Step 7 — Type Inspection and Key Management


Step 8 — Capstone: Social Media Data Model


Summary

Structure
Best For
Key Commands

String

Simple values, counters, JSON blobs

GET/SET, INCR, SETEX

Hash

Object with multiple fields

HSET/HGET, HGETALL, HINCRBY

List

Queues, feeds, ordered history

LPUSH/RPUSH, LRANGE, BLPOP

Set

Unique membership, set math

SADD/SMEMBERS, SINTER/SUNION

Sorted Set

Leaderboards, ranked data

ZADD/ZRANGE, ZINCRBY, ZRANGEBYSCORE

Last updated