smaple.tr
Backend & APIs

Redis Use Cases: What It Does Well and the Settings Each Job Needs

Mehmet Kurtipek
November 15, 2025
14 min read
Backend & APIs
Redis
Caching
Valkey
Celery

Redis is used for data that must be read or changed very quickly and can live in memory: caching database results, storing user sessions, rate limiting, job queues for background workers, real-time messaging, leaderboards and counters, short-lived locks and, since Redis 8, JSON documents and vector search. Most of these have one thing in common. The data is either temporary or can be rebuilt from somewhere else, so if losing a key would be expensive, keep the original in a database and let Redis hold the fast copy.

The uses also pull Redis in opposite directions. A cache wants old keys thrown out when memory fills up, while a job queue must never lose one. For each use below you get the commands behind it and the setting that decides whether it holds up in production.

Why Redis suits these jobs

Three properties explain almost every use case on this page. The data sits in RAM, so reads and writes never wait for a disk. Values are data structures (strings, hashes, lists, sets, sorted sets, streams and more), and the server changes them for you: to bump a counter you send INCR instead of reading the value, adding one and writing it back. And Redis runs commands one at a time, so a single command is atomic with no locking on your side. When several commands must run as one step, with nothing from another client slipping in between, use MULTI/EXEC or a Lua script. Neither rolls back: in MULTI/EXEC the other commands still run; a Lua script stops at the failing command but keeps the writes it already made.

Every key can also carry an expiry (TTL). That one feature is what keeps sessions, rate limits and locks simple.

Caching

This is where most teams start. The usual pattern is cache-aside: the application asks Redis first, goes to the database on a miss, and writes the result back into Redis with a TTL.

import json
import redis

r = redis.Redis(host="localhost", port=6379, decode_responses=True)

def get_product(product_id, db):
    key = f"product:{product_id}"
    cached = r.get(key)
    if cached is not None:
        return json.loads(cached)
    product = db.fetch_product(product_id)  # your database call
    r.set(key, json.dumps(product), ex=300)  # expires after 5 minutes
    return product

def update_product(product_id, fields, db):
    db.update_product(product_id, fields)
    r.delete(f"product:{product_id}")  # the next read refills it

Delete the key when the row changes, and keep the TTL anyway. It is your safety net for the update path you forgot, because stale data then lives at most five minutes.

Then measure. INFO stats reports keyspace_hits and keyspace_misses, and the Redis eviction docs show how to turn them into a hit rate and what evicted_keys tells you next to it. A cache with a poor hit rate adds a network round trip to every request and saves nothing.

For a pure cache, set maxmemory and choose allkeys-lru, which the Redis docs call a good default. allkeys-lfu favors keys that stay popular over a longer period, so try it if your hit rate disappoints. The default policy, noeviction, rejects writes once memory is full, which is exactly what a cache should not do.

Session storage

With sessions in Redis, any app server can handle any request, so you can add or replace servers without logging anyone out. Store each session under a random ID as a hash or a JSON string, give it a TTL equal to your idle timeout, and refresh the TTL when the user does something.

Eviction is the trap here too. If sessions share an instance with a cache running allkeys-lru, a traffic spike can evict sessions and sign users out. Switching to volatile-lru doesn't help, because it evicts among keys that have a TTL, and every session has one. Either size memory so eviction never reaches the sessions, or give them their own instance with noeviction.

Rate limiting

A fixed-window limiter takes two commands: increment a counter for the current window and give it an expiry.

import time

def allow_request(r, client_id, limit=100, window=60):
    key = f"rate:{client_id}:{int(time.time() // window)}"
    pipe = r.pipeline()  # wrapped in MULTI/EXEC by default in redis-py
    pipe.incr(key)
    pipe.expire(key, window)
    count, _ = pipe.execute()
    return count <= limit

A fixed window lets a client fire up to twice the limit in a short burst around a window boundary. If that matters, use a sliding window: one sorted set per client with request timestamps as scores, trimmed with ZREMRANGEBYSCORE and counted with ZCARD.

Either way, it stops one client from eating the capacity everyone else shares, and it gives each API key a quota you can enforce. It does nothing against a volumetric DDoS attack, which has to be stopped before the traffic reaches your servers.

Job queues and background workers

A list on its own makes a simple queue (LPUSH to add work, BRPOP to wait for it). In practice most teams use Redis through a task library such as Celery in Python, BullMQ in Node.js or Sidekiq in Ruby. The library handles retries, scheduling and acknowledgements, and Redis holds the queues.

Here is how that looked on one of our projects. For EdgeHunters, a betting-analytics company in Dublin, we built and ran more than 65 real-time odds pipelines across 44 sportsbooks from July 2023 to early 2026. Each sportsbook had its own spider running as a Celery worker in Docker, and Redis was the Celery broker holding their queues. Redis also served as a cache for the frontend, and real-time updates reached the frontend over WebSocket.

