How to Use Redis: The Beginner's Guide (First Commands, Five Data Structures, Expiry, and Your First Cache)

CodexFuse Team · 2026-10-31T03:57:27.257Z · 15 min read

How do you use Redis?

Learning how to use Redis comes down to one loop: start a Redis server, connect to it with the redis-cli command line, and store data as keys with commands like SET and GET. That is the whole beginner arc of this Redis tutorial: install it, talk to it with redis-cli, learn the five data structures, set key expiry, and finish by building one real cache.

  1. Install Redis. The fastest route is Docker: docker run -d --name redis-dev -p 6379:6379 redis. macOS users can run brew install redis; Linux users can add Redis's official apt repository or compile from source.
  2. Connect with redis-cli. Type redis-cli in your terminal. You get the 127.0.0.1:6379> prompt — every command below runs there.
  3. Store and read a string. SET name "Flavio" stores it, GET name reads it back. A missing key returns (nil).
  4. Learn the five Redis data structures. Hashes store objects, lists store queues, sets store unique tags, sorted sets store ranked data — the Redis hashes, lists, and sets section below covers each one.
  5. Give keys a lifespan. SET session:abc "data" EX 300 makes the key delete itself after five minutes. Check the countdown with TTL.
  6. List keys safely. Use SCAN, never KEYS, on any server other people use.
  7. Build a real cache. Store a slow database result under a key with an expiry, and read it from Redis before touching the database.

What is Redis, and why does everyone say "just cache it in Redis"?

Redis is an in-memory data store that works as a database, a cache, and a message broker. It keeps data in RAM instead of on disk, so reads and writes happen in microseconds rather than milliseconds — which is why "just cache it in Redis" is the default answer to slow pages.

Two things make Redis different from a normal database. First, everything is a key: you store a value under a name, and the name is how you get it back. Second, the value can be one of five structures — strings, hashes, lists, sets, or sorted sets — so the data store itself can model counters, queues, leaderboards, and objects without extra code.

The trade-off is durability. Redis is in-memory by default, which means a restart loses your data unless you configure persistence (covered later in this guide). That is why Redis usually sits in front of a real database — it holds the hot, frequently-read data, and the database holds the truth. If you want the managed-database side of that picture instead of running your own store, our Supabase beginner guide covers the hosted option.

How do you install Redis?

You install Redis with Docker, a package manager, or from source — pick one path and stick with it for this guide. Docker is the choice this guide recommends, because it gives you a throwaway server you can delete and recreate in seconds.

The Redis Docker path is one command. If you have not used containers before, read our Docker beginner guide first, then come back:

docker run -d --name redis-dev -p 6379:6379 redis

This starts a Redis server named redis-dev, maps port 6379 to your machine, and runs it in the background. The official redis image on Docker Hub is kept current shortly after each release, and redis:8 pins the Redis 8 line if you want a major-version tag.

On macOS, the official Redis docs recommend Homebrew: brew install redis installs the latest open-source release. Start it with brew services start redis, or run it in the foreground with redis-server. On Ubuntu or Debian, add Redis's official repository, then install:

curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list
sudo apt update
sudo apt install redis-server

On Windows, Redis ships no official native build, so the practical route is Windows Subsystem for Linux 2 (WSL2) with the Linux commands above — that is how the guides in the field install it on Windows machines. Check redis-server --version afterwards; releases are currently in the Redis 8 line, and redis.io/downloads always shows the exact latest stable.

How do you run your first redis-cli commands?

You run your first Redis commands by opening redis-cli — the command-line client that installs alongside the server — and typing commands at the 127.0.0.1:6379> prompt. Type PING first; the server answers PONG, which proves you are connected.

Now store your first value. The two commands behind the "redis set get" pattern every beginner searches for are SET and GET:

127.0.0.1:6379> SET name "Flavio"
OK
127.0.0.1:6379> GET name
"Flavio"
127.0.0.1:6379> GET does-not-exist
(nil)

Redis confirms the write with OK. Reading a key that was never set returns (nil), which means "nothing here" — not an error. Two more housekeeping commands belong in your first session:

