How to Use Redis the Right Way: Fast Caching Without Losing Data

Title slide reading Use Redis the Right Way with chips for caching, TTLs, persistence and memory limits

Redis caching means keeping frequently used data in Redis, an in-memory key-value store, so your app can answer common reads from RAM instead of making a slower trip to the database. Used this way, Redis is one of the most useful tools in a backend. It is also one of the easiest to misunderstand.

Picture this: your Redis server restarts at three in the morning, and every logged-in user is suddenly logged out. Nothing crashed. The data simply lived in memory. This guide explains what Redis is, why it is so fast, how persistence works, and the habits that keep a fast setup from becoming a fragile one.

In short
  • Redis is an in-memory key-value store with rich data structures like hashes, lists and sorted sets.
  • It sits in front of your database to speed up reads; it should not replace it.
  • Commands run one at a time on a single main thread, so one slow command blocks everyone.
  • Persistence is optional: choose RDB snapshots, AOF logs, both, or neither, on purpose.
  • Set a TTL on every cache key, avoid huge keys, and use SCAN instead of KEYS.
  1. 0:00Intro
  2. 0:28Fast until it quietly fails
  3. 1:22An in-memory key-value store
  4. 2:26Skip the slow trip to the database
  5. 3:16RAM plus one main thread
  6. 4:07RDB snapshots vs AOF logs
  7. 5:07Six jobs Redis does well
  8. 5:52Caching a product page
  9. 6:42Redis as your only database
  10. 7:34TTLs, huge keys and KEYS
  11. 8:37Redis, used the right way
  12. 9:05Use Redis for speed, not storage

Why Redis problems only show up in production

Many teams use Redis every day while quietly treating it like something it isn't. The cost does not appear on a normal day. It appears on a bad one. In testing, Redis rarely restarts and rarely fills up, so the weak spots stay hidden until real traffic and real deploys arrive.

A typical incident stacks several causes. Redis restarts after a deploy. Sessions were never backed up to disk. And at the same time, memory has reached its limit. Each problem alone is manageable. Together, they produce a confusing outage where nothing technically crashed.

The two symptoms are worth recognizing early. Lost sessions happen when Redis held them only in RAM with persistence turned off, so a restart begins from empty and everyone has to sign in again. Write errors happen when Redis reaches its maxmemory limit with no eviction policy: it refuses new writes with an OOM error, and features start failing one by one.

  • Lost sessions: a restart wipes data that was never persisted.
  • Write errors: full memory can reject new writes with an OOM error.

What is Redis? An in-memory key-value store

Redis is an in-memory key-value store with rich data structures. A helpful mental model is a giant shared dictionary that lives in RAM. You always look things up by key, and Redis hands back the value. There are no tables and no joins, so well-chosen key names such as user:42 effectively become your schema.

What makes Redis special is what a value can be. In the example below, SET stores a plain string under user:42:name. HSET writes a field into a hash, LPUSH adds a job to a list, and ZADD places a player into a sorted set with a score.

These structures let Redis do work on the server. It can increment a counter, push onto a queue, or rank a leaderboard without your app reading the whole value and writing it back. And because Redis runs as its own process that every app instance talks to, it is a genuinely shared store rather than a cache tied to one server.

  • Key-value: look up any value directly by its key name.
  • Rich structures: hashes, lists, sets and sorted sets are built in.
  • Shared server: many app servers read and write the same data.
# a plain string
SET user:42:name "Ada"
# hash, list, sorted set
HSET user:42 plan pro
LPUSH jobs email:991
ZADD scores 1500 ada

Why put Redis in front of your database?

Redis exists because teams want fast access to shared data without hitting a slower database on every request. The idea is simple: popular data is answered from memory, and the database only handles what memory doesn't have.

Follow one read. The browser asks the app server for a product page. The app server checks Redis first, because reading from RAM is quick. Only if the key is missing does it continue to PostgreSQL, which remains the source of truth.

