Scrivio Interview library

Redis patterns and use cases

43 questions in 10 subtopics.

About this topic

Most teams adopt Redis for caching and then reach for it again for rate limits, sessions, queues, locks, counters, leaderboards, location search, probabilistic checks, live fan-out and, more recently, search and vector queries. Each of these patterns rests on a specific data type and a few atomic commands, and each has failure modes that show up only under load or during a failover. Knowing a pattern means knowing its data model, its memory cost, what Redis guarantees and what it does not, and when another system is the better home. The questions walk through each pattern from the basic commands and Java code to production incidents and to the decisions a senior engineer makes about whether Redis should be used for it at all.

Rate limiting with Redis

Redis is a common home for rate-limit counters because its atomic commands and Lua scripts let many service instances share one view of each limit. Know the main algorithms (fixed window, sliding log, sliding counter, token bucket and GCRA), their memory and CPU cost in Redis, and what the limiter should do when Redis is slow or unavailable.

CodingFoundations6 min read

A sliding-window log rate limiter keeps a timestamp for every accepted request and counts how many fall within the last window, which avoids the bursts at window edges that a fixed window allows.

Write a Redis Lua script that allows at most 20 requests per 60 seconds per user using a sorted set, and explain its memory cost and why it has to be a script.
InternalsIntermediate6 min read

Token bucket and the closely related generic cell rate algorithm (GCRA) enforce a rate with an allowed burst while storing a single number per key.

Explain how GCRA works, give the core of a Redis Lua implementation, and compare it with the sliding-window log in memory, precision and cost.
DebuggingIntermediate6 min read

An API gateway calls a Redis rate-limit script on every request: a sorted-set sliding log, with limits up to 10,000 requests per minute for large API keys. At 180,000 checks per second the Redis primary reaches 95 percent CPU and adds 8 ms to p99.

Find where the cost comes from and redesign the limiter so it scales.
ScenarioAdvanced6 min read

A public API platform enforces per-customer limits through a shared Redis. At 03:10 the Redis primary fails, Sentinel takes 25 seconds to promote a replica, and gateway threads block on rate-limit calls until their 2-second timeout.

What should the rate limiter do when Redis is down or slow, and how would you redesign it so this failure no longer takes the API down?
LeadershipPrincipal6 min read

Over the years four rate-limiting implementations appeared: a Redis Lua limiter in the gateway, Resilience4j limits inside services, a homegrown Redis library used by a dozen teams, and the cloud API gateway's own quotas.

As the senior technical leader, how do you decide what the company standardises on, and whether to build or buy?

Leaderboards and ranking

Sorted sets keep members ordered by score with logarithmic updates and rank lookups, which makes them the natural leaderboard structure. Understand tie-breaking through score encoding, periodic boards, around-me views, the memory cost of tens of millions of members, and what to do when one sorted set on one shard can no longer carry the reads or writes.

CodingFoundations6 min read

Sorted sets order members by a floating-point score and break ties by comparing member names, which is rarely what a game wants when two players reach the same score.

Using ZADD options and a composite score, build a leaderboard where only a player's best score counts and, among equal scores, the player who reached it first ranks higher.
DebuggingIntermediate6 min read

During a live tournament 2 million connected clients poll the top 100 every second. The leaderboard is one sorted set of 30 million members in Redis Cluster, and the node that owns its slot hits 100 percent CPU while other nodes are idle.

Explain the bottleneck and fix it without changing the game client.
DesignIntermediate6 min read

A mobile game with 50 million players wants an all-time leaderboard, daily and weekly boards, and an around-me view that shows the ten players above and below the current player.

Design the keys and commands, estimate the memory, and explain how the daily and weekly boards are maintained and expired.
ScenarioAdvanced6 min read

A global game expects 400,000 score updates per second and 300 million ranked players next season, more than one sorted set on one Redis primary can handle in CPU and memory.

How do you shard a leaderboard while still answering top-100 and what-is-my-rank queries, and which accuracy trade-offs would you accept?

Session storage

Keeping HTTP sessions in Redis lets any application instance serve any user, and Spring Session provides this with a simple and an indexed repository. Know what is stored per session, how expiry and events work, why eviction policies and session size matter so much, and how to revoke or limit sessions when security requires it.

