Redis Basics — Database

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…

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:

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

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)

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:

  1. GET product:1. If it holds something, that's a cache hit: send it to the customer, the database isn't touched.
  2. If it's (nil), that's a cache miss: read the database with SELECT id, name, price FROM products WHERE id = 1;.
  3. 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:

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"

⚠️ Stale caches, full memory

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".

What you will learn