Two benefits follow. First, the cache is shared: if you run ten app servers, they all talk to one Redis, so a value cached by one is immediately useful to the others. That is the advantage over an in-process cache. Second, the database gets relief. The same hot rows stop being queried thousands of times, leaving capacity for writes. The key point is that Redis sits in front of the database; it doesn't replace it.

How is Redis so fast? RAM and one main thread

Redis gets its speed from two design choices. The data lives in RAM, and commands run on a single main thread, one after another, like customers at a single counter. No disk seek happens on a read, and no locks are needed between commands, so each one stays very short.

In practice, app clients send requests, the commands line up in order, and the main thread takes one, runs it fully, and sends a reply before starting the next. Because each command is tiny, the line moves quickly.

Both choices come with a trade-off. Keeping data in RAM means your dataset must fit in memory, and that memory is gone when the process stops unless you persist it. Running one command at a time makes every command atomic, so INCR never races with itself. The catch is that a single slow command holds up the whole queue, which matters a great deal later.

  • Data in RAM: memory access is far faster than reading disk.
  • One at a time: each command is atomic, but slow ones block everyone.

RDB vs AOF: how Redis persistence works

Memory does not survive a restart on its own. Persistence in Redis is optional, and it comes in two forms: RDB snapshots and AOF logs. Neither is simply better. Each one answers a practical question: how much data can you afford to lose?

RDB writes a snapshot of memory at intervals. If Redis stops, you lose every write since the last snapshot, but the file is compact and loads quickly on restart. AOF logs every write command instead. With the everysec setting, you lose about one second of writes, but restarts are slower because Redis replays the log, and the file grows until it is rewritten.

Many production setups enable both: AOF keeps the loss window small, while RDB provides compact backups you can copy off the server. At the other end, a pure cache whose every key can be refilled from the database may reasonably skip persistence entirely. What matters is deciding on purpose rather than by default.

  • RDB: periodic snapshots, fast restarts, compact files, loses writes since the last snapshot.
  • AOF: logs every write, about one second of loss with everysec, slower restarts, larger files.
  • Both: small loss window plus portable backups.
  • Neither: acceptable for a cache you can fully rebuild.

What is Redis used for? Six jobs it does well

Redis earns its place because its data structures map neatly onto everyday backend jobs. Each common use lines up with a structure Redis already provides, and that fit is a large part of why it is so popular.

Caching keeps hot query results. Sessions hold login state behind a session ID. Rate limiting counts requests per user with INCR and a TTL. Leaderboards use sorted sets. Queues use lists. And Pub/Sub broadcasts messages to subscribers.

The common thread is fast, shared state, ideally data you can rebuild or can afford to lose a little of. When a job doesn't fit that description, such as payments, think twice before storing it only in Redis.

  • Caching: hot query results
  • Sessions: login state behind a session ID
  • Rate limiting: INCR plus a TTL
  • Leaderboards: sorted sets
  • Queues and Pub/Sub: lists and message broadcasts

Example: caching a product page with cache-aside

Consider an online shop that caches product pages using the cache-aside pattern. In this pattern the application owns the logic, and Redis simply stores whatever the app decides to put in it.

A request arrives for product 42. The app runs GET product:42 and gets nil back. That is a cache miss, so it queries PostgreSQL. It then stores the result with SET and EX 300, so the key expires in five minutes. The next request for the same product is a cache hit, served straight from memory.

Because the database stays the source of truth and Redis holds only a copy, losing Redis would make pages slower, not wrong. When a product changes, the app writes the new price to the database and then deletes product:42, so the next read refills the cache with fresh data. The TTL acts as a safety net if a delete is ever missed.

  • Check Redis: GET product:42
  • Cache miss: query PostgreSQL
  • Store result: SET with EX 300
  • Next request: cache hit
  • On update: delete the key

Should Redis be your only database?

This is where teams get burned. Redis feels so fast and simple that it gradually becomes the only database, without anyone planning persistence or memory limits. The reasoning sounds like: who needs Postgres, Redis is fast. But speed is not durability. With no persistence plan, a restart can lose data. With no memory limit, growth eventually hits a wall.

