Skip to content

Redis data types and what they’re for

BasicsConcept

Redis is more than a place to cache strings. Each key holds one of a few data structures, and the structure decides which questions are cheap to ask. Here are the five core types and the job each one is built for.

01 Every key holds one type

Redis is a server that keeps data in memory and answers short commands over the network. Each key points to exactly one value, and that value has a type. The type decides which commands work on the key and what each one costs.

The five core types
TypeHoldsGood forExample
Stringbytes: text, a number, a blobcached values, counters, locksINCR page:views
Hashfield → value pairsone object with named fieldsHSET user:42 plan pro
Listvalues in the order pushedqueues, the latest N itemsLPUSH jobs a
Setunique values, no ordertags, “seen this already?”SADD tags:post:1 db
Sorted setunique values, each with a scoreleaderboards, time windowsZADD board 50 ana

Use a command meant for another type and Redis refuses rather than guessing. TYPE tells you what a key holds.

Text
> LPUSH jobs a
(integer) 1
> GET jobs
(error) WRONGTYPE Operation against a key holding the wrong kind of value
> TYPE jobs
list

Redis has more types (streams, bitmaps, HyperLogLog, geospatial indexes), but these five cover most everyday jobs. The rest of this page takes them one at a time.

02 Strings: values, counters and locks

A string is the simplest value: up to 512 MB of bytes. It can hold text, a serialised object or a number. When it holds an integer, INCR adds one inside the server, so two app servers can never both read 10 and both write 11.

Text
> SET page:views 10
OK
> INCR page:views
(integer) 11
> SET name ana
OK
> INCR name
(error) ERR value is not an integer or out of range

Add NX (only set it if the key does not exist) and EX (delete it after this many seconds), and the same SET becomes a simple lock. The first worker gets OK; the second gets nothing and knows to back off. The expiry frees the lock if the holder crashes.

Text
> SET lock:order:7 worker-1 NX EX 30
OK
> SET lock:order:7 worker-2 NX EX 30
(nil)
> TTL lock:order:7
(integer) 30

A fixed-window rate limiter is the same idea: INCR a key such as rl:user:7:1200 (user 7, minute 1200), set an EXPIRE on it, and reject the request once the count passes the limit.

03 Hashes: one object, many fields

A hash is a small map stored under one key. Use it when a thing has named fields that you read or change one at a time.

Text
> HSET user:42 name Ana plan pro logins 3
(integer) 3
> HGET user:42 plan
"pro"
> HINCRBY user:42 logins 1
(integer) 4
One key, three fields
user:42 · hash
name→Anaplan→prologins→4was 3
  • changed by HINCRBY

You could store the user as a JSON string instead. Compare what it takes to count one more login:

JSON in a string
GET user:42
# parse the JSON in your app, add 1 to logins
SET user:42 '{"name":"Ana","plan":"pro","logins":4}'
Hash
HINCRBY user:42 logins 1

The string version moves the whole object twice, and if two clients do it at once, the second SET wipes out the first one’s change. The hash changes one field in one command.

04 Lists: queues and the latest N

A list keeps values in the order you push them. Pushing or popping at either end is cheap, O(1). Reaching into the middle, with LINDEX or LINSERT, walks the list and costs O(N). That shape fits a work queue: producers push on the left, a worker pops from the right.

A list used as a job queue
Step 1 of 7
jobs · list, left to right
Empty
Worker received
Empty
  • just pushed or received
  • about to be popped

The list jobs is empty, and a worker is waiting for something to do.

0 LLEN jobs

Real workers use BRPOP, which blocks until a job arrives instead of asking over and over. For a feed of the latest 100 items, LPUSH and then LTRIM recent 0 99 keeps the list from growing forever.

05 Sets: each member once

A set holds unique values with no order. SADD tells you how many members were new, SISMEMBER checks one in O(1), and SINTER or SUNION combine sets on the server.

Text
> SADD tags:post:1 redis db cache
(integer) 3
> SADD tags:post:1 redis
(integer) 0
> SISMEMBER tags:post:1 db
(integer) 1
> SADD tags:post:2 redis queue
(integer) 2
> SINTER tags:post:1 tags:post:2
1) "redis"

A set also answers “how many distinct visitors today?” with SCARD. That works until the numbers get large, because every member costs memory. If an estimate will do, Redis has a type built for exactly that:

Set of visitor idsExact countMemory grows with every member. Fine for thousands, costly for hundreds of millions.
HyperLogLogAbout 0.81% offPFADD and PFCOUNT estimate the count in at most about 12 KB per key, but can’t list the members.

06 Sorted sets: members ranked by score

A sorted set is a set where each member carries a number, its score, and Redis keeps the members in score order as you change them. Adding or updating a member is O(log N); reading the top 10 is O(log N + 10). A large sorted set is a skip list plus a hash table, so Redis can find a member by name and also walk members in order.

Text
> ZADD board 50 ana 80 bo 65 cy
(integer) 3
> ZINCRBY board 20 ana
"70"
> ZRANGE board 0 2 REV WITHSCORES
1) "bo"
2) "80"
3) "ana"
4) "70"
5) "cy"
6) "65"
> ZREVRANK board ana
(integer) 1
board after ZINCRBY, highest score first
board · sorted set, index = rank
bo · 800
ana · 701
cy · 652
  • moved up after +20

ZRANGE ... REV was added in Redis 6.2. On older versions use ZREVRANGE board 0 2 WITHSCORES.

The score does not have to be points. Make it a timestamp and a sorted set becomes a sliding window: add each request, drop those older than the window, count what is left. Members must be unique, so give each request its own id, and run the three commands in a MULTI block or a script so they happen together.

Text
ZADD rl:user:7 1200 req-81 # score = time in seconds
ZREMRANGEBYSCORE rl:user:7 -inf 1140 # drop requests older than 60 s
ZCARD rl:user:7 # requests in the last minute

07 Pick the type by the question you ask

Start from the question your app asks most often and choose the type that answers it in one cheap command.

Question → type → command
You askTypeCommand
What is the value of X?StringGET
How many so far?StringINCR
What is field F of object X?HashHGET
What is the next job?ListBRPOP
Have we seen X before?SetSISMEMBER
Who is in the top 10?Sorted setZRANGE ... REV
KEYS user:*Listing keys with KEYSKEYS checks every key in the database while every other client waits. Use SCAN, which returns a small batch per call.
SMEMBERS tags:allReading a huge collection at onceSMEMBERS, HGETALL and LRANGE key 0 -1 return everything in one reply. On large keys, page through with SSCAN, HSCAN or a range.
DEL big:setDeleting a huge keyFreeing millions of members takes time. UNLINK removes the key at once and frees the memory in the background.
EXPIRE user:42 60Expiry is per key, not per fieldA TTL on a hash removes the whole hash. Redis 7.4 added HEXPIRE for single fields; on older versions, give short-lived data its own key.
RPOP jobsA popped job is goneIf the worker crashes after RPOP, the job is lost. Move it to a processing list with BLMOVE first, or use a stream with consumer groups.

08 Check yourself

Question

Ten app servers count page views in the same key at the same time. Which way loses no updates?

Question

A game shows the top 10 players and each player’s rank, and scores change after every match. Which type fits?

Question

A worker takes a job with RPOP and crashes halfway through. What happens to the job?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?