Redis 8.0 Beyond Simple Caching: 16 Powerful Use Cases You Must Try
Redis 8.0 consolidates many previously external modules—JSON, time‑series, vector search, probabilistic data structures, and more—into a single package, and this article walks through 16 concrete scenarios ranging from field‑level cache expiration to AI‑ready vector similarity search, showing exact commands and when to prefer each feature.
Cache with New Hash Commands
Redis 8.0 adds three hash commands— HGETDEL, HGETEX, and HSETEX —that enable field‑level expiration. Example:
# Set a hash field with a 3600‑second TTL
HSETEX session:user:1001 3600 token "eyJhb..." role "admin" last_seen "1746000000"
# Retrieve specific fields and refresh TTL atomically
HGETEX session:user:1001 EX 3600 FIELDS 2 token role HGETEXrefreshes the field’s TTL in a single atomic step, eliminating the need for a separate GET‑then‑SET script.
Distributed Lock
Implement a lock with SET using the NX option and an expiration ( EX) to avoid deadlocks. Example:
# Acquire lock for 30 seconds
SET lock:order:888 "worker-process-42" NX EX 30Release must be done with a Lua script that checks the lock owner before DEL to avoid deleting another client’s lock.
Session Management
Store each session attribute in a hash and use HSETEX for per‑field TTL. Example:
# Store session fields with a 7200‑second TTL
HSETEX session:abc123 7200 user_id "42" username "penglei" role "admin"
# Refresh TTL while reading
HGETEX session:abc123 FIELDS 2 user_id role
# Delete on logout
HGETDEL session:abc123Leaderboard
Sorted Sets ( ZSET) provide O(log N) updates and reads, ideal for game scores, e‑commerce hot items, or content likes.
# Update scores
ZADD game:score 9800 "player:1001"
ZADD game:score 9500 "player:1002"
# Top 10 with scores
ZREVRANGE game:score 0 9 WITHSCORES
# Get a player’s rank (0‑based)
ZRANK game:score "player:1001"Rate Limiting
Two patterns are shown. A simple daily counter uses INCR + EXPIRE. A sliding‑window limiter uses a Sorted Set to store timestamps and removes out‑of‑window entries before counting.
# Simple daily counter
INCR rate:user:1001:20260429
EXPIRE rate:user:1001:20260429 86400
# Sliding window (ZREMRANGEBYSCORE + ZCARD)
ZREMRANGEBYSCORE rate:slide:1001 0 (now-window)
ZCARD rate:slide:1001Message Queue
Lists provide a lightweight queue with LPUSH and blocking BRPOP. For richer semantics, Redis Streams support consumer groups, acknowledgments, and replay.
# List‑based queue
LPUSH mq:tasks '{"type":"email","to":"[email protected]"}'
BRPOP mq:tasks 0
# Stream example
XADD orders * user_id 42 product_id 100 amount 299
XREADGROUP GROUP order-workers worker-1 COUNT 10 BLOCK 2000 STREAMS orders >
XACK orders order-workers <message-id>Publish/Subscribe
Pub/Sub is suitable for fire‑and‑forget notifications where durability is not required.
# Subscribe
SUBSCRIBE channel:notifications
# Publish
PUBLISH channel:notifications '{"event":"order_paid","order_id":888}'Messages are lost if a subscriber disconnects; use Streams for reliable delivery.
Geolocation
GEO commands store longitude/latitude in a Sorted Set and enable radius or bounding‑box queries.
# Add locations
GEOADD locations 116.397128 39.916527 "beijing" 121.473701 31.230416 "shanghai"
# Distance in km
GEODIST locations "beijing" "shanghai" km
# Find 10 points within 5 km of a coordinate
GEOSEARCH locations FROMLONLAT 116.397 39.916 BYRADIUS 5 km ASC COUNT 10HyperLogLog (UV Counting)
HyperLogLog estimates unique elements with ~0.81 % error using only 12 KB per key.
# Add user IDs
PFADD uv:page:home "user:1001" "user:1002" "user:1003"
# Estimate UV
PFCOUNT uv:page:home
# Merge pages for total UV
PFMERGE uv:total uv:page:home uv:page:detailBitmap (Feature Flags & Check‑ins)
Bitmaps store one bit per user or day, enabling ultra‑compact counters and set operations.
# Record a daily check‑in (bit 1)
SETBIT user:checkin:20260429 1001 1
# Count total check‑ins for the day
BITCOUNT user:checkin:20260429
# Find users who checked in two consecutive days
BITOP AND active_users user:checkin:20260428 user:checkin:20260429JSON Document Store
Redis 8.0 includes a native JSON data type with JSONPath queries, allowing atomic field updates without fetching the whole document.
# Store a product document
JSON.SET product:1 $ '{"name":"iPhone","price":7999,"stock":100,"tags":["手机","苹果"]}'
# Retrieve only the price
JSON.GET product:1 $.price
# Increment price atomically
JSON.NUMINCRBY product:1 $.price 500
# Append a tag
JSON.ARRAPPEND product:1 $.tags '"数码"'Time Series
The native TimeSeries module compresses timestamped data efficiently.
# Insert a sample point
TS.ADD sensor:cpu:server01 * 68.5
# Query with 60‑second aggregation
TS.RANGE sensor:cpu:server01 - + AGGREGATION avg 60000
# Create a down‑sampling rule (hourly avg)
TS.CREATERULE sensor:cpu:server01 sensor:cpu:server01:1h AGGREGATION avg 3600000Full‑Text Search (Redis Query Engine)
Formerly RediSearch, now built‑in. Create an index on JSON keys, search with weighting, numeric filters, and tags.
# Create index on product JSON documents
FT.CREATE idx:products ON JSON PREFIX 1 product: SCHEMA $.name TEXT WEIGHT 2.0 $.price NUMERIC $.tags TAG
# Search for "手机" priced between 1000‑5000, sorted by price
FT.SEARCH idx:products "@name:手机 @price:[1000 5000]" SORTBY price ASC LIMIT 0 20Provides BM25 ranking and can be horizontally scaled, delivering up to 16× query throughput compared with older versions.
Vector Search / AI RAG
Redis 8.0 adds vector indexing for Retrieval‑Augmented Generation. Store embeddings in a hash or JSON, then perform K‑Nearest‑Neighbor (KNN) queries.
# Create a vector index on hash keys (1536‑dim FLOAT32, HNSW, cosine)
FT.CREATE idx:docs ON HASH PREFIX 1 doc: SCHEMA content TEXT embedding VECTOR HNSW 6 TYPE FLOAT32 DIM 1536 DISTANCE_METRIC COSINE
# Insert a document with an embedding (binary placeholder)
HSET doc:1 content "Redis 8.0 new features" embedding <float-array-1536>
# KNN search for top 5 similar docs
FT.SEARCH idx:docs "*=>[KNN 5 @embedding $vec AS score]" PARAMS 2 vec <query-vector-binary> RETURN 3 content scoreRedis also offers a beta Vector Set data structure with VADD and VSIM for pure vector similarity workloads.
# Add a vector to a Vector Set
VADD doc_vectors 1536 <float-array> doc:1
# Find the 5 most similar members
VSIM doc_vectors 1536 <query-vector> COUNT 5Bloom & Cuckoo Filters
Probabilistic filters are now native. Bloom filters answer "maybe"/"no" membership queries; Cuckoo filters add deletions.
# Bloom filter add & check
BF.ADD spam:urls "http://malicious.com"
BF.EXISTS spam:urls "http://example.com"
# Cuckoo filter add & delete
CF.ADD active:sessions "session:abc123"
CF.DEL active:sessions "session:abc123"Typical use: cache‑penetration protection, URL deduplication, session invalidation.
Top‑K & Count‑Min Sketch
These probabilistic structures track heavy hitters and approximate frequencies with fixed memory.
# Top‑K: keep top 10 items
TOPK.RESERVE trending:words 10 50 5 0.9
TOPK.ADD trending:words "redis" "mysql" "redis" "kafka" "redis"
TOPK.LIST trending:words WITHCOUNT
# Count‑Min Sketch: estimate occurrences
CMS.INITBYERROR freq:search 0.001 0.01
CMS.INCRBY freq:search "redis" 1
CMS.QUERY freq:search "redis"Ideal for real‑time hot‑word stats, ad‑click hot spots, or P99 latency tracking (via T‑Digest, also built‑in).
Conclusion
Redis 8.0’s biggest shift is the consolidation of many previously external modules—search, time‑series, vector, and probabilistic data structures—into a single server. The result is dramatically lower latency (up to 87 % reduction) and higher throughput (multithreaded I/O can double performance). When facing a new technical requirement, consider whether Redis 8.0 can handle it before adding separate middle‑wares.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Architect's Tech Stack
Java backend, microservices, distributed systems, containerized programming, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