Redis can store data durably, but only if you configure it that way and size it for your data. Choose RDB, AOF, or both, then actually restart a test server and check what comes back. Set maxmemory so Redis cannot consume the whole machine, and choose an eviction policy, such as allkeys-lru for a cache, so old keys are removed before writes start failing.

The real fix is keeping a durable source elsewhere. Orders, accounts and payments belong in a database built for durability. Redis then does what it does best: making access to that data faster.

  • Plan persistence and test a restore.
  • Set maxmemory and pick an eviction policy.
  • Keep durable data in a real database.

Common Redis mistakes: TTLs, huge keys and KEYS

Even when Redis is used only as a cache, three smaller mistakes cause most incidents: missing TTLs, huge keys, and slow commands like KEYS. You don't need special tooling to find them. A few redis-cli commands reveal all three, as shown below.

Running TTL on a session key and getting -1 means the key never expires. Cache keys without expiry pile up until memory fills with data nobody reads, so set an expiry with EX whenever you write a cache key. The --bigkeys scan reports oversized values, such as a giant hash called feed:all. Reading or deleting one massive value takes long enough to stall other clients on the single thread, so split it up and use UNLINK to delete in the background.

KEYS user:* walks every key in the database and blocks the server while it scans. Since one thread runs everything, that can freeze all other clients. SCAN performs the same search in small batches instead, which is why it is the safe choice in production.

  • Missing TTLs: keys without expiry fill memory.
  • Huge keys: split them; delete with UNLINK.
  • Slow commands: use SCAN, not KEYS, in production.
redis-cli TTL session:9f2
redis-cli --bigkeys
redis-cli KEYS user:*
redis-cli SCAN 0 MATCH user:*

Key takeaways

  • Redis is an in-memory store with rich data structures, best used for fast, shared state.
  • Commands run on one main thread, so keep every command fast.
  • Choose RDB, AOF, or both deliberately, and test a restore.
  • Always set a TTL on cache keys and set maxmemory with an eviction policy.
  • Avoid huge keys and the KEYS command; use SCAN and UNLINK instead.
  • Keep durable data like orders and accounts in a real database.

Frequently asked questions

Does Redis lose data when it restarts?

It can. Redis keeps data in RAM, so if persistence is turned off, a restart starts from empty. Enabling RDB snapshots, AOF logging, or both lets Redis reload data from disk.

What is the difference between RDB and AOF in Redis?

RDB saves snapshots of memory at intervals, giving compact files and fast restarts but losing writes since the last snapshot. AOF logs every write command; with everysec you lose about one second of data, but restarts are slower and the file grows until rewritten.

Why should I avoid the KEYS command in production?

Redis runs commands on a single main thread, and KEYS scans every key at once, blocking all other clients while it runs. SCAN does the same search in small batches, so the server stays responsive.

What happens when Redis runs out of memory?

If Redis reaches its maxmemory limit with no eviction policy, it rejects new writes with an OOM error. Setting an eviction policy such as allkeys-lru for a cache lets Redis remove old keys before writes fail.

Can Redis replace my main database?

Redis can store data durably if you configure persistence and size it properly, but it is safest as a speed layer in front of a durable database. Orders, accounts and payments belong in a database built for durability.

What is the cache-aside pattern?

The app checks Redis first, and on a miss it reads from the database and stores the result in Redis with an expiry. The database stays the source of truth, and the app deletes the cached key when the data changes.

Watch the full video on YouTube →

Souy Soeng

Souy Soeng

Hi there 👋, I’m Soeng Souy (StarCode Kh)
-------------------------------------------
🌱 I’m currently creating a sample Laravel and React Vue Livewire
👯 I’m looking to collaborate on open-source PHP & JavaScript projects
💬 Ask me about Laravel, MySQL, or Flutter
⚡ Fun fact: I love turning ☕️ into code!

Post a Comment

CAN FEEDBACK
Ad