The Milk Coffee page is opened thousands of times a day. Each time, Sunset Coffee's app sends the same SELECT to the database, for a price that rarely changes. The cashier doesn't work like that: the best-selling cakes sit in the display case next to the till, so she doesn't walk to the storeroom for every customer. The case is small and cakes go stale, so each one gets a use-by date.
In an app, the role of that display case is often played by Redis. Redis is an in-memory key-value store: a database that keeps pairs of a key and a value in RAM, then fetches them again by key (the key-value type from the Types of Database lesson). Because the data is in RAM, answers usually come back in under a millisecond. The cakes in the case are data that is read often, such as the price of Milk Coffee. The storeroom is your main database, which keeps its data on disk. A cake's use-by date is a TTL in Redis.
Why Redis is fast, and when to use it
Redis is fast because its data is kept in RAM (memory), not on disk. Reading RAM is far quicker than reading a disk, and Redis finds a value straight from its key, with no complicated query.
The downside: RAM is limited and expensive. Depending on its persistence settings (how Redis copies data to disk), the last few seconds to few minutes of changes can also be lost when the server stops. So Redis is not the place for your main data. It is used next to the main database for:
- caching: keeping the results of queries that are read often,
- sessions: who owns this login, checked on every request,
- counters and rate limiting (limiting how many times something may be done): page views, a limit of 3 OTPs (one-time codes) a minute,
- queues: lines of jobs to do,
- leaderboards: rankings by points.
Redis has two ways to copy data to disk: RDB, a snapshot (a copy of all the data) every so often, and AOF, which writes every command that changes data to a file. These are Redis's persistence options, from the one you will meet most:
| Setting | What can be lost when the server stops | When to pick it |
|---|---|---|
| RDB, regular snapshots (the default) | the changes since the last snapshot, usually a few minutes | Caches and data that can be rebuilt. |
AOF with appendfsync everysec (appendonly yes) |
about 1 second | Sessions and queues that must not lose much. |
| RDB + AOF | about 1 second, plus snapshots for backups | Redis that holds important data. redis.io suggests it when you want data safety close to PostgreSQL. |
| No persistence | everything | A pure cache: after a restart, the cache is filled again from the main database. |
You talk to Redis through redis-cli, Redis's command-line program. Its prompt (the sign at the start of the line where you type) is 127.0.0.1:6379>, because Redis runs on your own computer (127.0.0.1) and waits for commands on port 6379 (a numbered entrance on that computer).
First commands: SET, GET, INCR
A line that starts with the prompt is your command, and the line below it is Redis's answer:
127.0.0.1:6379> SET session:7f3a "1"
OK
127.0.0.1:6379> GET session:7f3a
"1"
127.0.0.1:6379> GET session:0000
(nil)
127.0.0.1:6379> INCR views:product:1
(integer) 1
127.0.0.1:6379> INCR views:product:1
(integer) 2
SET key valuestores the value under that key. Redis answersOK.GET keyreturns the value in quotes. A key that doesn't exist is answered(nil), meaning empty.INCRadds 1 to the number in the key and answers(integer)with the result. A key that doesn't exist yet counts as 0. INCR is atomic: reading the number, adding 1 and storing the result happen as one step, so two requests adding at the same moment never overwrite each other.- Key names are usually built from parts joined by colons, for example
kind:id:partorviews:product:1(the view count of product 1). For Redis a name is only text, but this pattern makes keys easy for people to read.
TTL: data that expires by itself
The SET command below stores Milk Coffee's data (as JSON) under the key product:1:
127.0.0.1:6379> SET product:1 '{"id":1,"name":"Milk Coffee","price":450}' EX 60
OK
127.0.0.1:6379> TTL product:1
(integer) 60
127.0.0.1:6379> TTL session:7f3a
(integer) -1
Then 60 seconds later:
127.0.0.1:6379> TTL product:1
(integer) -2
127.0.0.1:6379> GET product:1
(nil)
EX 60gives the key a TTL (Time To Live) of 60 seconds. After that Redis deletes it by itself. This is the feature for temporary data: caches, sessions, OTP codes.TTL keyanswers the seconds left.-1means the key exists but has no TTL (it lives forever),-2means the key doesn't exist.EXPIRE key 60puts a TTL on a key that already exists.PERSIST keyis the opposite: it removes the TTL.- Don't confuse TTL with
maxmemory(the RAM limit for Redis) and eviction policies likeallkeys-lru: those settings remove keys when RAM is full, not because their time is up.
Cache-aside: ask Redis first
The most common way to use Redis as a cache is called cache-aside. For every request for the Milk Coffee page:
GET product:1. If it holds something, that's a cache hit: send it to the customer, the database isn't touched.- If it's
(nil), that's a cache miss: read the database withSELECT id, name, price FROM products WHERE id = 1;. - Store the result:
SET product:1 '...' EX 60, so the next request hits.
This is the trace in this page's Lab, on a virtual clock (a pretend clock that you move forward yourself):
| second | Redis answers | result | database |
|---|---|---|---|
| 0 | (nil) |
miss | read, then SET ... EX 60 |
| 5 | "{...450}" |
hit | not touched |
| 61 | (nil) |
miss, TTL ended | read again |
In Laravel (with CACHE_STORE=redis, so Laravel's cache is kept in Redis), those three steps take one line:
$product = Cache::remember('product:1', 60, fn () => Product::find(1));
Cache::remember checks the key 'product:1'. The function at the end of the line only runs on a cache miss, and its result is kept for 60 seconds.
The stale cache
Now the admin raises Milk Coffee's price to $5.00 in the database at second 10, while product:1 in Redis still holds $4.50 until second 60. Which price does a customer opening the page at second 15 see? They get a cache hit, so $4.50. Cached data that no longer matches the database is called a stale cache.
Two ways to fix it:
- Delete the key after changing the database:
DEL product:1. The next request misses and reads $5.00. This is called cache invalidation. - A short TTL: the shorter the TTL, the shorter a stale cache can last, but the more often the database is read.
Redis's five data structures
A value in Redis isn't only text. Pick the structure that fits the need:
| Structure | Commands | Fits |
|---|---|---|
| String | SET, GET, INCR |
counters, a simple cache |
| Hash | HSET, HGET, HGETALL |
a user profile, an object |
| List | RPUSH, LPOP, LRANGE |
queues, latest notifications |
| Set | SADD, SISMEMBER, SMEMBERS |
unique tags, roles |
| Sorted Set | ZADD, ZRANGE ... REV |
leaderboards, rankings |
Here is one example command for each structure except String, which you have already seen above:
127.0.0.1:6379> HSET user:1 name "Budi" phone "07700 900999"
(integer) 2
127.0.0.1:6379> RPUSH queue:orders "order:4" "order:5"
(integer) 2
127.0.0.1:6379> LPOP queue:orders
"order:4"
127.0.0.1:6379> SADD tags:product:1 coffee milk coffee
(integer) 2
127.0.0.1:6379> ZADD points 120 Budi 95 Siti 40 Andi
(integer) 3
127.0.0.1:6379> ZRANGE points 0 -1 REV WITHSCORES
1) "Budi"
2) "120"
3) "Siti"
4) "95"
5) "Andi"
6) "40"
- A Hash keeps many fields under one key, like an object: Budi's name and phone number.
HSETanswers how many fields are new. - A List is ordered.
RPUSHputs on the right,LPOPtakes from the left: the first one in is the first one handled, exactly a queue. - A Set never stores a value twice.
coffeeis added twice, so only 2 tags are kept. - A Sorted Set keeps members with a score and is always in order.
0 -1means from the first member to the last,REVreverses the order (so the most points come first), andWITHSCORESshows the scores too.
⚠️ Stale caches, full memory
- Keeping your main data only in Redis. Its RAM can fill up and the last changes can be lost when the server stops. Orders stay in the main database.
- A cache with no TTL. The key lives forever: the data can stay stale and RAM slowly fills up.
- Forgetting
DELafter anUPDATE. Customers see the old price until the TTL ends. KEYS *in production. It checks every key at once and makes Redis stop serving everyone else meanwhile. UseSCAN, which checks the keys a few at a time.- Misspelling the structure in the exercise. Return the exact text:
"String","Hash","List","Set","Sorted Set"(capital first letters, one space).
TL;DR: Redis is an in-memory key-value store: fast because its data is in RAM, looked up by key, and answered as OK, "value", (nil) or (integer) n. Use it for caches, sessions, counters, queues and leaderboards (rankings), not as the only copy of your data. A TTL, the lifetime of a key (EX 60, EXPIRE, TTL), makes a key delete itself. The TTL command answers -1 for a key with no TTL, and -2 when the key doesn't exist. The cache-aside pattern: GET first, on (nil) read the database then SET ... EX; after the data changes, delete the key with DEL so the cache doesn't go stale (out of date with the database). The structures: String for counters, Hash for user profiles, List for queues, Set for unique tags, Sorted Set for leaderboards.
⚡ Keys and values in RAM
Write:
127.0.0.1:6379> SET session:7f3a "1"
OK
127.0.0.1:6379> GET session:7f3a
"1"
Guess first: why does Redis usually answer in under a millisecond?
Its data is kept in RAM, not on disk, and found straight from its key.
Meaning: Redis is an in-memory key-value store: a database that keeps pairs of a key (a name) and a value (the contents) in RAM. SET stores the value "1" under the key session:7f3a, and GET fetches it again. Use Redis for caches, sessions, counters, queues and leaderboards (rankings), not as the only copy of your data.
⚡ TTL: gone by itself
Write:
127.0.0.1:6379> SET product:1 '{"id":1,"name":"Milk Coffee","price":450}' EX 60
OK
Meaning: Here Redis keeps Milk Coffee's data as a cache, a copy of database data that is read often. EX 60 gives the key 60 seconds to live (a TTL), then Redis deletes it by itself. After the price changes in the database, delete the key with DEL so the cache doesn't go stale (out of date with the database).
⚡ Five data structures
Meaning: A value in Redis can be one of five data structures. String for counters, Hash for user profiles, List for queues, Set for unique tags, and Sorted Set for leaderboards.
In the exercise, your function returns the name of the structure for a need, with the exact text: "String", "Hash", "List", "Set", "Sorted Set".