Updated 7 min read

Getting Started with Redis: Install, Commands, Gotchas

Install Redis, learn the commands you use daily, and avoid five beginner traps: lost TTLs, racy counters, KEYS, persistence defaults. Tested on Redis 8.0.

redis database tutorial backend
On this page · 6 sections
  1. Install and run
  2. The commands you will use first
  3. Five things that bite in the first month
  4. What to use it for, with a starting point for each
  5. FAQ
  6. Where to go next

Redis is an in-memory key-value server. Every key points at a typed value (a string, hash, list, set, sorted set or stream), every command runs on one thread against data in RAM, and that is why a single instance answers in well under a millisecond. You will use it as a cache, a session store, a counter, a lock, a rate limiter or a small queue.

This post gets Redis running, covers the dozen commands you will type in your first week, and then shows five mistakes that look harmless and are not. Every output below is real: Redis 8.0.2 on Debian 13, an 8-core VM, client and server on the same machine. The scripts are in the repo under course-code/posts/getting-started-with-redis/.

Install and run

# macOS
brew install redis && brew services start redis

# Ubuntu / Debian (installs a systemd service on port 6379)
sudo apt-get install redis-server

# Anywhere with Docker
docker run -d --name redis -p 6379:6379 redis:8

Then check it answers:

redis-cli PING
# PONG

The commands you will use first

SET greeting "hello"          # OK
GET greeting                  # "hello"
SET session:42 "u=7" EX 60    # value that deletes itself after 60 s
TTL session:42                # 60  (seconds left)
TTL greeting                  # -1  (key exists, no expiry)
TTL nosuchkey                 # -2  (key does not exist)
INCR page:views               # 1   (missing key counts as 0)
SET lock:job1 worker-a NX EX 30   # OK  (only if the key is absent)
SET lock:job1 worker-b NX EX 30   # (nil): worker-a already holds it
DEL greeting                  # 1

Key names are just strings. The object:id:field convention (session:42, user:7:cart) costs nothing and makes SCAN patterns and memory reports readable later.

Five things that bite in the first month

1. A plain SET throws away the TTL

SET session:42 "u=7" EX 60
TTL session:42                 # 60
SET session:42 "u=7;theme=dark"
TTL session:42                 # -1   <- the session now lives forever

Overwriting a key with SET resets it to “no expiry”. Code that updates a cached value or a session without re-passing EX slowly fills memory with keys that never go away. Either pass the expiry on every write, or use KEEPTTL:

SET session:42 "u=7" EX 60
SET session:42 "u=8" KEEPTTL
TTL session:42                 # 60

INCR behaves the other way: it keeps the existing TTL (SET views:home 0 EX 100, INCR views:home, TTL still says 100). That asymmetry is exactly why people get caught.

2. GET + SET from your app is a race; INCR is not

A counter written as “read the value, add one, write it back” loses updates as soon as two clients do it at once. race.py runs 8 threads that each add 1,000:

def get_set(n):
    c = redis.Redis(port=6390)          # one connection per thread
    for _ in range(n):
        v = int(c.get("count:getset"))
        c.set("count:getset", v + 1)

def incr(n):
    c = redis.Redis(port=6390)
    for _ in range(n):
        c.incr("count:incr")
count:getset: expected 8000, got 1650
count:incr: expected 8000, got 8000

Three runs gave 1,650, 1,629 and 1,634: about 80% of the increments vanished. INCR is one command, and Redis runs one command at a time, so nothing can slip in between the read and the write. The same rule covers HINCRBY, SADD, LPUSH and friends: push the read-modify-write into Redis instead of doing it in your app. When you need several steps to be atomic, that is what MULTI/EXEC and Lua scripts are for (transactions and Lua).

3. KEYS blocks everyone

With 1,000,000 keys loaded (85 MB of used_memory), SLOWLOG recorded the server-side time of two KEYS calls:

KEYS user:99999*   158 ms   (returned 11 keys)
KEYS *             255 ms

Redis executes commands on one thread, so for those 158 ms no other client gets an answer. In keys_vs_scan.py, a PING sent 20 ms after KEYS * started waited 274–295 ms. On a cache serving a few thousand requests a second, that is a visible latency spike every time someone runs a “quick” debug command.

SCAN walks the keyspace in small pages:

SCAN count=1000   -> 11 keys, 556-622 ms total over ~1,000 calls
one SCAN call     -> 0.56-0.70 ms

