Redis: cache, sessions, queues, and other use cases
What Redis is really for: cache with TTL and eviction, session store, rate limiting, queues, pub/sub, and distributed locks, and why it is not your database.
Every application that grows hits the same wall: a query that was instant at launch now takes 400ms because the table has millions of rows and the JOIN shows no mercy. You add indexes, you optimize, and the database still becomes the bottleneck at peak. At some point someone says "put a Redis in front of it" — and it works. But Redis is not just a cache: people use it for sessions, for rate limiting, for an improvised queue, for game leaderboards, for distributed locks. The catch is that each of those uses has its own traps, and the question "it lives in memory, can I lose data?" deserves an honest answer before you trust anything important to it.
This piece covers the real uses of Redis, when each makes sense, and where the Swiss-army knife cuts the hand that holds it.
What Redis is, in practice
Redis is a key-value store that lives in RAM. It is fast because of that: no disk in the critical path, no SQL parser, no query planner. You ask for a key, it returns the value. The structures go beyond plain strings — there are hashes, lists, sets, sorted sets, and each exists because it solves a specific problem.
It is single-threaded for command execution, which scares people coming from relational databases. In practice that is an advantage: no lock contention, no race conditions between commands, every operation atomic by definition. A single modern core handles tens of thousands of operations per second because each command takes microseconds. The bottleneck is usually the network and the payload size, not the Redis CPU.
Cache: the use that justifies the install
The most common pattern is cache-aside. The application asks Redis first; if the key exists (cache hit), it uses the value; if it does not (cache miss), it reads the database, writes to Redis with a TTL, and returns.
GET user:42:profile
SET user:42:profile "{...}" EX 300
The EX 300 sets a TTL of 300 seconds. Past that, the key expires on its own and the next access reloads from the database. TTL is what stops the cache from serving stale data forever — without it you become hostage to manual invalidation, the source of half the cache bugs in history.
When memory fills up, the eviction policy kicks in. The default noeviction makes Redis refuse new writes — terrible for a cache. For caching you want allkeys-lru, which discards the least recently used keys. There is also allkeys-lfu (least frequently used), useful when the access pattern is stable. Configure this explicitly; the default will bite you during a traffic spike.
A note from someone who got burned: a cache is not where you keep the only copy of anything. If a key disappears through eviction or a restart, the system has to survive by reading from the database. Cache accelerates; it is not the source of truth.
Session store
Storing user sessions in Redis is almost mandatory once you have more than one application server. Without it, the session is stuck in one process's memory and the load balancer sends the user to another machine that does not know them — or you pin the user to a server (sticky sessions) and lose flexibility.
A session has a natural TTL: it expires on inactivity. You store it in a hash and renew the expiration on each request.
HSET sess:abc123 user_id 42 role admin
EXPIRE sess:abc123 1800
Here the tolerance for loss differs from cache. Losing a session means logging the user out — annoying, not catastrophic. Still, it is the kind of data that makes you start asking about persistence, which I get to below.
Rate limiting
Limiting requests per user or per IP is a case where Redis atomicity shines. The classic pattern is INCR plus EXPIRE:
INCR rate:ip:203.0.113.5
EXPIRE rate:ip:203.0.113.5 60
The first request creates the key at 1 and marks a 60-second expiration. The next ones increment it. When the counter passes the limit, you block until the key expires and resets the window. Because INCR is atomic, there is no risk of two simultaneous requests reading the same value and incrementing wrong — a problem you would have to solve with a lock in a relational database. For more sophisticated windows (sliding window) you use a sorted set, but INCR covers 90% of cases.
Queues: how far Redis goes
You can build a queue with lists. LPUSH inserts on one side, BRPOP consumes from the other in a blocking way:
LPUSH jobs:email "{to: 'x@y.com'}"
BRPOP jobs:email 0
BRPOP waits until an item appears, with no polling. For a simple internal job queue this works and is cheap. Redis Streams improves on it with consumer groups and acknowledgment.
Now the honest part: for a serious queue, a real broker beats Redis. RabbitMQ, SQS, or Kafka deliver what Redis does not give for free — delivery guarantees, dead-letter queues, retry with backoff, robust message persistence, routing. With lists, if the worker grabs the message and dies before processing, the message is gone. You can mitigate with RPOPLPUSH into a processing queue, but you are reimplementing, poorly, what a broker already does well. Use Redis for a queue when the queue is simple and the occasional lost job is acceptable. For payments, no.
Pub/sub, leaderboards, and distributed locks
Redis pub/sub is fire-and-forget: the publisher sends on a channel, active subscribers receive. Anyone not connected at that moment misses the message — do not confuse it with a queue. Good for real-time notifications, cross-node cache invalidation, ephemeral signals.
A leaderboard is the perfect use case for a sorted set. ZADD inserts with a score, ZREVRANGE returns the top N already ordered, and ZRANK gives a member's position — all in logarithmic time. Game ranking, top products, trending: it is almost unfair how convenient it is.
Distributed locking is where the danger lives. The naive version — SET lock:x token NX EX 10 to acquire and DEL to release — looks right and breaks in subtle cases: the process that acquired it can pause (GC, swap), the lock expires, another process takes it, and the first one wakes up and DELs a lock that now belongs to someone else. The correct solution uses a unique token and releases the lock with a Lua script that checks the token before the DEL. For multiple Redis nodes there is the Redlock algorithm, which has its critics. Advice: if you need reliable distributed locking, read a lot before you write; the naive version that seems to work is the one that wakes you at 3 a.m.
Persistence: can I lose data?
The right question. Redis lives in RAM, but it has two persistence mechanisms. RDB takes periodic snapshots of the dataset to disk — fast to restore, but you lose everything changed since the last snapshot if it crashes in between. AOF (append-only file) logs every write operation; it loses less, but the file grows and restoration is slower. You can combine both.
Even with AOF in its safest mode, Redis is not a transactional database with ACID durability in the same league as Postgres. Hence the rule: do not keep the only copy of important data in Redis. Cache, sessions, counters, rankings — things you can rebuild or whose loss is tolerable. The source of truth stays in the main database. If you are torn between a relational database and a NoSQL option for that source of truth, the topic is worth its own read — see relational vs NoSQL databases for the choice context.
A practical detail from operating Redis: when debugging expiration and TTL you end up reading Unix timestamps in logs and in commands like EXPIRETIME, which returns the expiration instant as an epoch. Converting that raw number into a readable date helps you confirm a key will expire when you think it will — quick to do with the timestamp converter.
Frequently asked questions
What is Redis used for?
Redis stores data in memory with very fast access, for cases where latency matters more than absolute durability. The most common uses are caching (speeding up reads that would normally hit the database), session storage, rate limiting, counters, leaderboards with sorted sets, pub/sub, and simple queues. It is an infrastructure Swiss-army knife, but not a replacement for your main database.
Can Redis be used as a primary database?
Technically yes, but it is rarely a good idea. It has persistence (RDB and AOF), but its durability model does not compare to a transactional database, and the cost of keeping everything in RAM grows fast. The healthy practice is to use Redis as an acceleration layer and ephemeral store, keeping the source of truth in a database that survives a crash without losing the last second of writes.
What is the difference between Redis and Memcached?
Memcached is a pure key-value cache, simpler and great if you only want to cache strings. Redis does that and much more: rich structures (hash, list, set, sorted set), optional persistence, pub/sub, Lua scripting, and replication. If your need is strictly string caching and nothing else, Memcached is enough; when in doubt, Redis covers more ground.
Is Redis really single-threaded? Isn't that slow?
It is single-threaded for command execution, and that is not slow because each command takes microseconds and runs entirely in memory. The absence of concurrency between commands removes locks and race conditions and makes every operation atomic. Recent versions use threads for network I/O, but the command logic stays serial — on purpose.
Practical takeaway
Redis is the best thing you can put between the application and the database when latency starts to hurt. For cache, use cache-aside with a TTL and configure allkeys-lru instead of trusting the default. Sessions, rate limiting with INCR+EXPIRE, leaderboards with sorted sets, and pub/sub are uses where it is nearly unbeatable. A list-based queue handles the simple case, but for a serious queue grab a real broker. Distributed locking, do it carefully with a unique token, never the naive version. And above all: configure persistence consciously and never keep the only copy of important data in RAM. Redis accelerates everything; being the source of truth is not its job.
- 01 Does the PageSpeed Score Affect SEO? 100/100 and Failing Google doesn't rank on PageSpeed's 0 to 100 score but on Core Web Vitals from real users. Here's why a site scores 100/100 and still fails in the field.
- 02 Unit test vs integration test: the difference in practice The difference between unit and integration tests with API and database examples: what each one catches, what it costs, and when to use each in your project.