127.0.0.1:6379> EXISTS name
(integer) 1
127.0.0.1:6379> DEL name
(integer) 1
127.0.0.1:6379> EXISTS name
(integer) 0

EXISTS answers 1 or 0, and DEL tells you how many keys it removed. The counter commands are where Redis starts earning its reputation — INCR and DECR update a number atomically, so two clients incrementing at the same moment never lose a count:

127.0.0.1:6379> SET visits 10
OK
127.0.0.1:6379> INCR visits
(integer) 11
127.0.0.1:6379> INCRBY visits 5
(integer) 16

Running INCR on a key that does not exist yet starts it at 1. A few redis-cli flags are worth learning on day one: redis-cli -n 2 PING talks to database number 2 (Redis ships with 16 numbered databases, switched with SELECT), redis-cli --raw GET key prints values without quotes or escaping, and redis-cli -h <host> -p <port> -a <password> connects to a remote server.

What are the five Redis data structures?

The five Redis data structures are strings, hashes, lists, sets, and sorted sets — and they are the whole reason people choose Redis over a plain key-value cache. Every structure has its own commands, and the structure you pick decides what your code looks like later.

StructureWhat it modelsCore commandsUse it for
StringOne key, one valueSET, GET, INCR, DELSessions, counters, cached pages
HashOne key, a small objectHSET, HGET, HGETALLUser profiles, product records
ListAn ordered queueRPUSH, LRANGE, LMOVEJob queues, activity feeds
SetUnique unordered membersSADD, SMEMBERSTags, unique visitors
Sorted setMembers ranked by scoreZADD, ZRANGELeaderboards, rate limiters

Strings are what you already used: a value can hold up to 512 MB of text, serialized JSON, or an integer you bump with INCR. SET name "Roger" NX adds a useful variation — it only sets the key if it does not exist yet, returning nil instead of overwriting. The older SETNX still works but is deprecated in favor of SET ... NX.

Hashes store an object under one key, so a user profile is a single key instead of a dozen:

127.0.0.1:6379> HSET user:1 name "Alice" age 25
(integer) 2
127.0.0.1:6379> HGET user:1 name
"Alice"
127.0.0.1:6379> HGETALL user:1
1) "name"
2) "Alice"
3) "age"
4) "25"

Lists are ordered, so they make natural queues. Push jobs on one end and read them from the other:

127.0.0.1:6379> RPUSH queue job1 job2 job3
(integer) 3
127.0.0.1:6379> LRANGE queue 0 -1
1) "job1"
2) "job2"
3) "job3"

For a reliable queue, move each job with LMOVE queue processing, do the work, then remove it with LREM processing 1 job — a job that crashes mid-processing is still sitting in processing instead of lost.

Sets hold unique members and ignore duplicates automatically:

127.0.0.1:6379> SADD tags:post1 redis db cache
(integer) 3
127.0.0.1:6379> SADD tags:post1 redis
(integer) 0
127.0.0.1:6379> SMEMBERS tags:post1
1) "redis"
2) "db"
3) "cache"

Sorted sets are the most versatile structure on this list. Every member carries a score, and Redis keeps them ordered — leaderboards, priority queues, time-ordered indexes, and rate limiters all reduce to them:

127.0.0.1:6379> ZADD leaderboard 1500 "alice" 2300 "bob" 900 "carol"
(integer) 3
127.0.0.1:6379> ZRANGE leaderboard 0 -1 REV WITHSCORES
1) "bob"
2) "2300"
3) "alice"
4) "1500"
5) "carol"
6) "900"

How does Redis expiry work?

Redis expiry works by attaching a countdown timer to a key; when the timer ends, Redis deletes the key automatically. This is the mechanism behind sessions, temporary tokens, and every cache entry you will ever write.

The simplest form is the EX option on SET:

127.0.0.1:6379> SET session:abc123 "user-42" EX 300
OK
127.0.0.1:6379> TTL session:abc123
(integer) 297

TTL reports the seconds left. It has two special answers you should memorize: -1 means the key exists but has no expiry and stays until you delete it, and -2 means the key is gone — it expired, or it was never set. You will also see SETEX <key> <seconds> <value> in older tutorials; it still works but is deprecated in favor of SET with EX.

