Redis Query Cookbook
High-speed in-memory key-value data structure store used as a database, cache, and message broker. 10 production-tested query recipes ready to copy and execute.
1. Cache Value with Expiration (SET EX)
Store key-value pair in cache with 60-second TTL expiration.
SET user:42:session "eyJhbGciOiJIUzI1..." EX 60; 2. Store User Profile Object in Hash (HSET)
Manage structured fields inside a single Redis Hash key.
HSET user:1001 name "Alex" email "alex@dev.com" logins 5;
HGETALL user:1001; 3. API Rate Limiter with INCR & EXPIRE
Limit client request count to 100 per minute.
MULTI;
INCR rate:client:192.168.1.1:minute;
EXPIRE rate:client:192.168.1.1:minute 60;
EXEC; 4. Real-Time Leaderboard with Sorted Set (ZADD)
Rank gaming players dynamically by score.
ZADD leaderboard 1500 "PlayerA" 2300 "PlayerB" 1800 "PlayerC";
-- Get top 3 players:
ZREVRANGE leaderboard 0 2 WITHSCORES; 5. Publish Message to Channel (PUBLISH)
Broadcast real-time message to connected channel subscribers.
-- In Publisher:
PUBLISH updates:news "New article published!";
-- In Subscriber:
-- SUBSCRIBE updates:news; 6. Producer-Consumer Task Queue (LPUSH & RPOP)
Implement high-speed background job processing queue.
LPUSH queue:jobs '{"task": "send_email", "id": 99}';
-- In worker process:
BRPOP queue:jobs 5; 7. Spatial Distance Lookup (GEOADD & GEODIST)
Store geospatial coordinates and compute distance.
GEOADD locations -73.9857 40.7484 "EmpireState" -73.9654 40.7829 "CentralPark";
GEODIST locations EmpireState CentralPark km; 8. Unique Cardinality Count (PFADD)
Count millions of unique daily visitors consuming minimal memory (~12KB).
PFADD uv:2026-01-01 "user_ip_1" "user_ip_2" "user_ip_1";
PFCOUNT uv:2026-01-01; 9. Atomic Inventory Decr with Lua Script
Execute safe stock decrement without concurrency race conditions.
EVAL "if redis.call('get', KEYS[1]) > ARGV[1] then return redis.call('decrby', KEYS[1], ARGV[1]) else return 0 end" 1 stock:item:5 1; 10. Inspect Memory Consumption
Monitor peak RAM usage and key eviction stats.
INFO memory; Test your Redis architectural knowledge!
Practice key concepts, memory structures, and indexing questions with flashcards.