ConceptFoundations5 min read

Spring Session can keep HTTP sessions in Redis so any application instance can serve any request. It offers a simple repository and an indexed one, which store different keys.

Describe what the default Redis session repository stores per session and how expiry works, and what the indexed repository adds and costs.
DebuggingFoundations5 min read

An online shop keeps Spring Session data in the same Redis cluster as its product cache. During evening peaks support receives complaints that users are logged out and lose their checkout progress.

INFO stats shows evicted_keys climbing during the peak, and maxmemory-policy is allkeys-lru. Explain the cause and the fix.
ScenarioAdvanced6 min read

A web application with 2 million active sessions sees Redis memory reach 300 GB and session saves taking 20 ms. Analysis shows an average session of 150 KB, mostly entity graphs and search results stored as attributes over the years.

How do you bring the session store back under control without logging everyone out, and which rules do you set for the future?
ScenarioAdvanced6 min read

A B2B application keeps Spring Session sessions in Redis. A customer tenant reports compromised credentials, and security wants all sessions of that tenant's 40,000 users ended within five minutes, and at most three concurrent sessions per user from now on.

How do you revoke the sessions now, and how would you design session storage so both requirements become routine?

Queues and job processing

Redis lists, sorted sets and Streams can all carry background jobs, with very different guarantees. Understand reliable list patterns, consumer groups with pending entries and claiming, delayed jobs on sorted sets, what at-least-once delivery demands of handlers, and how memory limits and outages turn a fast queue into lost or duplicated work.

ConceptFoundations7 min read

A Redis list can act as a simple work queue: producers push jobs and workers pop them. The simplest version loses jobs when a worker crashes in the middle of one.

Explain why LPUSH with BRPOP is not reliable and how the BLMOVE pattern with a processing list fixes it. What still needs handling?
DebuggingIntermediate7 min read

An order-processing service reads a Redis Stream with a consumer group. After a deployment, XPENDING reports 120,000 pending entries, some idle for six hours with a delivery count of 1, while new orders flow normally.

What happened, how do you recover the stuck entries, and how do you prevent it?
DesignIntermediate8 min read

A notification system must send reminders at a scheduled time, from seconds to weeks ahead, and retry failed sends with backoff. The team wants to use Redis rather than add a scheduler product.

Design delayed jobs with a sorted set: the data model, how workers pick due jobs safely in parallel, and the guarantees you get.
ScenarioAdvanced7 min read

A Redis Stream buffers document-conversion jobs between an upload service and workers. A storage outage stops the workers, the stream grows by 2 million jobs an hour, and Redis will hit maxmemory in about three hours.

What do you do now, and how would you redesign the system so a long outage does not threaten Redis or lose jobs?
LeadershipPrincipal7 min read

Twelve teams built job processing on Redis in different ways: plain lists, Streams, a library with its own Lua scripts, and Redisson queues. In the last year three incidents lost or duplicated jobs that customers noticed.

As the senior technical leader, how do you decide whether Redis stays the company's job-processing platform, and what do you standardise?

Distributed locks, Redlock and fencing tokens

Redis locks are leases: a key with a value and an expiry that one client holds for a while. Know how Redisson's lock and watchdog behave, what the Redlock algorithm does and assumes, why expiry and failover can create two holders, and how fencing tokens and idempotent writes keep data correct when that happens.

CodingFoundations6 min read

Redisson is a Java client that offers a distributed RLock on Redis with reentrancy and automatic lease renewal, which many Spring Boot services use instead of hand-written SET NX locks.

Show how to take and release an RLock with a wait time, explain what the watchdog does, and say when the lock is released if the process dies.
DebuggingFoundations6 min read

A warehouse service takes a Redisson lock per order with tryLock(0, 30, SECONDS) before calling a slow carrier API. Customers occasionally receive two shipments, and logs show 'attempt to unlock lock, not locked by current thread' at the end of some jobs.

Explain what is happening and how you would fix it properly.
InternalsIntermediate7 min read

Redlock is the algorithm proposed for Redis locks that must survive the failure of one Redis node, using several independent Redis primaries instead of one primary with replicas.

