Skip to content

Redis beyond caching: leaderboards, sessions, rate limits, locks, streams, persistence and the license question

The Redis data structures and the problem each one solves, with real commands, plus persistence, a full memory, the command that blocks everything and the story of the license and Valkey.

Ramon Gomes 12 min read Level: Intermediate

Also available in: Español, Français, Português

Almost every dev knows Redis as "that cache in front of the database". It's a good start, but it leaves out most of what it does. The project itself calls Redis a data structure server, and that's where the value is: each structure solves, with one or two atomic commands, a problem that would take real work in a relational database.

This article goes through the most common uses beyond caching, with the real commands, and through the precautions the official docs call for: persistence, memory, the single-threaded nature and the licensing saga. Versions and figures checked on November 21, 2026, with Redis 8.10.3 as the stable version.

Bakery counter with bread and cold cuts within the clerk's reach, and in the background a half-open door to the stockroom, warm morning light
The counter is fast because everything is within reach. The big stock stays in the back.

Why It's So Fast

Two design choices explain it:

  1. Everything lives in memory. Reading from RAM is orders of magnitude faster than reading from disk.
  2. One command at a time. The docs describe the design as "mostly single-threaded": Redis serves one request at a time. That removes locking and contention between commands, and it's why INCR, ZINCRBY and friends are atomic for free.

The second choice has a price we'll see later: one slow command holds up the whole line.

The Structures and What Each One Solves

Structure What it is Typical use
String Bytes; INCR treats it as an integer Cache, counter, lock, rate limit
Hash Field and value pairs Session, profile, cart
List Items in insertion order Simple queue, last N events
Set Unique items, unordered Tags, "who already liked it"
Sorted set Unique items ordered by score Leaderboard, schedule by time
Stream Append-only log with consumer groups Queue with acknowledgment, events
Geo Points with latitude and longitude "Stores near me"
Bitmap Bits over a string Daily presence of millions of users
HyperLogLog, Bloom Probabilistic structures Counting uniques, "have I seen this email?"
JSON Document with access to its parts Documents without a fixed schema
Vector set (8.0) Vectors with similarity search Semantic search, recommendations

Since version 8, JSON, time series, probabilistic structures and the search engine, which used to ship in the separate Redis Stack bundle, are part of core Redis.

Real-time Leaderboard

The sorted set stores each item with a score and keeps the order on its own. Adding points and looking up a position costs O(log N), even with millions of players.

text
ZADD leaderboard 10 "ana" 8 "bruno" 6 "carla" 14 "davi"
ZINCRBY leaderboard 9 "carla"                 # carla scored 9 points: now she has 15
ZRANGE leaderboard 0 2 REV WITHSCORES         # top 3, highest to lowest
ZREVRANK leaderboard "ana"                    # ana's position (starts at 0)
Two leaderboards show before and after ZINCRBY: carla goes from 6 to 15 points after gaining 9 and takes first place, followed by davi with 14, ana with 10 and bruno with 8. ZREVRANK returns 0 for carla.
One command adds the points. The order adjusts itself.

In a relational database, the same leaderboard would need an ORDER BY over the whole table on every query, or a positions table that gets recalculated.

Session and Cart with an Expiration

A hash stores several fields under one key, and EXPIRE makes the key go away on its own:

text
HSET session:9f2c user_id 42 name "Ana" plan "pro"
EXPIRE session:9f2c 1800                  # goes away after 30 minutes without renewal
HGET session:9f2c plan

It's the oldest use after caching, and it's still great for server sessions and guest shopping carts.

Rate Limits and Counters

INCR is atomic, which makes the counter safe even with a thousand requests at once. The docs show the per-second limit pattern and warn about a trap: INCR and EXPIRE as separate commands can leave a key with no expiration if the client dies between the two. The official fix is a Lua script, which Redis runs all at once:

lua
local current = redis.call("incr", KEYS[1])
if current == 1 then
  redis.call("expire", KEYS[1], 60)
end
return current

The rate limiting article goes deeper into the algorithms and the race between servers.

Locks Between Processes

To make sure only one process runs something at a time (the 3 a.m. job, for example), you create a key that can only exist once:

text
SET lock:report <random-value> NX PX 30000     # NX: only if it doesn't exist; PX: expires in 30 s
DELEX lock:report IFEQ <random-value>          # Redis 8.4+: deletes only if it's still yours

The random value is what stops you from deleting another process's lock if yours has expired. Before 8.4, this was done with a Lua script.

Three stages show contention for a lock: both workers try SET NX, worker 1 receives OK while worker 2 receives nil and waits; after DELEX lock IFEQ w1, worker 2 receives OK. PX 30000 sets expiration to 30 seconds.
Whoever creates the key first does the work. The other waits its turn.

One important warning, which the docs themselves stress: a lock with an expiration is good for efficiency (avoiding duplicate work). For correctness (when running twice corrupts data), it isn't enough, because of process pauses and replica failures. That debate, between Martin Kleppmann and the creator of Redis, is explained in the scheduled jobs article.

