Ankit KanojiyaIntermediate
Evergreen guide by Ankit Kanojiya · Intermediate · Databases
Redis Data Structures and What to Use Them For
Redis is more than a key-value cache. Strings, hashes, lists, sets, sorted sets, streams and the probabilistic types, with the use case each one fits.
- redis
- databases
- caching
- system-design
- backend
Most people meet Redis as a cache: SET user:42 "{json}" with a TTL, GET it back, done. That works, but it uses one of about nine data types and misses the reason Redis is in nearly every system design interview. Redis keeps everything in memory and runs commands on a single thread, so each command is fast and atomic. The data types let you push logic into the server instead of fetching data, changing it in your app and writing it back, which is where race conditions live.
This article walks through each type, the commands you will use most, and the problem each one solves. Commands are shown as you would type them in redis-cli.
Strings
A string is any byte sequence up to 512 MB: text, JSON, a serialised object or a number. The commands that matter beyond GET and SET:
SET session:abc123 "user=42" EX 1800 # expire in 30 minutes
SET lock:order:991 "worker-7" NX EX 10 # only set if not exists: a lock
INCR page:home:views # atomic counter
INCRBY wallet:42 -150
GETEX cache:profile:42 EX 60 # read and refresh TTL
SET ... NX EX is the standard distributed lock pattern: NX means "only if the key does not exist", EX puts a timeout on it so a crashed worker cannot hold the lock forever. INCR on a string that holds an integer is atomic, which is why rate limiters and view counters use it rather than reading, adding and writing back.
Use strings for sessions, cache entries, counters and locks.
Hashes
A hash is a map of fields to values under one key. If you store a user profile as a JSON string, updating the email means fetching and rewriting the whole blob. With a hash you touch one field:
HSET user:42 name "Ankit" email "a@example.com" plan "pro"
HGET user:42 email
HINCRBY user:42 login_count 1
HGETALL user:42
Hashes with a small number of fields are stored in a compact encoding, so a million small hashes use noticeably less memory than a million JSON strings. The catch is that a TTL applies to the whole key, not to individual fields (Redis 7.4 added per-field expiry with HEXPIRE, but check your server version before relying on it).
Use hashes for objects you update field by field: user profiles, product records, feature flags per tenant.
Lists
A list is a linked list of strings, with O(1) push and pop at either end:
LPUSH queue:emails "{job}" # producer adds to the head
BRPOP queue:emails 0 # consumer blocks until a job arrives
LRANGE feed:user:42 0 9 # the ten most recent items
LTRIM feed:user:42 0 999 # keep only the latest 1,000
LPUSH plus BRPOP gives you a simple work queue; BRPOP blocks, so the consumer does not poll. LPUSH plus LTRIM is a capped recent-activity feed. Indexing into the middle of a long list is O(n), so if you need random access, a list is the wrong type.
Use lists for queues, recent-items feeds and anything with a natural head and tail.
Sets
A set is an unordered collection of unique strings. The server enforces uniqueness, so you never check for duplicates in app code:
SADD post:17:likes 42 99 7
SISMEMBER post:17:likes 42 # 1 if user 42 liked it
SCARD post:17:likes # like count
SINTER user:42:follows user:99:follows # people both follow
SRANDMEMBER tags:all 5 # five random tags
SINTER, SUNION and SDIFF run on the server, which is the whole appeal: "friends in common" or "tags on A but not B" is one command instead of two fetches and a loop.
Use sets for likes, tags, unique visitors per day and membership checks.
Sorted sets
A sorted set is a set where each member has a floating-point score, kept in score order. It is the type interviewers most want to see you reach for:
ZADD leaderboard 1500 "player:42" 1320 "player:7"
ZINCRBY leaderboard 50 "player:7"
ZREVRANGE leaderboard 0 9 WITHSCORES # top ten
ZREVRANK leaderboard "player:42" # my position
ZRANGEBYSCORE jobs:delayed -inf 1732876800 # jobs due before a timestamp
Reads and writes are O(log n), and range queries by rank or by score are cheap. That makes sorted sets fit leaderboards, priority queues (score = priority), delayed job schedulers (score = run-at timestamp), and sliding-window rate limiters (score = request timestamp, then ZREMRANGEBYSCORE to drop anything older than the window and ZCARD to count what is left).
Streams
A stream is an append-only log where each entry gets an ID based on its timestamp. Unlike a list used as a queue, a stream keeps the messages after they are read, and consumer groups let several workers share the load with acknowledgements:
XADD orders * user 42 total 1299
XGROUP CREATE orders billing $ MKSTREAM
XREADGROUP GROUP billing worker-1 COUNT 10 BLOCK 5000 STREAMS orders >
XACK orders billing 1732876800000-0
If worker-1 crashes before XACK, the message stays pending and XAUTOCLAIM lets another worker pick it up. This is the pattern to describe when an interviewer asks how you would do Kafka-style event processing without running Kafka, with the honest caveat that a stream lives in one Redis instance's memory and needs XTRIM or MAXLEN to stay bounded.
Use streams for event logs, audit trails and work queues that need at-least-once delivery.
Bitmaps, HyperLogLog and geo
Three smaller types solve specific problems with very little memory.
A bitmap is a string treated as an array of bits. SETBIT active:2026-11-29 42 1 marks user 42 active today in one bit; BITCOUNT active:2026-11-29 counts daily actives, and BITOP AND across days gives retention. Ten million users fit in about 1.2 MB per day.
HyperLogLog estimates the number of unique items with a standard error of 0.81% using 12 KB per key, no matter how many items you add. PFADD visitors:home ip1 ip2 ... then PFCOUNT visitors:home. Use it when "roughly how many unique" is good enough and an exact set would be too large.
Geo commands store coordinates in a sorted set under the hood. GEOADD drivers 77.5946 12.9716 "driver:8" then GEOSEARCH drivers FROMLONLAT 77.60 12.97 BYRADIUS 3 km returns drivers within 3 km, which is the first version of every "find nearby" feature.
Worked example: a rate limiter with a sorted set
Allow 100 requests per user per minute, sliding window:
MULTI
ZREMRANGEBYSCORE ratelimit:42 -inf <now_ms - 60000>
ZADD ratelimit:42 <now_ms> <now_ms>:<request_id>
ZCARD ratelimit:42
EXPIRE ratelimit:42 60
EXEC
Drop timestamps older than a minute, add this request, count what remains, and let the key expire if the user goes quiet. If ZCARD returns more than 100, reject the request. MULTI/EXEC makes the four commands run as a unit, so two app servers cannot interleave. The fixed-window version is simpler, INCR on a key named by the current minute with a 60-second TTL, but it allows 200 requests across a window boundary; say so if asked.
Interview questions you should expect
Why is Redis fast if it is single-threaded? Because every command runs against in-memory structures with no locks, and the network I/O is multiplexed; the single thread is a feature that gives you atomicity for free.
How do you keep a list or sorted set from growing forever? LTRIM, ZREMRANGEBYRANK, XTRIM, or a TTL on the key.
What is the difference between a list as a queue and a stream? A list pop removes the message and there is no acknowledgement; a stream keeps it, supports consumer groups, and lets a crashed consumer's messages be reclaimed.
When would you not use Redis? When the dataset does not fit in memory, when you need complex queries across fields, or when losing the last few seconds of writes on a crash is unacceptable and you have not configured AOF persistence.
How do you count unique users for a year without storing them all? HyperLogLog, with the 0.81% error stated up front.
Go deeper
The Redis docs page "Data types" has one page per type with every command and its complexity. Try each command above in redis-cli against a local Docker container (docker run -p 6379:6379 redis) before an interview; the muscle memory helps. Then read the "Redis Streams" tutorial in the docs and the sliding-window section of the earlier article on this site, Designing a Rate Limiter.