Those two jobs want opposite settings, and that is the first thing to decide if you copy the setup. An evicted queue key is lost work, so a broker needs noeviction and persistence turned on. A cache wants eviction and usually no persistence at all. The Redis eviction docs make the same point: if one instance would hold both cache keys and keys you must keep, consider running two instances.

If you pair Celery with Redis, read the caveats in Celery's Redis broker docs before you go live. The one that catches people out is the visibility timeout, one hour by default. A task message that hasn't been acknowledged within that time is handed to another worker and the task runs again. Unless you turn on task_acks_late, Celery acknowledges a task just before running it, so the usual victims are tasks scheduled with an ETA, countdown or retry delay further out than the timeout. With task_acks_late on, any task that runs longer than the timeout is at risk as well.

Raising the timeout is the quick fix, and it has a cost: if a worker is killed or the machine loses power, its unfinished tasks wait that long before another worker picks them up. So raise it to cover your longest task, schedule far-future work with a database-backed periodic task instead of a distant ETA (the Celery docs suggest the same), and make tasks safe to run twice. The Celery 5.6 docs ask for the same value in three settings:

from celery import Celery

app = Celery("pipelines", broker="redis://redis-queue:6379/0")
timeout = 4 * 3600  # seconds
app.conf.broker_transport_options = {"visibility_timeout": timeout}
app.conf.result_backend_transport_options = {"visibility_timeout": timeout}
app.conf.visibility_timeout = timeout

If several applications share one broker with different values, the shortest one applies to all of them.

Real-time messaging with pub/sub and streams

Pub/sub is the shortest way to fan an event out to every server that might have an interested user, for example to push a notification down each server's open WebSocket connections. Delivery is at-most-once: a subscriber that is disconnected at the moment a message is published never sees it. For typing indicators or a "new data, refresh" signal, that is fine.

When a message must not be lost, use Streams. A stream is an append-only log. Consumer groups share the work between several workers, and each message stays pending until a worker acknowledges it with XACK, so another worker can claim the messages of one that crashed (XAUTOCLAIM does that in one call). How those events then reach the browser is a separate choice, which we compare in our post on WebSocket and SSE.

Leaderboards, counters and unique counts

Sorted sets keep members ordered by score. A leaderboard is ZINCRBY when a score changes and ZRANGE leaderboard 0 9 REV WITHSCORES for the top ten (ZREVRANGE still works but has been deprecated since Redis 6.2). ZREVRANK returns one player's position counted from the top (starting at 0), without any sorting in your code.

Counters are INCR on a string key. For "how many unique visitors did we have" at scale, HyperLogLog (PFADD, PFCOUNT) gives an estimate in a small, fixed amount of memory per key, and in exchange you accept a small error.

Distributed locks

To stop two workers from processing the same invoice, set a key only if it doesn't exist yet, with an expiry and a random value that only this worker knows:

SET lock:invoice:42 <random-token> NX PX 30000

Release it only if the value is still yours. On older versions that check needs a short Lua script. Redis 8.4 added DELEX key IFEQ value for the job, and Valkey 9.0 added DELIFEQ: the same feature under two names, and a small sign that the two projects are drifting apart. In Python, r.lock("lock:invoice:42", timeout=30) from redis-py handles the token for you.

Know the limit before you trust it with money. Replication is asynchronous, so if the primary fails right after granting a lock, a replica that never saw the lock can be promoted and a second worker can take it. The Redis page on distributed locks covers this case, the multi-node Redlock algorithm and Martin Kleppmann's critique of it, and recommends fencing tokens wherever correctness matters. A practical rule: a Redis lock is good enough when a rare duplicate only wastes some work. If two holders at once would corrupt data, the write itself has to reject the stale holder, for example with a version column or a fencing token that the database checks.

JSON, search and vectors

Redis 8 folded what used to ship separately as Redis Stack into Redis Open Source itself: JSON documents, the query engine (secondary indexes and full-text search), time series, probabilistic types, and a new vector set type for similarity search. That makes Redis a sensible home for a semantic cache in front of an LLM or for a small recommendation feature. For large vector collections you need to keep for years, a database you already back up, such as PostgreSQL with pgvector, is usually the simpler choice.

When Redis is the wrong tool

  • As the only copy of data you can't lose: orders, payments, anything an auditor will ask about. Even with AOF and appendfsync everysec, a crash can cost you the last second of writes.
  • When the data set is much larger than the RAM you are willing to pay for.
  • For ad-hoc queries, joins and reporting. A relational database or a warehouse does that job.
  • For events you need to keep for months and replay into many services. Streams cope with modest volumes, but Kafka or a managed log service fits better at scale.
  • When you run one PostgreSQL, traffic is modest and nothing has been measured as slow. PostgreSQL can run a job queue with SELECT ... FOR UPDATE SKIP LOCKED, and an unlogged table can work as a cache. Redis is one more service to secure, monitor and back up, so add it when profiling points at it.