Pub/Sub and Streams: The Two Messaging Options in Redis

Redis has two ways to send messages between processes, and mixing them up is a common mistake.

Pub/Sub is like radio: whoever is tuned in at that moment hears it. The docs are explicit: delivery is at most once. If the subscriber is disconnected or crashes while processing, the message is gone for good.

Streams are an append-only log with consumer groups and acknowledgment, a bit like a compact version of Kafka:

text
XADD orders * order_id 42 total 120.00             # returns an ID like 1763740800000-0
XREADGROUP GROUP billing worker1 COUNT 10 STREAMS orders >
XACK orders billing 1763740800000-0                # acknowledges the processing

A message that was read and not acknowledged stays in a pending list, and another consumer can take it over (XAUTOCLAIM) if the first one dies.

Two columns compare the same message sent while the consumer is offline. On the left, a radio represents Pub/Sub: the message is lost and nothing reaches the returning consumer. On the right, a mailbox represents the Stream: the message waits as pending, is read with XREADGROUP and acknowledged with XACK.
Pub/Sub is live radio. A Stream is a mailbox with a delivery receipt.

When to use each: Pub/Sub for notices that can get lost without harm (invalidating cache across several instances, notifying open screens). Streams when every message has to be processed. And to compare with RabbitMQ, Kafka and SQS, the message queues article has the full picture, including BullMQ, which runs on Redis under the hood.

Geolocation, Uniques and Vectors

Three lesser-known uses that save a lot of code:

text
GEOADD stores -46.6333 -23.5505 "centro" -46.6900 -23.5600 "pinheiros"
GEOSEARCH stores FROMLONLAT -46.65 -23.55 BYRADIUS 5 km ASC   # stores within 5 km, nearest first

PFADD visitors:2026-11-21 "u1" "u2" "u3"                 # HyperLogLog
PFCOUNT visitors:2026-11-21                              # unique visitors, with very little memory

VADD products VALUES 3 0.1 0.8 0.3 product:42            # vector set, Redis 8
VSIM products ELE product:42 COUNT 5                     # 5 most similar products

HyperLogLog counts uniques with a small error and fixed memory, even with millions of items. Vector sets, new in Redis 8, bring similarity search without a separate vector databaseDatabase that stores embeddings and quickly finds those closest to a query, the basis of meaning-based search. Examples: pgvector in Postgres, Qdrant, Pinecone., which helps if you already run Redis and want to get started with RAG.

Persistence: Does Redis Lose Everything on Restart?

Not necessarily, but it depends on the configuration. There are two mechanisms, and they can work together:

RDB (snapshot) AOF (append-only file)
How it works A snapshot of memory every so often Writes every change to a file, replayed on startup
How much a crash can lose The last few minutes Up to 1 second with everysec (the AOF default)
Out-of-the-box default On: after 1 h with 1 change, 5 min with 100, 1 min with 10,000 Off (appendonly no)
Two timelines compare RDB, with periodic snapshots, and AOF, which writes every command. A power cut highlights in red the minutes lost since the last RDB snapshot and only the last second in AOF.
With the out-of-the-box setup, a hard crash takes the last few minutes with it.

The docs recommend using both together if you want data safety comparable to PostgreSQL, and advise against AOF alone. On a clean restart (SHUTDOWN), nothing is lost. The risk is the hard crash.

The practical lesson: if the data only exists in Redis and can't disappear, configure persistence on purpose. If it's a copy of something in the database, the default setup is fine.

Memory: What Happens When It Fills Up

Redis has to fit in RAM. Two settings decide what happens at the limit:

  • maxmemory: how much it can use. On 64-bit systems, the default is no limit.
  • maxmemory-policy: what to do when it hits the limit. The default is noeviction: writes start returning errors.

This surprises people who use Redis as a cache without configuring anything: instead of dropping the oldest data, it starts refusing writes. For caching, the docs suggest allkeys-lru (drops the least recently used) as a good default. And if the same instance holds both cache and data that can't disappear, the recommendation is to split them into two instances.

The Command That Blocks Everything

Since Redis serves one command at a time, one slow command makes everyone wait.

Three lanes show GET, SET and INCR commands served by Redis with a response of about 1 ms, the queue blocked by KEYS * over millions of keys with a response in seconds, and SCAN walking through the keys in small chunks.
One slow command at the front and the whole line stops.

The docs name KEYS in production as a very common cause of slowness. Use SCAN, which walks through the keys a little at a time. The same goes for operations on huge collections (SMEMBERS on a set with millions of items) and for lots of keys expiring in the same second.

I/O threads (off by default) parallelize network reads and writes on machines with four or more cores, but command execution still happens on a single thread.

The Licensing Saga and Valkey