Describe the Redlock algorithm step by step, including how lock validity is calculated, and explain the assumptions it depends on.
CodingIntermediate7 min read

A fencing token is a number that increases each time a lock is granted. The protected resource checks it, so a client whose lock has expired cannot overwrite newer work.

Implement lock acquisition that returns a fencing token in one Redis Lua script, and show how the database update uses the token to reject stale writers.
ScenarioAdvanced6 min read

A billing scheduler runs on four instances and uses a Redis lock (SET NX PX) on a primary with an asynchronous replica and Sentinel. One night the primary crashed right after granting the lock, a replica was promoted without the key, and two instances charged customers twice.

Explain the failure and decide what the billing system should use for mutual exclusion and safety from now on.

Counting with HyperLogLog and bitmaps

HyperLogLog estimates distinct counts in about 12 KB with a small known error, and bitmaps store one bit per user for exact yes-or-no facts. Understand how each works, their memory costs, how to combine them across days with unions and bit operations, and where approximate counts are acceptable and where they are not.

ConceptFoundations6 min read

HyperLogLog is a probabilistic structure that estimates how many distinct items a set contains using a small fixed amount of memory, and Redis offers it as a built-in type.

Explain PFADD, PFCOUNT and PFMERGE, the memory use and error of a Redis HyperLogLog, and what you cannot do with it.
CodingFoundations6 min read

Redis bitmaps are strings treated as bit arrays, so one bit per user can record a yes-or-no fact, such as whether the user was active on a given day.

Use SETBIT, BITCOUNT and BITOP to record daily active users and compute 7-day active users and day-1 retention. How much memory does this take for 100 million users?
DebuggingIntermediate7 min read

A content site tracks unique visitors per article per day with one HyperLogLog per article per day, across about 2 million articles. After four months Redis memory has reached 90 GB, and the weekly unique-visitor figures in reports look too high.

Explain both problems and fix them.
LeadershipPrincipal6 min read

Product dashboards show unique users from Redis HyperLogLogs, and finance reports use exact numbers from the data warehouse. The two differ by 1 to 2 percent, and a privacy request asks that one user be removed from all counts.

As the senior technical leader, how do you set policy for where approximate counting is allowed, and how do you answer the privacy request and the mismatch?

Geospatial queries

Redis stores geographic points as geohash scores in a sorted set and answers radius and box searches around a location. Know how GEOADD and GEOSEARCH work, what drives query cost in dense areas, how to handle moving objects with no per-member expiry, and where a spatial database or routing engine is the better tool.

ConceptFoundations7 min read

Redis geospatial commands store points by longitude and latitude and answer radius and box searches, such as finding stores within 5 km of a user.

How are geo points stored internally, which commands add and search them, and what are the limits on accuracy and coordinates?
DebuggingIntermediate6 min read

A food-delivery app's restaurants-near-me query takes 40 ms at lunchtime in a dense downtown area, and Redis CPU spikes. One key holds all 2 million restaurants in the country, and the query uses a 10 km radius with COUNT 50.

Why is the query slow, and how do you fix it?
DesignAdvanced7 min read

A ride-hailing service has 300,000 active drivers who send a location every 4 seconds, about 75,000 updates per second, and riders search for the nearest available drivers within 3 km.

Design the Redis data model for driver locations, including how stale drivers disappear and how the load spreads across a cluster.
LeadershipPrincipal6 min read

A logistics platform that started with Redis geo commands for nearby searches now needs delivery zones as polygons, travel-time distances, historical location analysis and coverage in 40 countries.

How do you decide what stays in Redis and what moves to other geospatial technology, and how do you organise ownership of location data?

Bloom filters and probabilistic structures

Bloom and Cuckoo filters, Count-Min Sketch and Top-K answer membership and frequency questions in little memory by accepting controlled errors. Know how each works, how to size it for a target error rate, what happens when it outgrows its capacity, and why a positive answer must be confirmed when correctness matters.

ConceptFoundations6 min read

A Bloom filter answers whether an item has possibly been seen before using a bit array and several hash functions, with no false negatives but some false positives. Redis offers it alongside other probabilistic types.