The total is slower than KEYS, and that is fine: each call holds the server for under a millisecond, so other clients slot in between. Use SCAN (or redis-cli --scan --pattern 'user:*') for anything you run against a live server.

4. The default config can lose your last minute of writes

A fresh redis-server started without a config file reports:

save        3600 1 300 100 60 10000
appendonly  no
maxmemory   0
maxmemory-policy noeviction

That means RDB snapshots only (after 3,600 s if 1 key changed, 300 s if 100 changed, 60 s if 10,000 changed) and no append-only file. To see what that costs, I took a snapshot, wrote one more key, and killed the process with kill -9:

SAVE                     -> OK
SET order:1001 paid      -> OK
(kill -9, restart)
Done loading RDB, keys loaded: 1000002 ... 0.565 seconds
GET order:1001           -> (nil)

The million older keys came back from the snapshot in 0.57 s; the write after it was gone. With appendonly yes (default appendfsync everysec) the same test returned paid after the restart, at the cost of losing up to about one second of writes on a crash. If Redis only holds a cache you can rebuild, snapshots are fine. If it holds anything you cannot recompute, turn on AOF. The trade-offs are covered in RDB vs AOF.

Note the other two lines as well: maxmemory 0 means no limit, and noeviction means that once the machine runs out of RAM, writes fail with an error instead of old keys being dropped. For a cache, set a limit and an eviction policy, for example maxmemory 2gb and maxmemory-policy allkeys-lru.

5. Benchmarks measure your setup, not Redis

redis-benchmark on this VM, 200,000 requests, 50 clients:

SET:   142,653 requests per second, p50 = 0.183 ms
GET:   139,860 requests per second, p50 = 0.191 ms
INCR:  146,628 requests per second, p50 = 0.183 ms

with -P 16 (16 commands pipelined per round trip):
SET: 1,785,714 requests per second
GET: 2,150,537 requests per second

Pipelining gave 12–15x more throughput from the same server, because most of the cost of a simple command is the network round trip and the system calls, not the work inside Redis. Two practical consequences: batch commands (MGET, MSET, client pipelines) when you have many of them, and don’t quote a “Redis does a million ops a second” figure for your app until you have measured it over your real network, where one round trip is often 0.3–1 ms instead of the 0.18 ms seen on loopback here.

What to use it for, with a starting point for each

JobData type and commandWhere it is explained
Cache in front of a databaseString with SET ... EX, cache-asideCaching with Redis
Session storeHash or string with a TTLStrings, keys and expiry
Counters, rate limitsINCR + EXPIRE, or a sorted setSorted sets, leaderboards and rate limits
LeaderboardSorted set (ZADD, ZREVRANGE)same lesson
Simple job queueList (LPUSH + BRPOP)Lists, hashes and sets
Event fan-out, durable streamsPub/Sub or StreamsPub/Sub and Streams
Mutual exclusion across serversSET key value NX PXDistributed locks

What it is not good at: data larger than RAM, ad-hoc queries over values (there is no “find all users in Pune” without an index you maintain yourself), and anything that needs multi-key transactions across a cluster.

FAQ

Is Redis a database or a cache?

Both. It keeps the whole dataset in memory and can persist it to disk with RDB snapshots and an append-only file. Most teams use it as a cache or a fast secondary store next to a primary database, because the dataset has to fit in RAM and the default persistence settings can lose recent writes.

Why is Redis single-threaded and still fast?

Commands run on one thread against in-memory data structures, so there are no locks and a simple command takes microseconds. Network I/O can use extra threads (io-threads), and the real limit is usually round trips: on this test machine pipelining raised throughput from about 140,000 to over 1.7 million operations per second.

What does TTL -1 and -2 mean in Redis?

TTL returns -1 when the key exists but has no expiry, and -2 when the key does not exist. A key that showed a positive TTL and now shows -1 was probably overwritten by a SET without EX or KEEPTTL.

Should I use KEYS or SCAN?

Use SCAN on any server that serves traffic. KEYS runs in one go: on a million keys it held the server for 158–255 ms here, and every other client waited. SCAN returns results in small pages that each take under a millisecond.

Where to go next

Redis data structures explains when to pick each type. The free Redis course goes from setup to replication and Cluster in 10 lessons, starting with what Redis is and how to run it.

AlgoSimplified logo

AlgoSimplified

Practical engineering courses and technical notes

Share: X LinkedIn

Related articles