Databases · Beginner · 16 min
Learn the Redis data types with redis-cli
By Padding · Updated 18 Nov 2026
Redis 8.12.0 (redis:8 image) · Python 3.15 · redis-py 8.2
You will model a small online shop session in Redis 8.12 with strings, hashes, lists, sets and sorted sets, give keys a lifetime, find and measure them without blocking the server, and read the result back from Python.
On this page
Redis keeps data in memory and gives each key a type. The type decides which commands work on the key and how much memory it costs. Picking the right one is most of the skill: a shopping cart stored as one JSON string has to be read, changed and written back whole, while the same cart as a hash lets you change one line with one command.
In this tutorial you store the pieces of one shopper's session, each in the type that fits it: a session token and page counter as strings, the cart as a hash, recently viewed products as a capped list, product tags as sets, and a bestseller board as a sorted set. Then you give keys a lifetime, list and measure them safely, and read the whole thing from a short Python script.
Every key starts with shopdemo:, so you can tell the demo data apart from anything else on the server and delete it cleanly at the end.
A note on licences: from version 8, Redis Open Source is offered under your choice of RSALv2, SSPLv1 or AGPLv3. Valkey, the Linux Foundation fork set up in the Valkey install tutorial, is BSD-licensed and accepts every command used here. If you run Valkey, type valkey-cli wherever this page says redis-cli.
Step 1 · Connect and check the server
redis-cli connects to 127.0.0.1:6379 unless you tell it otherwise. If your server needs a password, put it in the REDISCLI_AUTH variable for this shell first. The prompt hides what you type, and the password never appears in your shell history or in the process list, as it would with -a:
read -rsp 'Redis password: ' REDISCLI_AUTH; echo
export REDISCLI_AUTHSkip that if your server has no password. Then ask the server to answer and to report its version:
redis-cli PING
redis-cli INFO server | grep -E '^(redis_version|tcp_port)'You can also run redis-cli with no arguments to get an interactive prompt (127.0.0.1:6379>) with history and Tab completion of command names. This page passes each command as arguments instead, so you can copy the lines straight into a terminal. Type quit to leave the prompt.
Check it worked
PING replies PONG. The INFO lines read redis_version:8.12.0 (or a later 8.x) and tcp_port:6379. A reply of NOAUTH Authentication required. means the server has a password and REDISCLI_AUTH is not set in this shell.
Step 2 · Store the session token and a counter as strings
A string is the simplest type: one key, one value of up to 512 MB of any bytes. Store the shopper's session with a one-hour lifetime (EX 3600, in seconds). An hour gives you room to finish this walkthrough; 30 minutes (EX 1800) is more typical in a real app. NX means "only if the key does not exist yet", so a second login cannot quietly overwrite a session that is still live:
redis-cli SET shopdemo:session:amaka '{"user":"amaka","lang":"yo"}' EX 3600 NX
redis-cli GET shopdemo:session:amaka
redis-cli SET shopdemo:session:amaka '{"user":"someone-else"}' EX 3600 NXThe first SET replies OK. GET prints the JSON back. The second SET replies (nil): the key already existed, so nothing changed.
Strings that hold whole numbers can be counted up in one step. Count three views of a product page; -r 3 tells redis-cli to send the command three times:
redis-cli -r 3 INCR shopdemo:views:p100The replies are (integer) 1, (integer) 2 and (integer) 3. INCR creates the key at 0 on first use, and because Redis runs one command at a time, two app servers counting the same page at once never lose a view.
Redis stores bytes, so text in any language is safe. Save a Yorùbá greeting and ask for its length:
redis-cli SET shopdemo:greeting:yo 'Ẹ káàbọ̀'
redis-cli --raw GET shopdemo:greeting:yo
redis-cli STRLEN shopdemo:greeting:yoCheck it worked
GET without --raw would show escape codes such as \xe1\xba\xb8 for the accented letters; with --raw you see the greeting as typed. STRLEN replies (integer) 15, far more than the letters you see, because it counts bytes, and each accented letter takes two to five bytes in UTF-8 (ọ̀ is a base letter plus a combining tone mark). Keep that in mind when you enforce a length limit on names or messages in Hausa, Yorùbá, Amharic or any language beyond plain ASCII: check the length in your app, in characters, not with STRLEN.
Step 3 · Keep the cart in a hash
A hash is a small map of fields to values under one key, like a row with flexible columns. Use one field per product and the quantity as its value:
redis-cli HSET shopdemo:cart:amaka p100 2 p205 1
redis-cli HINCRBY shopdemo:cart:amaka p100 1
redis-cli HGET shopdemo:cart:amaka p100
redis-cli HGETALL shopdemo:cart:amaka
redis-cli HLEN shopdemo:cart:amakaHSET replies (integer) 2, the number of new fields. HINCRBY changes one quantity without touching the rest of the cart and replies with the new value, 3. HGETALL prints field and value on alternate lines: p100, 3, p205, 1. HLEN replies 2.
Ask Redis how it holds the hash in memory, then try to treat it as a list:
redis-cli OBJECT ENCODING shopdemo:cart:amaka
redis-cli LPUSH shopdemo:cart:amaka p999Check it worked
OBJECT ENCODING replies listpack: small hashes are packed into one compact block, which is why hashes are a cheap way to store many small records. Redis converts them to a real hash table once they grow past a size limit. LPUSH fails with WRONGTYPE Operation against a key holding the wrong kind of value. A key has exactly one type until you delete it, and the error leaves the cart as it was.
Step 4 · Track recently viewed products with a capped list
A list keeps values in order and is fast to add to at either end. Push each viewed product onto the front, then trim the list so it holds only the five newest. Six views arrive here in one command, as if the shopper clicked through six products:
redis-cli LPUSH shopdemo:recent:amaka p100 p205 p310 p412 p518 p623
redis-cli LTRIM shopdemo:recent:amaka 0 4
redis-cli LRANGE shopdemo:recent:amaka 0 -1LPUSH adds each value to the front in turn, so the last one, p623, ends up first. LTRIM 0 4 keeps positions 0 to 4 and drops the rest, and LRANGE 0 -1 prints the whole list: p623, p518, p412, p310, p205.
In an app, every page view runs the same small sequence. LREM ... 0 p100 first removes any older copy of the product, so it never shows twice:
redis-cli LREM shopdemo:recent:amaka 0 p100
redis-cli LPUSH shopdemo:recent:amaka p100
redis-cli LTRIM shopdemo:recent:amaka 0 4A capped list keeps the "recently viewed" strip small and fixed in size. The page renders a fixed strip of five products however long the shopper browses, and the key's memory stays bounded instead of growing with every view.
Check it worked
redis-cli LRANGE shopdemo:recent:amaka 0 -1
redis-cli LLEN shopdemo:recent:amakaThe list reads p100, p623, p518, p412, p310, and LLEN replies 5. p205 fell off the end when p100 came back in.
Step 5 · Tag products with sets
A set holds unique values with no order. Adding a value that is already there does nothing, which suits tags. Tag two products, then ask which tags they share:
redis-cli SADD shopdemo:tags:p100 ankara cotton women
redis-cli SADD shopdemo:tags:p205 ankara cotton men
redis-cli SADD shopdemo:tags:p100 cotton
redis-cli SINTER shopdemo:tags:p100 shopdemo:tags:p205
redis-cli SISMEMBER shopdemo:tags:p205 womenThe first two SADD calls reply (integer) 3. The third replies (integer) 0, because cotton was already a member. SINTER returns the tags both products have, ankara and cotton, in no fixed order. SISMEMBER replies 0: p205 is not tagged women.
SUNION (all tags of either product) and SDIFF (tags of the first that the second lacks) work the same way. They are the building blocks of "similar products" and filter panels.
Check it worked
redis-cli SCARD shopdemo:tags:p100
redis-cli SDIFF shopdemo:tags:p100 shopdemo:tags:p205SCARD replies 3, the number of tags on p100, and SDIFF prints women.
Step 6 · Rank bestsellers with a sorted set
A sorted set is a set where every member has a number, its score, and Redis keeps the members ordered by score. Record this week's sales per product, then add three more sales of p205:
redis-cli ZADD shopdemo:bestsellers 12 p100 7 p205 9 p310 4 p412
redis-cli ZINCRBY shopdemo:bestsellers 3 p205
redis-cli ZRANGE shopdemo:bestsellers 0 2 REV WITHSCORESZADD replies (integer) 4. ZINCRBY replies "10", the new score. ZRANGE ... 0 2 REV WITHSCORES reads the top three, highest score first, each followed by its score: p100 12, p205 10, p310 9. Without REV you get the lowest first.
Two more questions a leaderboard has to answer, a product's score and its place:
redis-cli ZSCORE shopdemo:bestsellers p310
redis-cli ZREVRANK shopdemo:bestsellers p310Check it worked
ZSCORE replies "9" and ZREVRANK replies (integer) 2. Ranks count from 0, so p310 is third. Scores stay in order as they change, so reading the top few stays fast as the board grows: the cost rises with the logarithm of its size, not with the size itself.
Step 7 · Give keys a lifetime
Any key can expire, whatever its type. TTL reports the seconds left. It replies -1 for a key with no expiry and -2 for a key that does not exist:
redis-cli TTL shopdemo:session:amaka
redis-cli TTL shopdemo:cart:amaka
redis-cli TTL shopdemo:no-such-keyThe session shows a number below 3600, lower by however many seconds have passed since you created it. The cart shows -1 and the missing key -2. Give the cart the same hour as the session, so an abandoned cart cleans itself up:
redis-cli EXPIRE shopdemo:cart:amaka 3600
redis-cli TTL shopdemo:cart:amakaEXPIRE replies 1 and TTL now shows the countdown. Changing a field with HSET or HINCRBY keeps the expiry. Replacing a string with a plain SET does not, which catches people out. Watch it happen on a banner message:
redis-cli SET shopdemo:banner 'Free delivery this weekend' EX 120
redis-cli SET shopdemo:banner 'Free delivery until Sunday'
redis-cli TTL shopdemo:banner
redis-cli SET shopdemo:banner 'Free delivery until Sunday' EX 120
redis-cli SET shopdemo:banner 'Free delivery until Monday' KEEPTTL
redis-cli TTL shopdemo:bannerCheck it worked
The first TTL replies -1: the second SET replaced the value and threw the expiry away, so the banner would now live for ever. The last TTL shows a number at or below 120, because KEEPTTL changed the text and kept the countdown.
Step 8 · Find keys and measure them without blocking the server
KEYS shopdemo:* would list the keys, but it walks the whole keyspace in one go, and Redis serves nobody else until it finishes. On a server with millions of keys that is a visible outage. SCAN does the same walk in small batches. Each call returns a cursor to pass to the next call, and 0 back means the walk is done:
redis-cli SCAN 0 MATCH 'shopdemo:*' COUNT 100The first line of the reply is the next cursor (0 here, as the demo keyspace is small), followed by the matching keys. redis-cli --scan runs the loop for you. Use it to print each key with its type:
for key in $(redis-cli --scan --pattern 'shopdemo:*'); do
echo "$key $(redis-cli TYPE "$key")"
doneThen ask how many bytes one key costs, including Redis's own bookkeeping:
redis-cli MEMORY USAGE shopdemo:cart:amaka
redis-cli MEMORY USAGE shopdemo:bestsellersCheck it worked
The loop prints nine keys, one per line, in no fixed order: the session, views and greeting as string, the cart as hash, the recent list as list, the two tag keys as set, the bestsellers as zset, and the banner as string. MEMORY USAGE replies with a number of bytes, something like a hundred for each of these small keys. Check it again on a big key in your own data before you decide a type is too expensive.
Step 9 · Read the session from Python, then clean up
Your app talks to Redis through a client library, with the same commands under method names. If you took a break, run redis-cli TTL shopdemo:session:amaka first: a reply of -2 means the session and cart have expired, so run the first SET ... EX 3600 NX line from the strings step, the HSET and HINCRBY lines from the hash step and EXPIRE shopdemo:cart:amaka 3600 again before you go on. Install uv 0.13.10, the Python project tool, from its official installer, and load it into this shell:
curl -LsSf https://astral.sh/uv/0.13.10/install.sh | sh
. "$HOME/.local/bin/env"
uv --versionMake a throwaway project on Python 3.15 and add redis-py, the official Python client. uv downloads Python 3.15 if you do not have it. The range allows 8.x updates and nothing newer:
mkdir -p ~/redis-types-demo
cd ~/redis-types-demo
uv init --no-package --vcs none --python 3.15
uv add "redis>=8.2,<9"Write a script that reads each piece of the session back. It takes the password from REDISCLI_AUTH when that is set, so nothing secret sits in the file. decode_responses=True turns Redis's bytes into Python strings:
cat > session.py <<'PY'
import json
import os
import redis
r = redis.Redis(
host="127.0.0.1",
port=6379,
password=os.environ.get("REDISCLI_AUTH"),
decode_responses=True,
)
session = json.loads(r.get("shopdemo:session:amaka"))
print("user:", session["user"])
print("cart:", r.hgetall("shopdemo:cart:amaka"))
print("recent:", r.lrange("shopdemo:recent:amaka", 0, -1))
for product, sold in r.zrange("shopdemo:bestsellers", 0, 2, desc=True, withscores=True):
print("top:", product, int(sold))
PY
uv run session.pyThe script prints the user, the cart as a dictionary, the recent list and the top three:
user: amaka
cart: {'p100': '3', 'p205': '1'}
recent: ['p100', 'p623', 'p518', 'p412', 'p310']
top: p100 12
top: p205 10
top: p310 9Now remove the demo data. This deletes only keys whose names start with shopdemo:. Never reach for FLUSHALL on a shared server: it empties every database on it, with no undo.
redis-cli --scan --pattern 'shopdemo:*' | xargs -r redis-cli DEL
cd ~
rm -rf ~/redis-types-demoDEL replies with the number of keys it removed, 9. uv and Python 3.15 stay installed for later tutorials.
Check it worked
redis-cli --scan --pattern 'shopdemo:*' | wc -lThe count is 0, and ~/redis-types-demo is gone.
Next steps
- Put these types to work in front of a slow database query: cache database results in Redis.
- Use a sorted set as a sliding window: throttle login attempts with Redis sorted sets.
- Meet the type this page skipped, the append-only stream: run background jobs with Redis streams.
- Run your own server with a password and a memory limit: install Valkey or Redis on Ubuntu.
Related tutorials
- Use SQLite safely in a Python app: WAL mode, foreign keys and busy timeoutsYou will build a small room-booking store on SQLite with Python 3.15, reproduce the "database is locked" error with two writer processes, and end with a connection helper that turns on foreign keys, WAL mode, a busy timeout and BEGIN IMMEDIATE writes, plus a tested online backup.
- Throttle login attempts with a sliding window in RedisYou will protect a Python login function from password guessing with a sliding-window log in Redis sorted sets, checked atomically in a Lua script, with per-address lockouts that double each time, an account-wide rule that asks for an extra check instead of locking the owner out, and tests that replay 50 guesses.
- Run background jobs with Redis Streams and consumer groupsYou will build a small receipt-sending job queue on Redis 8 Streams with two Python workers that share the work, recover jobs from a crashed worker, park repeated failures in a dead-letter stream and never send the same receipt twice.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials