SQLancer
← All Database Cookbooks Library / Cookbook / Redis
ðŸ”ī Redis Recipe Catalog

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;
#cache#ttl#string

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;
#hash#object#hset

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;
#rate_limit#incr#transaction

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;
#zset#leaderboard#ranking

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;
#pubsub#channel#messaging

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;
#queue#list#brpop

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;
#geo#spatial#geodist

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;
#hyperloglog#pfcount#cardinality

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;
#lua#script#atomic

10. Inspect Memory Consumption

Monitor peak RAM usage and key eviction stats.

INFO memory;
#dba#memory#info

Test your Redis architectural knowledge!

Practice key concepts, memory structures, and indexing questions with flashcards.

Study Redis Flashcards →