跪拜 Guibai
← All articles
Backend

Ten Redis Techniques That Go Way Beyond Caching

By 苏三说技术 ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

These patterns let a team replace heavier infrastructure with Redis alone: a Bloom filter stops cache stampedes, Redisson handles lock renewal safely, and HyperLogLog cuts UV tracking memory from gigabytes to kilobytes. That means lower operating cost and simpler ops, but also forces a judgment call on whether the added client dependencies and approximate results fit the system's consistency requirements.

Summary

Redis is commonly seen as a cache, but it ships with data structures and modules that solve distributed system problems directly. This roundup walks through ten of them, starting with a Bloom filter for cache penetration protection, which fits about 100 million elements in 100MB with a configurable false-positive rate. Redisson's distributed lock improves on raw SET NX with Lua-based atomicity and an automatic renewal watchdog, while its delayed queue leverages Sorted Sets for precise scheduling, like auto-canceling unpaid orders after 30 minutes.

Further entries cover a Lua-driven token bucket for rate limiting, bitmaps that compress daily check-in and online status tracking to pennies of memory, and HyperLogLog's fixed 12KB structure for cardinality estimates within 0.81% error. GEO support (Redis 3.2+) enables radius searches and distance calculations, and the Stream type (Redis 5.0) brings consumer groups, acknowledgments, and replay as a lightweight MQ. Lua scripts give atomic multi-command guarantees, and the RedisJSON module stores and manipulates JSON documents directly.

Each technique includes a code sample and explicit pros, cons, and use cases. The author stresses that Redis remains an in-memory database, so memory cost and persistence strategies still matter for large data sets, and several features lean on the Redisson client, which adds a dependency worth evaluating.

Takeaways
— A Bloom filter stores 100 million elements in about 100MB, with a false positive rate that is configurable (example uses 0.01); "not in set" is always accurate.
— Redisson's distributed lock uses Lua scripts for atomicity and a watchdog that auto-renews the lock, avoiding common SET NX problems like premature expiration and stolen lock releases.
— Redisson's delayed queue is built on Sorted Sets and can handle scenarios like order timeout cancellation, with an example using RBlockingQueue and RDelayedQueue.
— Token bucket rate limiting can be implemented with a small Lua script that increments a counter with an expiry, supporting smooth handling of traffic bursts.
— Bitmaps store 100 million users' check-in states in about 12MB by using user IDs as bit offsets; the BITFIELD command can calculate consecutive days.
— HyperLogLog uses fixed memory of about 12KB to estimate cardinality with roughly 0.81% error, suitable for UV counting and merging daily data into weekly metrics.
— GEO support in Redis 3.2+ uses GeoHash-encoded scores to search by radius or rectangle and compute distances, useful for nearby-store and dispatch features.
— Redis Streams (5.0+) provide consumer groups, message acknowledgment, and history replay, serving as a lightweight MQ with persistence and group coordination.
— Lua scripts run atomically on the server, reducing network round trips; examples include conditional stock deduction and a SETNX-based lock with expiry.
— RedisJSON is a module (included in Redis Stack) that stores JSON documents and allows field-level operations, but requires a separate installation and more memory.
— The author notes Redis is still an in-memory database, so memory cost and persistence planning are necessary for large data volumes.
Conclusions

Most of the advanced features in this list depend on the Redisson client, which bundles lock, queue, and stream abstractions; that convenience comes with a heavier dependency and an implicit trust in Redisson's implementation choices.

The article treats approximate data structures (Bloom filter, HyperLogLog) as acceptable trade-offs for high-concurrency systems, a stance that works only when the use case tolerates false positives or small cardinality errors.

The summary table suggests these features are drop-in replacements for dedicated services like message queues or spatial databases, but failure handling and operational semantics remain on the developer to build.

The emphasis on memory cost is a reminder that Redis's power comes with a price: every advanced structure still lives in RAM, so the real engineering problem is deciding which data genuinely needs in-memory speed versus which can be pushed to disk.

Concepts & terms
Bloom filter
A probabilistic data structure that answers "is this element in the set?" with either 'definitely not' or 'possibly yes', using a fixed-size bit array and multiple hash functions. It saves memory but can return false positives, and elements cannot be removed.
Watchdog (Redisson)
A background thread in Redisson that automatically extends the expiration of a distributed lock as long as the holder is still alive, preventing the lock from expiring mid-task and avoiding deadlocks from manual renewal logic.
Token bucket
A rate limiting algorithm where a bucket holds a fixed number of tokens; each request consumes one token, and tokens replenish at a steady rate. It allows short bursts of traffic up to the bucket size while capping the average rate.
GeoHash
A geocoding system that encodes latitude and longitude into a short alphanumeric string, so nearby points share prefixes. Redis uses it to store locations as sorted-set scores, enabling radius and rectangle searches.
Redis Stream
A log-like data structure in Redis (5.0+) that supports append-only entries, consumer groups, message acknowledgment, and replay from an arbitrary ID, making it a lightweight alternative to full message brokers in some scenarios.
HyperLogLog
A probabilistic algorithm that estimates the cardinality (number of distinct elements) of a large set using a fixed memory of about 12KB, with a typical error of 0.81%. It cannot tell you whether a specific element exists.
Source: juejin.cn ↗ Google Translate ↗ Backup ↗