Redis was BSD (open source) up to version 7.2. In March 2024, Redis Inc. switched the license to RSALv2 and SSPLv1, which aren't OSI-approved; the announcement itself admitted Redis was no longer open source by the OSI definition. Eight days later, the Linux Foundation announced Valkey, a fork of version 7.2.4 under BSD, backed by AWS, Google Cloud, Oracle and others.

In May 2025, Redis 8 added AGPLv3, which is OSI-approved, as a third option. The CEO acknowledged in the announcement that the earlier change had hurt the relationship with the community.

Where things stand today:

License Current version Notes
Redis RSALv2, SSPLv1 or AGPLv3 8.10.3 Vector sets, Arrays, Query Engine in the core
Valkey BSD 9.2.0 Offered by ElastiCache and Memorystore; compatible with Redis 7.2
Dragonfly Its own license, not OSI 2.1 Free in production up to 100 vCPUs
Garnet (Microsoft) MIT 2.2 Speaks the same protocol

For most apps, any of them works, because the clients speak the same protocol. The license matters if you offer Redis as a service to third parties, and the new Redis 8 features may not exist in Valkey.

And if you run on serverless, where long-lived TCP connections are a problem, Upstash offers Redis over a REST APIContract that defines how one program asks another for data or actions: which endpoints to call, what to send and what comes back. On the web, usually HTTP with JSON., with a free plan of 500 thousand commands per month.

Cartoon of a handyman with a tool belt full of different tools, hammer, wrench, tape measure and flashlight, while a customer points only at the hammer and asks if he doesn't do anything else
Everyone knows the hammer. The belt holds a lot more.

Quick check

1. Which Redis structure is the best fit for a player leaderboard?
Show answer

Answer: Sorted set

It keeps items ordered by score, with updates in O(log N).

2. What happens to a Pub/Sub message when the subscriber is disconnected?
Show answer

Answer: It's lost

Pub/Sub delivers at most once. To keep messages, use Streams.

3. With the out-of-the-box setup, what does Redis do when memory hits maxmemory?
Show answer

Answer: Starts refusing writes with an error

The default is noeviction. For caching, set a policy like allkeys-lru.

Frequently Asked Questions

Does Redis replace the database?

For most systems, no. It complements it: hot, temporary or derived data lives in Redis; the source of truth stays in a database with transactions and rich queries.

Redis or Valkey?

For caching, queues and locks, both work the same. If you need the new Redis 8 features (vector sets, Query Engine), go with Redis. If the BSD license matters or your cloud provider only offers Valkey, go with Valkey.

Does Redis work as a production queue?

With Streams or with BullMQ, yes, for many cases. Remember that everything lives in memory and depends on the persistence you configured.

What's the maximum size of a value?

A string can be up to 512 MB, but large values make latency worse for everyone. Keep values small.

How do I run it locally?

With Docker: docker run -p 6379:6379 redis:8. And redis-cli to try the commands in this article.

References

Checked on November 21, 2026:

Source: https://ramongomessilva.com.br/blog/redis-beyond-caching · Accessed on December 02, 2026

Share Share on LinkedIn Share on X
Cite this article

Ready-made reference, with today as the access date.

ABNT

Brazilian standard (NBR 6023). Use it in theses and academic papers submitted in Brazil.

GOMES, Ramon. Redis beyond caching: leaderboards, sessions, rate limits, locks, streams, persistence and the license question. Ramon Gomes, 30 nov. 2026. Disponível em: https://ramongomessilva.com.br/blog/redis-beyond-caching. Acesso em: 2 dez. 2026.

APA

American Psychological Association style. Common in scientific papers and journals, especially in the social, behavioral and health sciences.

Gomes, R. (2026, November 30). Redis beyond caching: leaderboards, sessions, rate limits, locks, streams, persistence and the license question. Ramon Gomes. https://ramongomessilva.com.br/blog/redis-beyond-caching

BibTeX

Format for LaTeX users (Overleaf, for example). Paste it into your .bib file or import it into Zotero or Mendeley.

@online{gomes2026redisbeyondcaching,
  author = {Gomes, Ramon},
  title = {{Redis beyond caching: leaderboards, sessions, rate limits, locks, streams, persistence and the license question}},
  organization = {Ramon Gomes},
  year = {2026},
  month = nov,
  date = {2026-11-30},
  url = {https://ramongomessilva.com.br/blog/redis-beyond-caching},
  urldate = {2026-12-02}
}
Found a mistake?

Wrong fact, broken link, outdated information: tell me and I will fix it.

10 to 2,000 characters. If you can, point to the right source.

Only so I can reply. It never shows on any page of the site.

Written by

Ramon Gomes

Software Engineer

Full stack software engineer. I like taking a messy problem, listening to the people who live with it and shipping something that holds up day to day. These days I split my time between my own products, applied AI and client work.

Available for projects

Need Something Like This Built?

I build websites, systems, apps and AI automations, from design to deploy. Tell me what you need or see what I offer.

Related Articles