
Your product page takes 800 milliseconds to load. Nearly all of that is one database query that joins five tables to produce a result which changes perhaps twice a day. You run it thousands of times an hour.
The usual fix is three lines of code and a Redis server: store the result in memory, give it an expiry time, and serve the stored copy until it runs out.
That is how most people meet Redis. But calling it a cache undersells it. Redis is a server full of data structures, and once you see it that way, a lot of awkward problems (rate limits, queues, leaderboards, sessions, locks) get short answers.
What Redis is
Redis is an in-memory data store. All the data lives in RAM, which is why reads and writes are extremely fast. You talk to it with simple commands over the network, and every value is stored under a key, a name you choose.
What sets it apart from a plain key-value cache is that a value can be a structure, with commands that work on it directly:
| Type | What it is | Typical use |
|---|---|---|
| String | Text, a number or bytes | Cached pages, counters, flags |
| Hash | A small record of fields and values | A user session, an object |
| List | An ordered list you push and pop at either end | Simple queues, recent items |
| Set | Unique members, no order | Tags, "who has seen this" |
| Sorted set | Unique members, each with a score, kept in order | Leaderboards, time-ordered feeds |
| Stream | An append-only log with consumer groups | Event pipelines, job queues |
Commands run one at a time on a single thread, so each command is atomic: nothing else can interleave halfway through an INCR.
A note on licences and forks
Redis was open source under a BSD licence for most of its life. In 2024 the company behind it moved to more restrictive source-available licences, and the community responded with Valkey, a fork under the Linux Foundation that stays BSD-licensed. Redis later added the AGPL as a licensing option. For everyday use the commands in this guide work the same on both. If you use a managed service, check which one you are actually getting.
Why teams choose it
- Speed. Reads and writes happen in memory, so responses are typically well under a millisecond on a local network.
- The right tool is already in the box. A sorted set is a leaderboard. A string with an expiry is a session. You write very little code.
- Expiry is built in. Any key can be given a time to live (TTL), after which Redis deletes it for you.
- Simple to run. One small server process, a readable configuration file, and clients for every language.
Where Redis fits, and where it does not
A strong choice for:
- Caching query results, rendered pages and API responses
- Sessions and short-lived tokens
- Rate limiting and counters
- Leaderboards and rankings
- Lightweight queues and background jobs
- Publishing live updates between services
Look elsewhere when:
- It would be your only copy of important data. Redis can save to disk, but it is designed around memory. Keep the source of truth in a database such as PostgreSQL or MySQL.
- The data is bigger than the RAM you can afford. Memory is expensive compared with disk.
- You need to query by anything other than the key. There is no
WHEREclause in core Redis. If you need flexible queries, joins or reports, use a database built for them. - You need a durable, replayable event log at large scale. Apache Kafka is designed for that.
Using it the right way
Examples use redis-cli, the command-line client.
redis-cli -h localhost -p 6379
Name keys with a pattern
Keys are just strings, so agree on a convention. Colons are the common separator:
user:42:profile
session:9f8a7c
cache:product:1001
rate:login:203.0.113.7
Consistent prefixes make keys easy to find, to expire together and to protect with permissions.
Cache with an expiry, every time
The pattern is called cache-aside: look in Redis first, fall back to the database, then store the answer.
GET cache:product:1001
(nil)
SET cache:product:1001 "{\"name\":\"Waffle cone\",\"price\":350}" EX 300
GET cache:product:1001
TTL cache:product:1001
EX 300 sets a five-minute time to live in the same command as the write. When the product changes, delete the key (DEL cache:product:1001) so the next read refreshes it. A cache entry with no expiry is a stale bug waiting to be noticed.
Count and limit
INCR rate:login:203.0.113.7
EXPIRE rate:login:203.0.113.7 60 NX
INCR adds one and returns the new value, atomically. EXPIRE ... NX starts a 60-second window only if the key has no expiry yet. If the count passes your limit, refuse the request. That is a working rate limiter in two commands.
Store objects as hashes
HSET session:9f8a7c user_id 42 role admin theme dark
HGET session:9f8a7c role
HGETALL session:9f8a7c
EXPIRE session:9f8a7c 1800
A hash lets you read or change one field without fetching and rewriting the whole object.
Rank with a sorted set
ZADD leaderboard 1500 "asha" 1720 "ben" 1310 "chen"
ZINCRBY leaderboard 250 "chen"
ZRANGE leaderboard 0 2 REV WITHSCORES
ZREVRANK leaderboard "asha"
Redis keeps the set ordered by score as you write, so "top ten" and "what is my rank" are cheap questions.
Take a lock safely
SET lock:invoice:881 "worker-7-a1b2c3" NX PX 30000
NX means "only if the key does not exist", and PX 30000 makes the lock expire after 30 seconds so a crashed worker cannot hold it forever. Only the worker whose token is stored should release it. This is fine for avoiding duplicate work. It is not a guarantee strong enough for money.
Set a memory limit and a policy
By default a self-hosted Redis has no memory limit. Decide what happens when memory fills up before it does:
CONFIG SET maxmemory 2gb
CONFIG SET maxmemory-policy allkeys-lru
allkeys-lru removes the least recently used keys to make room, which suits a cache. If Redis holds data you cannot lose, such as a job queue, use noeviction so writes fail loudly instead of data vanishing quietly. Put the same settings in redis.conf so they survive a restart.
Decide how much durability you need
Redis has two ways to save to disk:
- RDB snapshots write the whole data set to a file at intervals. Compact and quick to load, but you lose whatever changed since the last snapshot.
- AOF (append-only file) logs every write. With the usual
appendfsync everysecsetting you risk about a second of data.
For a pure cache you can leave persistence off. For anything else, turn AOF on, and add a replica so a server failure does not mean an outage.
Secure it
Redis was designed to sit on a private network. Never expose it directly to the internet. Require a password, use TLS where your provider offers it, and give applications limited accounts with access control lists (ACLs):
ACL SETUSER shop_app on >use-a-long-random-one ~cache:* ~session:* +@read +@write -@dangerous
That user can read and write only keys starting with cache: or session:, and cannot run administrative commands such as FLUSHALL.
Common mistakes
- Running
KEYS *in production. It walks every key and blocks the server while it does. UseSCAN, which works in small steps:SCAN 0 MATCH session:* COUNT 100. - Keys without a TTL. Memory fills with things nobody will read again.
- No
maxmemory. The server grows until the operating system kills it. - Very large values. A hash with millions of fields or a 100 MB string makes every operation on it slow, and deleting it with
DELblocks the server. Split big structures, and delete large keys withUNLINK, which frees memory in the background. - Treating the cache as the truth. If losing Redis loses data, you have a database with the wrong durability settings.
- Everything expiring at once. If a thousand cached entries share the same TTL, they all miss together and stampede the database. Add a little randomness to expiry times.
- A new connection per request. Use your client library's connection pool.
- An open port. An unprotected Redis on the internet will be found and abused. Bind to private addresses and require authentication.
Quick reference
| Task | Command |
|---|---|
| Is the server alive? | PING |
| Type of a key | TYPE user:42:profile |
| Time left on a key | TTL cache:product:1001 |
| Find keys safely | SCAN 0 MATCH cache:* COUNT 100 |
| Memory used by a key | MEMORY USAGE leaderboard |
| Memory overview | INFO memory |
| Number of keys | DBSIZE |
| Find the largest keys | redis-cli --bigkeys |
| Recent slow commands | SLOWLOG GET 10 |
| Delete without blocking | UNLINK big:key |
| Watch commands live (briefly, it is costly) | MONITOR |
Redis is at its best as a fast helper beside your main database: small keys, clear names, an expiry on everything temporary and a memory limit you chose on purpose.
Exploring Redis with CreamDB
redis-cli shows one answer at a time. To see what is actually in a server, CreamDB has a Redis explorer in the browser, with nothing to install.
- Keys are grouped into folders by their colon-separated prefixes, so
session:*andcache:*are easy to tell apart, and you can filter by pattern. - Each key shows its type: string, hash, list, set, sorted set or stream. Open one to page through its fields or members.
- See and change a key's TTL, and switch between numbered databases.
- Ask in plain English and the assistant picks the Redis command and shows the result.
The assistant only runs reading commands on its own. Anything that changes data waits as an approval card that you answer, and with read-only mode on, the server accepts reading commands only. A Redis server on a private network can be reached through an SSH tunnel, and connection passwords are encrypted at rest.
It is free to start, and your SQL databases live in the same tab.
About the author
- CreamDB is a web-based database explorer with an AI assistant. Connect your databases, ask questions in plain English and get answers, tables and charts from any browser. Product news and tips here.
Comments
Join the discussionNo comments yet. Be the first to comment.