To add a timer to a key that already exists, use EXPIRE <key> <seconds>. Expiry is the single most important Redis feature for a beginner to internalize: without it, a cache grows forever and your "fast" store slowly turns into a second database you never meant to run.

Why must you use SCAN instead of KEYS in production?

You must use SCAN instead of KEYS in production because KEYS walks every key on the server in one blocking operation — while it runs, no other client gets served. On your practice container that does not matter; on a server with a million keys, it is an outage.

On your practice instance, try both and compare. KEYS n* returns every key starting with "n" at once. SCAN 0 MATCH n* COUNT 100 returns a cursor plus one small batch:

127.0.0.1:6379> SCAN 0 MATCH n* COUNT 100
1) "0"
2) 1) "name"

The first reply is a cursor, the second is the keys found in this round. If the cursor comes back as something other than 0, call SCAN again with that cursor and keep going until the cursor returns 0 — that is when the scan is complete. Two details from the official behavior: the same key can appear more than once during a scan, so dedupe in your code if you need a unique list; and COUNT is only a hint about how much work Redis does per call, not an exact number of keys.

Rule of thumb for this Redis tutorial and everything after it: KEYS is a debugging tool for your own throwaway container. SCAN is how you list keys anywhere else.

How does Redis persistence work?

Redis persistence works by writing the in-memory data to disk, but you have to choose a mode — by default Redis keeps everything in RAM and a restart wipes it. That default surprises beginners, so learn the two modes before you store anything you care about.

The first mode is RDB snapshots: Redis periodically saves a point-in-time copy of the dataset. The save points are configurable; CONFIG GET save shows them. To test that your data survives a restart, set a key, run SHUTDOWN SAVE to stop the server after writing a snapshot, restart it, and check the key is still there.

The second mode is the append-only file (AOF): Redis logs every write operation, so a restart replays the log and rebuilds the data. Snapshots are compact and fast to load; the append-only log loses less data but writes more to disk. Most production setups run one of the two, and many run both.

For a beginner, the honest summary is this: persistence makes Redis durable enough for real work, but Redis is still happiest as the fast layer in front of a database that holds the permanent truth. When you are ready to put a Redis server somewhere permanent, start with our what is VPS hosting guide — Redis runs on the same kind of server your app does.

Redis vs Memcached: which one should you learn?

You should learn Redis first, because it does everything Memcached does plus the parts beginners actually need next. The short version: Memcached is a single-purpose tool, and Redis is the one that grows with you.

RedisMemcached
Data modelFive structures: strings, hashes, lists, sets, sorted setsPlain key-value strings only
PersistenceOptional — RDB snapshots or append-only logNone — memory only, restart wipes it
ExpiryPer-key TTL with the TTL commandPer-key expiry, similar idea
Atomic operationsINCR, Lua scripts, transactionsincr/decr only
MessagingPub/Sub and Streams built inNone
Best forCaching plus queues, leaderboards, sessions, rate limitingSimple object caching and nothing else

If your only job is "remember this string for ten minutes," Memcached is fine and simpler. The moment you need a queue, a leaderboard, a session store with structured data, or anything you would rather not lose on restart, that is the Redis lane — which is why this guide teaches Redis.

How do you build your first real Redis cache?

You build your first real Redis cache with the cache-aside pattern: check Redis before the database, and store the database result with an expiry when it is missing. This one pattern is the answer to most "how to use redis" searches, so it is worth typing out yourself.

Install the Python client with pip install redis, then write the pattern exactly as it runs in production. If your editor is not ready for Python work, our VS Code beginner guide gets you set up:

import json
import redis

r = redis.Redis(host="localhost", port=6379, decode_responses=True)

def get_product(product_id):
    key = f"product:{product_id}"
    cached = r.get(key)
    if cached:
        return json.loads(cached), True   # cache hit: no database call

    product = slow_database_lookup(product_id)  # your real query here
    r.set(key, json.dumps(product), ex=300)     # cache miss: store 5 minutes
    return product, False