Redis or Valkey?

You will see both names in 2026, and the history explains why. According to the Redis licenses page, Redis was BSD-licensed up to and including 7.2. In March 2024 Redis announced that from 7.4 onwards it would ship under a dual RSALv2/SSPLv1 license, and neither of those is an open source license. Later that month the Linux Foundation announced Valkey, a fork of Redis 7.2.4 under the BSD license, backed by AWS, Google Cloud, Oracle and others. In May 2025 Redis 8 added AGPLv3 as a third license option, which made Redis open source again.

As of October 2026 the current stable releases are Redis 8.10 and Valkey 9.1. Apart from the lock-release command, everything in this post up to the JSON section works the same on both, and the same client libraries connect to either. The differences:

Redis 8

Valkey 9

License

AGPLv3, RSALv2 or SSPLv1

BSD 3-clause

JSON, search, vectors

Included in Redis Open Source

Separate modules (valkey-json, valkey-search, valkey-bloom), preloaded in the valkey-bundle image

Safe lock release in one command

DELEX ... IFEQ (8.4+)

DELIFEQ (9.0+)

Cost can decide it on AWS: ElastiCache offers both engines, and its pricing page lists Valkey 20% cheaper than Redis OSS on node-based clusters and 33% cheaper than the other engines on serverless.

Our view: if you use Redis as a cache, queue or session store on AWS or Google Cloud, Valkey is a sensible default. If you want JSON, search and vector sets from one server without loading modules, use Redis 8. If you plan to modify the server itself and offer it to others over a network, have someone read the AGPL before you choose.

Before you go to production

  1. Set maxmemory and a maxmemory-policy that fits the job: allkeys-lru for caches, noeviction for queues, sessions and locks.
  2. Choose persistence on purpose. A cache can run without it. Queues and sessions want AOF with appendfsync everysec, plus RDB snapshots for backups.
  3. Keep Redis off the public internet. It is designed for trusted clients on a trusted network, so bind it to private interfaces, create ACL users and turn on TLS when traffic leaves networks you control. Watch out with the official Docker image: it ships with protected mode off, so docker run -p 6379:6379 redis:8 publishes a Redis with no password on every interface of the host, open to anyone who can reach the machine, or to the whole internet if it has a public IP. Publish it as -p 127.0.0.1:6379:6379 or keep it on a private Docker network.
  4. Split instances by role as soon as one Redis holds both disposable cache data and data you must keep.
  5. Plan for failure: a replica with automatic failover (Sentinel, or your managed service's own mechanism), and Redis Cluster only when one machine's memory is no longer enough. Cluster spreads keys over 16,384 hash slots, and a command that touches several keys only works if they sit in the same slot. Hash tags put related keys together: {user:42}:cart and {user:42}:profile are hashed on user:42 alone.
  6. Watch memory, hit rate, evicted_keys and slow commands (SLOWLOG). On a large production instance, KEYS * blocks every other client while it runs, so use SCAN instead.

Frequently asked questions

Is Redis a database or a cache?

It can be either, depending on configuration. With persistence and replication it keeps data across restarts like any database. Many teams still use it mainly for data they can rebuild, because everything has to fit in memory and a crash can lose the last second of writes.

Redis or Memcached?

Memcached stores plain string values and has no built-in replication. It is a perfectly good simple cache. If you need anything else from this page (queues, sorted sets, pub/sub, sessions that survive a restart), pick Redis or Valkey.

Is Redis free to use?

Redis 8 is available under AGPLv3, an OSI-approved open source license, and Valkey is BSD-licensed. Running either one unmodified behind your own application costs nothing in license fees. The AGPL adds obligations when you modify the server and make it available to others over a network, so read it first if that is your plan.

Can Redis replace Kafka?

For modest event volumes with short retention, Redis Streams with consumer groups work well and are simpler to operate. For high volume, long retention, or replaying history into many services, Kafka or a managed log service is the better fit.

If you are planning a backend where Redis will carry more than a cache, we're happy to look at the layout with you as part of our backend and API work.

Related Articles

August 1, 2026

Kong vs Traefik vs AWS API Gateway: How to Choose

Kong, Traefik and AWS API Gateway compared as of October 2026: features, licensing, Kubernetes support and what AWS charges for 100 million requests a month.

Read More: Kong vs Traefik vs AWS API Gateway: How to Choose
July 4, 2026

gRPC vs REST for Microservices: When gRPC Is Worth It

When gRPC beats REST between services, what it adds to your operations (load balancing, deadlines, browser access), and what our own protobuf vs JSON test showed.

Read More: gRPC vs REST for Microservices: When gRPC Is Worth It
March 14, 2026

RPA Implementation: From Process Choice to Bots That Keep Running

Most of an RPA implementation is choosing the process and designing for exceptions. The order we work in, current license prices, and what broke in the n8n and LLM automation we built with an agency.

Read More: RPA Implementation: From Process Choice to Bots That Keep Running