Back to Blog
Custom Software

What Is Redis? Caching, Sessions and When You Need It

What is Redis and what is caching for? Use cases of the in-memory key value store, the cache-aside pattern, TTL and invalidation, sessions, queues and rate limiting, and when Redis is needed and when it is not.

RedisÖnbellekCacheBackendPerformans

Redis is an open source key value data store that keeps data in memory (RAM) rather than on disk. Short answer: its most common use is caching; by keeping frequently read and expensive to compute results in Redis in front of the main database, it shortens response times and takes load off the database. It does not replace the main database; it is a fast layer that sits in front of it.

What is Redis and how does it work?

Redis stores every value under a key: the value of "product:42" can be a JSON string, the value of "cart:alice" can be a list. Because reads come from memory, a single read usually completes in under a millisecond. Besides plain strings it offers data structures such as lists, sets, sorted sets, hashes and streams, so it is used not only as a cache but also as a counter, a leaderboard and a simple queue. Every key can have a time to live (TTL); when it expires, the key is deleted automatically.

Redis has options for writing to disk (RDB snapshots and the AOF log), but by design it is not the system of record. Data that must not be lost, such as orders, payments and user accounts, lives in a relational database; our PostgreSQL or MySQL article helps with that choice. Redis carries a fast-to-read copy of that data.

What is caching for?

Every time a product page opens, the same queries hit the database again and again. A cache keeps a copy of the result for a short while and answers the following requests from that copy. The gain goes both ways: the user gets a faster response and the database stops doing the same work thousands of times. Not all page speed comes from caching; for images, JavaScript and server settings, our ways to speed up a website article gives a broader list.

What is Redis used for?

  • Query and API caching: keeping expensive query results or external service responses for a set time.
  • Session store: when several servers run, keeping the user session in one place that all of them can read.
  • Rate limiting: counting requests per minute for an IP or user and stopping whoever exceeds the limit.
  • Queues and background jobs: lining up work such as emails, notifications or report generation and processing it in a separate worker.
  • Leaderboards and counters: live score tables with sorted sets, view and like counters.
  • Distributed locks: preventing the same job from running on two servers at once, for example making sure only one copy of a scheduled task runs.

The cache-aside pattern: how to set up caching with Redis

The most common pattern is cache-aside (lazy loading). The application asks Redis first; if the value is there, it returns it. If not, it reads from the database, writes the result to Redis with a TTL and returns it. When the data changes, the database is updated first and then the related key is deleted; the next read puts fresh data back into the cache. The Node.js example below shows this flow:

import { createClient } from 'redis';

const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();

// Cache-aside: read from Redis first, fall back to the database on a miss.
async function getProduct(id: string, loadFromDb: (id: string) => Promise<object | null>) {
  const key = 'product:' + id;
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached);

  const product = await loadFromDb(id);
  if (product) {
    // A TTL keeps stale data from living forever.
    await redis.set(key, JSON.stringify(product), { EX: 300 });
  }
  return product;
}

// On every write, the database is updated first and the cache key is removed.
async function onProductUpdated(id: string) {
  await redis.del('product:' + id);
}
Every key in a cache has two questions to answer: when does it die on its own (TTL), and which write deletes it? A key with no answer to either will sooner or later show users stale data.

The most common caching mistakes

  • No TTL: on a write path where invalidation was forgotten, stale data stays forever.
  • Storing user-specific data under a shared key: if the key does not include the user or permission, one user can see another user's data.
  • Treating the cache as the only copy: when Redis restarts or evicts keys because memory is full, the system must be able to recover from the database.
  • Many keys expiring at the same moment: they all fall through to the database in the same second; adding a small random margin to the TTL spreads the load.
  • Caching everything: storing rarely read or already fast data costs memory and brings no gain.

When do you need Redis, and when is it unnecessary?

In an application that runs on one server, has low traffic and already fast queries, adding Redis means one more component to monitor and back up. First measure the slow queries, add missing indexes and try a simple in-process memory cache. Redis starts to make sense when the application runs on several servers and sessions or cache must be shared, when the same data is read many times per second, when an external API is slow or charged per request, or when you need rate limiting, queues or distributed locks. The most practical way to run Redis next to the application during development is a container; see our what is Docker article for that.

Conclusion

Redis is a fast in-memory key value store, used mostly for caching, sessions, queues and rate limiting. Set up well, it becomes a buffer in front of the database; if TTL and invalidation rules are not thought through from the start, it turns into a stale data problem. If you would like to assess together whether your project really needs a cache layer, see our custom software and web development pages or write to us through the get a quote form.

Let's Build Your Project

Get a free consultation for your website, mobile app, or corporate software project.

Get a Free QuoteExplore our Custom Software service