AI
50 AI Prompts for Redis and Caching Patterns
50 AI prompts for Redis and caching patterns in Node.js and Python applications. Covers cache-aside, write-through, TTL strategies, session storage, rate limiting, pub/sub, queues, distributed locks, and Redis Cluster.
Getting the Best Results from These Redis Prompts
Redis is a fast in-memory data store used for caching, session management, rate limiting, pub/sub messaging, job queues, and distributed coordination. These prompts cover the most common Redis patterns for Node.js and Python backends. All prompts assume Redis 7 or later and the ioredis client for Node.js or redis-py for Python.
The key to effective caching is not the implementation — that is straightforward — but the strategy: what to cache, for how long, and when to invalidate. When using these prompts, always include the context of what you are caching and how often it changes. A good cache strategy depends entirely on the read/write ratio and how much staleness is acceptable.
Caching Patterns and Session Management (Prompts 1-16)
Prompt 1: Write a cache-aside (lazy loading) pattern for a Node.js Express API using ioredis. The /api/users/:id endpoint first checks Redis with a TTL-keyed key, returns the cached value on hit, fetches from PostgreSQL on miss, stores the result in Redis with a 5-minute TTL, and returns it. Show the cache key naming convention and the JSON serialisation pattern.
Prompt 2: Create a write-through cache pattern where every database write also updates the cache. Show a UserRepository class where the update method writes to PostgreSQL in a transaction, then writes the updated user to Redis with the same TTL, and the delete method removes the user from both PostgreSQL and Redis. Prompt 3: Write a cache invalidation strategy for a product catalogue. Show tag-based invalidation using Redis Sets: when a product is updated, look up all cache keys tagged with that product ID and delete them all in a pipeline. Show how to register a cache key with a tag on write and clean up the tag set when the cache key expires.
- Prompt 4: Create a session store using Redis for an Express.js application with connect-redis and express-session. Store session data with a 24-hour TTL, slide the TTL on every request, store the user ID and role in the session, and show how to destroy the session on logout.
- Prompt 5: Write a JSON Web Token blocklist using Redis. When a user logs out or an admin revokes a token, store the token JTI (JWT ID) in Redis with a TTL equal to the token remaining lifetime. In the auth middleware, check if the incoming token JTI is in the blocklist and reject it if found.
- Prompt 6: Create a Redis rate limiter using the sliding window log algorithm. Store a sorted set per IP address where the score is the request timestamp. On each request, remove entries older than the window, count remaining entries, reject if over the limit, and add the current timestamp. Show the Lua script that executes the check and increment atomically.
- Prompt 7: Write a Redis rate limiter using the fixed window counter algorithm. Use INCR and EXPIRE to maintain a counter per IP per minute window. Compare this to the sliding window approach: fixed window is simpler and faster but allows burst traffic at window boundaries.
- Prompt 8: Create a Redis caching layer for GraphQL queries. Cache the query result using a hash of the query string and variables as the cache key. Set a per-type TTL based on how frequently the underlying data changes. Bypass the cache for authenticated user-specific queries. Invalidate relevant cache entries when a mutation is executed.
- Prompt 9: Write a Redis leaderboard using Sorted Sets. Show how to add and update a user score with ZADD, fetch the top 10 users with ZREVRANGE with scores, get a specific user rank with ZREVRANK, and get the scores of users around a specific user (the leaderboard context window) using ZREVRANGE with a calculated offset.
- Prompt 10: Create a Redis distributed lock implementation using the Redlock algorithm. Show using the redlock npm package to acquire a lock with a TTL, execute the critical section, release the lock, and handle the case where the lock cannot be acquired after retries. Explain when to use this over a database-level advisory lock.
- Prompt 11: Write a Redis pub/sub implementation in Node.js using ioredis. Show a publisher that sends JSON events to a channel, a subscriber that listens and processes events, and how to handle reconnection — ioredis requires a separate client instance for subscribe mode since subscribed clients cannot send other commands.
- Prompt 12: Create a Redis Streams producer and consumer setup. Write messages with XADD using auto-generated IDs, create a consumer group with XGROUP CREATE, read and acknowledge messages with XREADGROUP and XACK, and handle pending messages that were not acknowledged after a timeout using XPENDING and XCLAIM.
- Prompt 13: Write a Redis hypermedia counter for real-time analytics using HyperLogLog. Track unique visitors per page per day using PFADD, query the approximate unique count with PFCOUNT, merge daily HyperLogLog keys into a weekly key with PFMERGE. Explain the 0.81% error rate and when this approximation is acceptable.
- Prompt 14: Create a Redis geospatial index for a store locator. Add store locations with GEOADD, query stores within 10km of a point with GEOSEARCH FROMLONLAT BYRADIUS, return distance and coordinates for each result, and show how to store additional store metadata in a separate Hash key referenced by the geo member name.
- Prompt 15: Write a Redis bloom filter setup for email deduplication. Use the RedisBloom module BF.ADD and BF.EXISTS commands to check if an email has been seen before processing it. Explain the false positive rate and capacity configuration. Show the fallback to a database check on positive results to eliminate false positives.
- Prompt 16: Create a Redis cache warming strategy on application startup. Before traffic arrives, fetch the top 1000 most-accessed items from the database and populate the cache in batches using a Redis pipeline. Show how to run this as part of the deployment process before the load balancer routes traffic to the new instance.
Job Queues, Cluster, and Production Operations (Prompts 17-50)
Prompt 17: Write a BullMQ job queue setup for a Node.js application. Define a Queue for sending transactional emails, add jobs from an API handler with the user ID and email type, write a Worker that processes jobs by calling the email service API, configure retry with exponential backoff on failure, and set a concurrency of 5 workers.
Prompt 18: Create a BullMQ delayed job pattern. Schedule a reminder email 24 hours after user registration by adding a job with a delay option. Show how to cancel the scheduled job if the user verifies their email before the delay expires using job.remove(). Prompt 19: Write a Redis pipeline and transaction pattern in Node.js. Use pipeline() to batch multiple GET commands and send them in one round trip. Use multi() (MULTI/EXEC) for a transaction that reads a value, increments it, and writes it back atomically. Explain when pipeline is sufficient and when you need multi for atomicity.
- Prompt 20: Create a Redis Cluster setup for production high availability. Configure a 6-node cluster (3 primary + 3 replica), connect from Node.js using the ioredis cluster mode, show how the client handles slot redirection automatically, and explain how to use hash tags to colocate related keys on the same slot for multi-key operations.
- Prompt 21: Write a Redis eviction policy guide for a cache-only deployment. Explain the difference between volatile-lru, allkeys-lru, volatile-lfu, allkeys-lfu, and noeviction policies, show how to set maxmemory and maxmemory-policy in redis.conf, and recommend which policy to use for a web API response cache versus a session store.
- Prompt 22: Create a Redis monitoring setup using Redis Keyspace Notifications. Enable notifications for expired key events, subscribe to the expired channel, and log each expired key with its estimated size. Use this to identify cache keys with incorrect TTLs or unexpectedly high expiry rates.
- Prompt 23: Write a Redis key naming convention guide for a large application. Show hierarchical naming using colons as separators: user:1234:profile, user:1234:sessions, product:sku-abc:details, rate_limit:ip:1.2.3.4. Include the environment prefix for multi-environment deployments (prod:user:1234:profile) and show how wildcard patterns help with cache clearing.
FAQ
What is the difference between Redis caching and database query caching?
Database query caching (like MySQL query cache, now removed) caches query results inside the database process and is invalidated whenever any relevant table changes. Redis caching is application-level: your code decides what to cache, with what TTL, and when to invalidate. Application-level caching is more flexible and scalable — the cache lives on a separate server, can be shared across multiple application instances, and invalidation logic can be as granular or broad as needed.
Does Redis persist data to disk?
Redis has two persistence options. RDB (Redis Database) takes periodic snapshots of the dataset to disk — fast on restart but can lose data since the last snapshot. AOF (Append Only File) logs every write command and replays them on restart — slower to restart but much less data loss. For a cache, you may want no persistence (--save ) since cached data can be rebuilt from the database. For a session store or job queue where data loss is unacceptable, use AOF with fsync every second as a balance between durability and performance.
Should I use Redis or a database for rate limiting?
Redis. Rate limiting requires atomic increment operations at very high frequency with precise TTL control. Redis INCR and EXPIRE operations are atomic and execute in microseconds. A PostgreSQL rate limiter would require a SELECT then INSERT/UPDATE in a transaction, adding milliseconds of latency and database load for every API request. Redis is the standard choice for rate limiting; the only exception is if you already have a PostgreSQL extension like pg_rate_limit and do not want to add Redis as a dependency.
What happens to Redis data if the server restarts?
Without persistence configured, all Redis data is lost on restart. For a pure cache this is acceptable — the cache is warmed again from the database on the first requests. For session storage, a Redis restart would log out all users unless you have persistence or a Redis replica that takes over. In production, run Redis with a replica (Redis Sentinel or Redis Cluster) so a failover promotes the replica without data loss and without application downtime.
Related free tools
If you want to turn this topic into action, use one of ShortIQ's free tools for campaign planning, UTM structure, or QR distribution.
Continue Reading
Explore more guides on link shortener SaaS strategy, Bitly alternatives, and white label link management.
Free newsletter
Get new guides in your inbox
We publish practical guides on dev tooling, prompt engineering, marketing workflows, and deployment. No fluff — straight to the point.
No spam. Unsubscribe any time.
Was this article helpful?
Tell us if this guide solved the problem or what was still missing. We use this to improve the blog and only follow up if you explicitly allow it.