The flow is three lines of logic: r.get(key) checks the cache, the database fills the gap, and r.set(key, ..., ex=300) writes the result with a five-minute expiry so stale data fixes itself. The ex parameter is the same EX option you learned in redis-cli.

A second mini-pattern completes your first toolkit: a page-view counter with INCR, which stays correct even when a hundred visitors arrive at once:

views = r.incr("page:home:views")   # atomic: never loses a count
print(f"Home page views: {views}")

Between the cache-aside pattern and the atomic counter, you now have the two Redis uses that appear in nearly every backend job description: make slow things fast, and count things correctly.

What mistakes do Redis beginners make?

Redis beginners make the same four mistakes, and all four are avoidable once you have seen them listed. First: running FLUSHDB or FLUSHALL anywhere but a practice instance — both commands delete data instantly with no undo, so keep them on the throwaway Docker container from this guide's install section.

Second: reaching for KEYS * on a shared server instead of SCAN. Third: leaving port 6379 open to the internet with no password — a Redis server with no authentication and a public port gets found and abused quickly, so bind it to localhost and set a password before anything else in production.

Fourth: treating Redis as the database of record. Redis is the fast layer; the database is the truth. Cache what is expensive to compute, expire what goes stale, and let the database own the data you cannot afford to lose.

Sources

Facts in this guide were verified on October 30, 2026 against the following sources:

  • Flavio Copes, "First steps with Redis" (updated October 5, 2026) — redis-cli basics, SET/GET/EXISTS/DEL, SET NX and the deprecated SETNX, KEYS vs SCAN semantics, SET EX expiry, TTL -1/-2 values, INCR/DECR atomicity — https://flaviocopes.com/redis-first-steps/
  • Codezup, "Redis for Beginners: Commands, Data Types and Pub/Sub (2026)" (updated July 24, 2026) — Redis 8.8 as the current release, Docker install command, string 512MB limit, Pub/Sub semantics — https://codezup.com/redis-for-beginners-tutorial/
  • Musa Muhammad, "Mastering Redis from the Command Line: A Hands-On Practice Guide" (dev.to, ~17 days old) — CLI drill, redis-cli flags, SCAN vs KEYS production rule, RDB persistence restart test, sorted-set and queue patterns — https://dev.to/musamuhammad/mastering-redis-from-the-command-line-a-hands-on-practice-guide-2hi9
  • redis.io official documentation — macOS Homebrew install route (brew install redis, formula details), install-from-source procedure, downloads page and Docker image availability — https://redis.io/docs/latest/operate/oss_and_stack/install/install-stack/homebrew/
  • Reynaldi Neo, "Getting Started with Redis: A Beginner's Guide" (March 2025) — WSL install path, 16 default databases and SELECT, basic command reference — https://reynaldineo.com/blog/redis-beginner-guide

Frequently asked questions

Is Redis a database or a cache?

Redis is both: an in-memory data store that works as a database, a cache, and a message broker. Most teams use it as a cache in front of a real database, because it is in-memory by default and a restart loses data unless persistence is configured.

How long does it take to learn the basics of Redis?

A focused beginner can run first commands in under an hour: install with Docker, open redis-cli, and work through SET/GET, the five data structures, and key expiry. The production skills — SCAN discipline, persistence choices, and memory limits — are the second day, not the first hour.

What is the difference between KEYS and SCAN in Redis?

KEYS lists every matching key in one blocking operation, which stalls the whole server while it runs — fine on a practice container, an outage risk in production. SCAN returns keys in small batches using a cursor, so the server keeps answering other clients between rounds.

Do I need to learn all five Redis data structures?

Learn strings and expiry first — they cover sessions, counters, and caching, which is most beginner work. Add hashes when you store objects, lists when you build queues, sets when you need uniqueness, and sorted sets when you need rankings like leaderboards.

Can I use Redis without Docker?

Yes. macOS users install it with brew install redis, Ubuntu and Debian users can add Redis's official apt repository, and the source tarball compiles on most Linux systems. Docker is just the fastest throwaway setup for learning.

Featured on Twelve Tools Launch Llama Tools Launch your MCP