Explain how a Bloom filter works, the main BF commands, and when you would choose a Cuckoo filter, a Count-Min Sketch or Top-K instead.
DebuggingIntermediate6 min read

A recommendation service keeps one Bloom filter per user to avoid showing items the user has already seen, created implicitly with default settings. After six months users complain they see few new items, and BF.INFO shows 8 sub-filters for heavy users.

Explain the behaviour and redesign the approach.
DesignIntermediate7 min read

A sign-up service wants an instant username-taken hint for 500 million existing usernames, with at most 0.1 percent false positives, before running the exact database check.

Size the Bloom filter, explain how you would create and load it, and describe the risks of keeping it in a single Redis key.
DesignAdvanced7 min read

During a credential-stuffing attack a login service receives 2 million requests per second from hundreds of thousands of IP addresses. The security team wants the heaviest sources within seconds without an exact counter per IP.

Design heavy-hitter detection with Redis probabilistic structures, explain the error trade-offs, and say how the results feed into blocking.

Real-time fan-out with pub/sub

Redis pub/sub delivers each message to whoever is subscribed at that moment, which makes it a simple backplane for chat, notifications and live updates across application instances. Understand its fire-and-forget semantics, subscriber buffer limits, how it behaves in Redis Cluster and with sharded pub/sub, and when a durable stream or broker is required instead.

CodingFoundations7 min read

A chat service runs eight Spring Boot instances; each user holds a WebSocket connection to one instance, and a message from one user must reach the other members of a room wherever they are connected.

Show how to deliver room messages across instances with Redis pub/sub and RedisMessageListenerContainer, and say what is lost when an instance disconnects from Redis.
InternalsIntermediate6 min read

A team moved its live-updates pub/sub from one Redis primary to a 30-node Redis Cluster to scale. Afterwards, traffic between cluster nodes tripled and pub/sub latency rose, although the message rate had not changed.

Explain how classic pub/sub works in Redis Cluster and what sharded pub/sub changes.
DebuggingIntermediate7 min read

Instances of a notification service subscribed to Redis pub/sub disconnect and reconnect every few minutes during peaks, losing messages. The Redis log shows lines saying such clients were scheduled to be closed for overcoming output buffer limits.

Explain the cause and the fixes on both the server and the client side.
LeadershipPrincipal6 min read

Over several years fifteen services started using Redis pub/sub and keyspace notifications as an event bus between teams. After a Redis failover some downstream systems missed order updates, and nobody noticed for two days.

As the senior technical leader, what guidance do you set for when Redis pub/sub is acceptable, and how do you move the critical flows?

Search and vector queries in Redis

The Redis query engine adds secondary indexes over hashes and JSON, with full-text, tag, numeric, geo and vector fields, so Redis can serve search and semantic retrieval. Know how indexes are defined and kept current, how HNSW and FLAT vector indexes trade accuracy, memory and speed, and the operational limits that decide when a dedicated search engine fits better.

ConceptFoundations6 min read

The Redis query engine adds secondary indexes over hashes and JSON documents, so you can search by text, tags, numeric ranges and vectors instead of only looking up keys. It ships with Redis 8 and Redis Stack.

Show how to create an index over product JSON documents and query them by text, tag and price range, and explain how the index stays up to date.
CodingIntermediate7 min read

A support assistant built with Spring Boot needs semantic search over 2 million document chunks with 1536-dimension embeddings, filtered by tenant, and the team wants Redis as the vector store.

Show the index definition and a filtered KNN query, explain the HNSW parameters, and say how Spring AI fits in.
DebuggingIntermediate7 min read

A team loaded 8 million 1536-dimension embeddings into a Redis HNSW index. Memory reached about 70 GB, the build took hours, and query latency during the nightly re-ingestion rose from 5 ms to 90 ms.

Explain where the memory and the latency come from, and what you would change.
ScenarioAdvanced6 min read

A shop runs product search on the Redis query engine over 20 million JSON documents. After an unplanned restart of a primary that had no replica, search returns partial results for 40 minutes, and FT.INFO shows indexing in progress.

Explain why this happens, and how you would design the deployment so a restart or failover does not degrade search like this.