Go2X
Go2X

India's leading training and placement platform offering hands-on learning, powered by 200+ IITian and industry experts, connecting students to 1,000+ hiring and referral partners.

Let's Go2X

Stay updated with Go2X

Get course updates, interview tips, and career insights delivered to your inbox.

Contact Us

Address

1st Floor, Plot No 332, Phase IV, Udyog Vihar,
Sector 19, Gurugram, Haryana 122015

Email

support@go2x.live

Phone

+91 94107 10085

© 2025 Go2X Private Limited. All rights reserved.

Made with 🧡 and a lot of late nights.

Interview ExperiencesBlogsAbout UsPrivacy PolicyTerms of ServiceRefund Policy

On This Page:

DevOps

Redis Interview Questions

Crack your Redis interview with 50 in-depth questions covering data types, persistence (RDB/AOF), transactions, pub/sub, replication, clustering, Sentinel, Lua scripting, and distributed locking - explained in plain English with practical command examples.

Sept 8, 2026
50 mins read

I. Beginner Level

1. What is REDIS?

Redis (Remote Dictionary Server) is an in-memory database that stores data in RAM instead of disk, making it extremely fast.

Imagine a standard database (like MySQL) as a filing cabinet, it stores lots of data safely, but it takes time to open the drawer and find a file because it saves data on a hard drive (disk). Redis stores data directly in the computer's RAM (temporary memory) because reading from RAM is incredibly fast.

It is mainly used to cache frequently used data and reduce the load on the main database, which improves system performance and response time.

  • It stores frequently accessed data so applications can retrieve it quickly without querying the main database, improving performance and response time.

  • Also used to store user sessions for fast authentication and helps manage queues, leaderboards, and analytics in applications requiring quick updates.

2. What are the primary data types supported by Redis ?

Redis isn't just "key = value" pair database, it supports rich data structures like :

  • String : a simple piece of text or a number, like storing a username. ( name = "Alex")

  • List :an ordered collection of values, useful for building queues or stacks. (great for creating waiting lines or queues).

  • Hash : key-value pairs inside a single key like a JSON object, or a mapping of field→value. For example, storing a user's name and age together user:1 = {name: Alex, age: 25})

  • Set : a collection of unique values with no particular order (e.g., storing a list of unique tags on a blog post).

  • Sorted Set (ZSet) : like a Set, but every value has a score, so it stays sorted (great for leaderboards)

3. How does Redis differ from traditional relational databases?

Traditional relational databases like MySQL store data on disk in tables made up of rows and columns, and they support complex relationships and joins between tables.

Redis, on the other hand, stores data in memory and works with simple key value type structures instead of tables. Because of this, Redis is much faster for reading and writing data, but it is not meant to permanently store large amounts of structured, relational data the way a traditional database is.

You can think of Redis as a quick notepad you keep close by, while a relational database is more like an organized filing cabinet.

4. What is the default port used by Redis?

Redis runs on port 6379 by default. Whenever you connect to a Redis server without specifying a custom port, it uses this one.

bash
1redis-cli -h 127.0.0.1 -p 6379
2
3# Connect to a Redis instance running on a custom port
4redis-cli -p 6380

5. How do you set and get a key-value pair in Redis?

You use the SET command to store data (SET username "john") and the GET command to retrieve it (GET username).

For example, SET name John stores the value John under the key name, and GET name will return John. This is the most basic operation in Redis.

bash
1SET username "john"
2GET username
3# (string) "john"
4
5SET counter 10
6GET counter
7# (string) "10"

6. What is TTL (Time To Live) and how do you set an expiry on a key?

TTL stands for Time To Live, and it tells Redis how long a key should stay alive before it automatically gets deleted. It is basically the lifespan of a key before Redis automatically deletes it. This is very useful for things like login sessions or temporary cache entries that should not last forever.

You can set an expiry while creating a key, for example SET session1 userdata EX 60, which means it will expire in 60 seconds. You can also add or update an expiry on an existing key using the EXPIRE command, like EXPIRE session1 30.

bash
1# Set a key that expires in 60 seconds
2SET session1 userdata EX 60
3
4# Check remaining time to live (in seconds)
5TTL session1
6# (integer) 57
7
8# Set expiry on an existing key (in milliseconds)
9PEXPIRE session1 30000

7. What is the difference between the EXPIRE and PERSIST commands?

  • EXPIRE is used to set a countdown timer on a key so that it automatically deletes itself after a certain number of seconds.

  • PERSIST does the opposite. It removes that timer from a key, so the key will now stay forever unless someone deletes it manually.

In simple words, EXPIRE starts a self destruct timer, and PERSIST cancels that timer. If you change your mind and want a temporary key to stay in Redis forever, you use PERSIST.

bash
1SET session1 userdata
2EXPIRE session1 60      # key will auto-delete in 60 seconds
3TTL session1             # (integer) 58
4
5PERSIST session1         # cancels the countdown
6TTL session1             # (integer) -1  → key now lives forever

8. What is RDB persistence and how does it work?

As RAM wipes out if the computer restarts, Redis needs a way to save data to a hard drive (Persistence). RDB stands for Redis Database Backup which acts like a camera taking a snapshot of your entire database at specific intervals (like every 5 minutes) and saving it as a file.

You can think of it like taking a photograph of your data every so often. It is fast and takes up less space, but if Redis crashes right after some changes and before the next snapshot is taken, those recent changes could be lost.

The catch: You might lose the data created in the minutes between the last picture and the crash.

9. What is AOF (Append Only File) persistence?

AOF stands for Append Only File. Instead of taking periodic snapshots, it acts like a diary. Every time you make a change in Redis, AOF writes that exact command down in a log file, like every SET or DELETE, into the file as soon as it happens. You can think of it like recording a video instead of taking occasional photos.

When Redis restarts, it replays this log to rebuild the exact data it had before. This method is safer and loses less data than RDB, but the log file can grow large over time and takes a bit longer to load.

10. What is the difference between Redis Strings and Redis Hashes?

  • A String is a single value (Key: "User1Name", Value: "John"). For example, you might create separate keys like user1name and user1age.

  • A Hash is like a folder (Key: "User1"). Inside that folder, you can have multiple fields (Name: "John", Age: "30"). Hashes keep related data organized together and are highly memory-efficient. When you have multiple related pieces of information about the same entity, using a Hash is cleaner and uses memory more efficiently than creating many separate String keys.

bash
1# String: one value per key
2SET user:1:name "John"
3
4# Hash: many fields grouped under one key
5HSET user:1 name "John" age "30" city "NYC"
6HGET user:1 name
7# (string) "John"
8HGETALL user:1
9# 1) "name" 2) "John" 3) "age" 4) "30" 5) "city" 6) "NYC"

11. How do you delete a key in Redis?

You simply use the DEL command followed by the key name, for example DEL keyname. This immediately removes that key and its value. You can also delete several keys at once by listing them together, like DEL key1 key2 key3.

bash
1SET username "john"
2DEL username
3# (integer) 1   → 1 key was deleted
4
5DEL nonExistingKey
6# (integer) 0   → nothing to delete

12. What is the purpose of the INCR and DECR commands?

These stand for Increment and Decrement. They easily increase or decrease a number by 1. The magic here is that they are Atomic. INCR increases a numeric value stored at a key by one, and DECR decreases it by one. Both of these operations happen atomically, meaning they are safe even if many requests try to update the same value at the same time. This makes them perfect for things like counting page views, likes, or available stock.

This means if 1,000 people click "Like" on a video at the exact same millisecond, Redis guarantees every single click is counted properly without skipping any, one after the other.

bash
1SET pageviews 10
2INCR pageviews
3# (integer) 11
4
5DECR pageviews
6# (integer) 10
7
8INCRBY pageviews 5
9# (integer) 15

13. Is Redis single-threaded or multi-threaded?

The core part of Redis that executes your commands is single threaded, meaning it processes one command at a time in order. This might sound slow, but since everything happens in memory and most operations are simple, Redis is still extremely fast, and it avoids a lot of the complicated bugs that come with multiple threads trying to change data at the same time. Newer versions of Redis do use some background threads for things like saving data to disk, but the main command processing stays single threaded.

Imagine a very fast cashier at a grocery store. Even if 100 people are in line, the cashier handles one person at a time. Because RAM is so insanely fast, this one "cashier" can handle millions of requests a second without getting confused or mixing up data.

14. What is a Redis List and how does it differ from a regular array?

In a normal programming array, adding an item to the very beginning pushes all other items back, which is slow. A Redis List is an ordered collection of values, similar to an array, but internally it works more like a linked list. This means adding or removing items from the front or the back of the list is very fast, whereas in a regular array, adding something at the front usually means shifting every other item over. Redis Lists are commonly used to build queues and stacks in applications.

bash
1LPUSH mylist "a" "b" "c"
2LRANGE mylist 0 -1
3# 1) "c"  2) "b"  3) "a"
4
5# Unlike an array, no need to pre-allocate size,
6# and pushing/popping from either end is O(1)

15. How do you check if a key exists in Redis?

You use the EXISTS command followed by the key name. It returns 1 if the key exists and 0 if it does not.

bash
1EXISTS username
2# (integer) 1   → key exists
3
4EXISTS nonExistingKey
5# (integer) 0   → key does not exist

II. Intermediate Level

1. What is the difference between Redis Sets and Sorted Sets?

  • A Set stores unique values with no particular order, so it is good for things like checking whether an item is already present or storing tags without duplicates (like a list of unique visitors today).

  • A Sorted Set also stores unique values, but each value has a score attached to it, and Redis automatically keeps the values sorted based on that score. This makes Sorted Sets perfect for building things like leaderboards where you need to rank players by their points.

bash
1# Set: unique, unordered values
2SADD tags "redis" "cache" "nosql"
3SMEMBERS tags
4# 1) "cache" 2) "nosql" 3) "redis"
5
6# Sorted Set: unique values, ordered by score
7ZADD leaderboard 100 "alice" 250 "bob" 90 "carol"
8ZRANGE leaderboard 0 -1 WITHSCORES
9# 1) "carol" 2) "90" 3) "alice" 4) "100" 5) "bob" 6) "250"

2. How does Redis handle eviction when the memory limit is reached? Explain the maxmemory-policy options.

When Redis reaches the memory limit you have configured, it needs a strategy to free up space, and this strategy is called the maxmemory policy. For example when your RAM gets 100% full, Redis has to kick old data out to make room for new data. This is called Eviction. You can set rules (Policies) for who gets kicked out. The most popular is LRU (Least Recently Used), meaning Redis kicks out the data that hasn't been touched in the longest time.

Some common options are:

  • allkeys LRU : which removes the least recently used keys across the entire dataset.

  • volatile LRU : which does the same thing but only considers keys that already have an expiry set.

  • allkeys LFU : which removes the least frequently used keys instead.

  • volatile TTL : which removes the keys that are closest to expiring first, and random options that simply remove keys at random.

In most caching setups, an LRU based policy is the most commonly chosen one.

bash
1# View current eviction policy
2CONFIG GET maxmemory-policy
3
4# Set a memory cap and an eviction policy
5CONFIG SET maxmemory 100mb
6CONFIG SET maxmemory-policy allkeys-lru

3. What is Redis Pub/Sub and how does it work?

Pub Sub stands for Publish and Subscribe. Publish/Subscribe is a messaging system inside Redis. In this model, one client publishes a message to a channel, and every client that is subscribed to that channel receives the message instantly, almost like a group broadcast.

Think of it like a radio station. A Publisher broadcasts a message to a specific channel (like "Sports_Updates"). Anyone who has Subscribed to that channel hears the message live. However, it's live-only if a subscriber is disconnected when the message plays, they miss it forever.

For example, one client can run PUBLISH news helloEveryone, and any client that had run SUBSCRIBE news beforehand will immediately receive that message. It is great for real time features like chat applications or live notifications. However, if nobody is subscribed at the exact moment a message is published, that message is lost forever, since Redis does not store it anywhere.

bash
1# In one client:
2SUBSCRIBE news
3
4# In another client:
5PUBLISH news "helloEveryone"
6# Subscriber instantly receives: "helloEveryone"

4. Compare RDB and AOF persistence in terms of durability, recovery time, and performance impact.

AspectRDB (Redis Database)AOF (Append Only File)
Durability (Safety)• Saves data as periodic snapshots. •Can lose recent data if Redis crashes between two snapshots.• Less durable but uses less disk activity.• Logs almost every write operation as it happens. • Minimizes data loss in case of a crash.• More durable and safer than RDB.
Recovery Time• Faster startup because Redis loads a single compact snapshot file. • Suitable when quick recovery is important.• Slower startup because Redis replays all logged write commands. • Recovery time depends on the size of the AOF log.
Performance Impact• Lower performance overhead since snapshots are created occasionally in the background .• Better runtime performance for most workloads.• Slightly higher performance overhead due to continuous disk writes. • Logging every write operation may slightly reduce performance.

Note: Many production systems use both RDB and AOF together to achieve a balance between high durability and good performance.

5. What are Redis transactions, and how do MULTI/EXEC work?

A Redis transaction lets you group multiple commands together so that they run as a single, uninterrupted unit, without any other client's commands sneaking in between them.

You start with MULTI, write your commands, and finish with EXEC. Redis promises that no other user's commands will interrupt yours. When you finally run EXEC, all the queued commands are executed together in order.

Important note: Unlike traditional databases, Redis does not have a "Rollback" feature. If command #2 fails, it still pushes through and executes command #3.

bash
1MULTI
2SET balance 100
3DECRBY balance 20
4EXEC
5# 1) OK  2) (integer) 80
6# All commands run as one atomic unit

6. What is the WATCH command used for in Redis transactions?

WATCH is a safety guard used to implement something called optimistic locking.

Before starting a transaction, you tell Redis to watch a particular key. If that key gets changed by some other client before your transaction actually runs with EXEC, Redis will cancel your entire transaction instead of letting you overwrite data based on outdated information. This is a safe way to handle situations where multiple clients might try to update the same data at the same time.

bash
1WATCH balance
2MULTI
3DECRBY balance 20
4EXEC
5# Returns (nil) instead of executing if another
6# client changed "balance" after the WATCH call

7. How does Redis pipelining work and why does it improve performance?

Normally, every single command you send to Redis involves a round trip over the network, where your app sends the command and then waits for a reply before sending the next one. For example, you ask Redis a question, wait for the answer, ask another, and wait again. The waiting time for the question to travel across the internet network is called Latency.

Pipelining allows you to send a whole batch of commands one after another without waiting for each individual reply, and then read all the replies together at the end. That means Redis processes them all and sends all 100 answers back in one package.

This cuts down heavily on the network delay you would otherwise face, especially when you need to run many commands quickly and this helps to drastically reduce internet travel time.

bash
1# Without pipelining: 3 round trips to the server
2SET a 1
3SET b 2
4SET c 3
5
6# With pipelining: all 3 sent in one batch, one round trip
7redis-cli --pipe <<EOF
8SET a 1
9SET b 2
10SET c 3
11EOF

8. When would you use a Redis Hash over multiple String keys?

If you have several related pieces of information about the same entity, such as a user's name, age, and email, storing each of them as a separate String key wastes memory and makes things harder to manage.

Using a single Hash to group all these fields under one key is more memory efficient, since Redis optimizes small hashes internally, and it also makes it much easier to fetch or update specific fields for that entity.

For example, if you have a user, you could create three separate keys: user:1:name, user:1:age, user:1:city. But this wastes a lot of memory repeating "user:1". Putting them all inside a single Hash called user:1 is much cleaner and allows Redis to compress the data, saving a massive amount of RAM.

bash
1# Instead of 3 separate keys:
2SET user:1:name "John"
3SET user:1:age "30"
4SET user:1:city "NYC"
5
6# Use one Hash:
7HSET user:1 name "John" age "30" city "NYC"

9. What are Redis keyspace notifications and how would you use them?

This is a feature where Redis can send an alarm to your application when something happens to a key. For example, if you want your app to know the exact second a user's session expires, your app can listen for an Expired Event.

It can be configured to automatically send out notifications, through Redis’ Pub Sub system, whenever something happens to a key, such as when it expires, gets deleted, or gets updated.

Once you enable this feature in the configuration, you can subscribe to special channels and get notified in real time about these events. This is useful when you want to automatically trigger some action, like refreshing a cache, exactly when a related key expires or changes.

10. Explain the difference between LPUSH/RPUSH and LPOP/RPOP.

These are commands for Lists. L stands for Left (the front of the line) and R stands for Right (the back of the line).

  • LPUSH : adds a new item to the left side, or the front, of a list.

  • RPUSH adds a new item to the right side, or the end, of a list.

  • LPOP : removes and returns the item from the front of the list.

  • RPOP : removes and returns the item from the end of the list.

By combining these commands in different ways, you can build either a queue, which follows first in first out order, or a stack, which follows last in first out order.

bash
1LPUSH queue "task1"
2RPUSH queue "task2"
3LRANGE queue 0 -1
4# 1) "task1"  2) "task2"
5
6LPOP queue
7# (string) "task1"
8RPOP queue
9# (string) "task2"

11. How would you implement a simple rate limiter using Redis?

A rate limiter prevents users from spamming a website.

A common approach is to use a key that represents a particular user along with a time window, and increase its value using the INCR command every time that user makes a request.

The very first time the key is created, you also set a TTL on it, for example sixty seconds, using EXPIRE timer. If the counter goes beyond your allowed limit within that time window, you simply reject any further requests until the key expires and the counter resets. Since INCR is atomic, this approach stays safe and accurate even when many requests come in at the same time.

bash
1# Allow max 5 requests per user per 60 seconds
2INCR rate_limit:user123
3EXPIRE rate_limit:user123 60 NX   # only sets TTL on first request
4
5# Application checks the counter before proceeding
6GET rate_limit:user123
7# if > 5, reject the request

12. What is Redis replication and how does master-replica synchronization work?

Replication is having backup servers. You have one main server (Master) and several helpers (Replicas). You only write new data to the Master. The Master then sends a copy of that data to all the Replicas. To share the workload, your app can read data from any of the Replicas.

When a replica first connects, it performs a full sync with the master, similar to copying an entire snapshot of the data. After that, the replica keeps receiving a continuous stream of write commands from the master, so it always stays up to date. This setup lets you spread out read traffic across replicas, and also gives you a backup copy of your data in case the master server fails.

13. What is the difference between synchronous and asynchronous replication in Redis?

AspectAsynchronous ReplicationSynchronous Replication
WorkingThe master does not wait for replicas to acknowledge the write before replying to the client.The master waits for replicas to acknowledge the write before replying to the client.
SpeedFaster because the client receives an immediate response.Slower because the master waits for replica confirmations.
Data SafetySlight risk of data loss if the master crashes before replicas receive the latest updates.Safer because replicas confirm they have received the data before the operation is considered complete.
PerformanceBetter performance and lower write latency.Higher write latency due to waiting for acknowledgements.
Redis SupportDefault replication mode in Redis.Redis approximates synchronous behavior using the WAIT command, which waits for acknowledgements from a specified number of replicas.

Key Points:

  • Asynchronous Replication

  • The master saves the data, immediately responds "Done!" to the client, and then updates replicas in the background.

  • Provides high performance and low latency.

  • If the master crashes before replicas are updated, the latest data may be lost.

  • Synchronous Replication

  • The master waits for replicas to confirm "We got it!" before responding "Done!" to the client.

  • Provides better data safety and consistency.

  • Slower due to the extra waiting time for replica acknowledgements.

  • Redis supports near-synchronous behavior using the WAIT command, allowing applications to trade some performance for greater durability.

14. How does Redis Sentinel provide high availability?

Sentinel is a separate monitoring system that constantly keeps an eye on your master and replica servers. Basically Sentinel is an automated watchdog. It constantly monitors the Master. If your Master server crashes, your app goes down. If it detects that the master has gone down Sentinel automatically promotes one of the replicas to become the new master and reconfigures the other servers and clients to point to it.

This whole process, called failover, happens automatically, so your Redis setup can keep running even if the main server suddenly fails.

15. What are Redis Streams and how do they differ from Pub/Sub?

Streams are like a WhatsApp group chat history. Unlike Pub/Sub (where messages vanish if you aren't listening live), Streams permanently record every message.

A Redis Stream works like an append only log of messages, somewhat similar to how Kafka works. Every message added to a stream gets a unique ID and stays stored, so consumers can read it later, replay old messages, and even use something called consumer groups to split the workload among multiple readers. If a server goes offline and comes back later, it can read the Stream history to catch up on what it missed.

Pub Sub, on the other hand, is completely fire and forget. If no client happens to be subscribed at the exact moment a message is published, that message disappears and can never be recovered.

So Redis Streams give you durability and the ability to replay history, while Pub Sub is meant purely for instant, real time broadcasting.

bash
1# Add an entry to a stream
2XADD mystream * sensor "temp" value "22.5"
3
4# Read all entries from the beginning
5XRANGE mystream - +
6
7# Read new entries as they arrive (like a durable, replayable Pub/Sub)
8XREAD BLOCK 0 STREAMS mystream $

16. Why is SCAN preferred over KEYS in a production environment?

  • The KEYS * command asks Redis to find every single key in the database at once, and because Redis is single threaded, this can freeze the whole server for a noticeable amount of time if you have a large dataset.

  • SCAN is much smarter. It flips through the database like a book, giving you a few keys at a time, allowing other users to use the database in between page flips. It basically walks through the keys gradually in small batches using something called a cursor, so it does not block other operations while it runs.

Because of this, SCAN should always be used in production, while KEYS is fine only for local testing or debugging on small datasets.

bash
1# Blocks the server while scanning all keys at once - avoid in production
2KEYS user:*
3
4# Non-blocking, returns a cursor + small batch of keys each call
5SCAN 0 MATCH user:* COUNT 100

17. What are Redis bitmaps used for, and how do bitwise operations work on them?

A Bitmap is just a string of 0s and 1s. It is the ultimate trick for saving memory when you only need to store "Yes" or "No" answers. It is just a string that Redis lets you treat as a sequence of individual bits, and you can set or check each of those bits separately.

For example, SETBIT can mark whether a particular user was active on a given day, and GETBIT can check that same bit later. You can also use BITCOUNT to quickly count how many bits are set to one, which tells you how many users were active in total. Since each bit takes up very little space, you can use it to track if a user logged in today, you just flip the 0 to a 1 at their specific ID spot. You can track millions of users this way using almost zero memory.

bash
1SETBIT online_users 123 1   # mark user ID 123 as online
2GETBIT online_users 123
3# (integer) 1
4
5BITCOUNT online_users        # count how many users are online

18. How would you use Redis as a cache, and what cache invalidation strategies exist?

A very common pattern is called cache aside. Your application first checks Redis for the data it needs. If the data is found, that is called a cache hit, and you return it directly. If it is not found, that is a cache miss, so you fetch the data from your main database and then store a copy of it in Redis for next time.

To keep the cache from serving outdated data, you can rely on TTL so entries automatically expire after some time, use write through caching where the cache updates immediately whenever the database updates, or manually delete the cache entry whenever the underlying data changes.

19. What is OBJECT ENCODING in Redis (e.g., ziplist vs. hashtable, intset vs. hashtable), and why does it matter?

Redis is obsessed with saving memory. If a Hash or List is very small, Redis quietly compresses it into a tight, super-efficient format behind the scenes. If the data grows too big for that format, Redis instantly unpacks it into a standard format. This automatic memory management is called Encoding.

For example, a small Hash might be stored using a compact format called a ziplist, but once it grows past a certain size, Redis automatically switches it to a full hashtable format. Similarly, a Set made only of small integers might use a compact intset format, but it switches to a hashtable if it grows large or contains non integer values.

You can check the current encoding of any key using the OBJECT ENCODING command. This matters because compact encodings save a lot of memory for small pieces of data, but they behave slightly differently in terms of performance as the data grows bigger.

bash
1SADD small_set 1 2 3
2OBJECT ENCODING small_set
3# "intset"  → compact encoding for small sets of integers
4
5SADD small_set "notanumber"
6OBJECT ENCODING small_set
7# "hashtable"  → switches encoding once it no longer fits the compact case

20. How do you handle a cache stampede / thundering herd problem with Redis?

This problem happens when a very popular cache key expires, and suddenly a huge number of requests all miss the cache at the same time and hit the main database together, which can overload it. In easy language, a stampede happens when a highly popular item in Redis (like a trending news article) suddenly expires. Suddenly, 10,000 users ask for it, Redis doesn't have it, and all 10,000 users crash your main database trying to fetch it at the exact same time.

You solve this by using a Redis Lock, ensuring only the first user fetches the data from the database, while the other 9,999 wait a fraction of a second for it to be put back into Redis. The locking mechanism states that only one request is allowed to rebuild the cache while all the others simply wait for it to finish, refreshing the cache slightly before it actually expires instead of waiting for it to fully expire, adding a small random amount of extra time to each key's TTL so that many keys do not all expire at the exact same moment, and serving the old, slightly outdated data to users while the cache is being refreshed in the background.

III. Advanced Level

1. How does Redis Cluster achieve horizontal scaling and data sharding?

When you have too much data to fit into one computer's RAM, you use Redis Cluster. It automatically chops your data into chunks and spreads it across multiple computers. Every key gets automatically assigned to a specific node based on a hashing calculation, and this process of splitting data across nodes is called sharding.

Redis Cluster spreads your entire dataset across multiple different nodes, or servers, instead of keeping everything on just one machine.. As you add more nodes to the cluster, you gain the ability to store more total data and handle more overall traffic, since the load gets distributed across all the nodes instead of relying on just one.

bash
1# Check which hash slot a key maps to
2CLUSTER KEYSLOT username
3# (integer) 5474
4
5# See how slots are distributed across nodes
6CLUSTER SLOTS

2. What are hash slots in Redis Cluster, and how many total slots exist?

To keep track of where data lives, Redis Cluster divides its space into exactly 16,384 Hash Slots (think of them as 16,384 buckets). When you save a key, Redis runs a math formula on the key's name to assign it to one specific bucket. Each server in your cluster is responsible for guarding a specific range of these buckets.

3. How does Redis Cluster detect and handle node failure/failover?

Nodes in a Redis Cluster constantly send small messages back and forth to check on each other's health. The servers in a cluster constantly ping each other to say "I'm alive."

If enough nodes agree that a particular node has become unreachable, that node first gets marked as possibly failed, and then, once confirmed, it is marked as fully failed. When this happens, the cluster automatically promotes one of that failed master's replicas to take over as the new master, so the cluster can keep serving that range of hash slots without needing anyone to manually step in.

4. In terms of the CAP theorem, what tradeoffs does Redis Cluster make?

The CAP theorem states you can't have perfect Consistency (everyone seeing the exact same data instantly) and perfect Availability (the system never goes down).

Redis Cluster generally leans towards favoring availability and partition tolerance over strict consistency. Because replication between nodes is asynchronous, there is a small chance that a few very recent writes could be lost during a failover if a replica had not yet received them from the master.

In short, Redis Cluster prioritizes staying up and responsive rather than guaranteeing absolutely zero data loss in every possible situation, there is a tiny fraction of a second where a Master might crash before syncing data to its backup. This means you might experience tiny data loss in rare cases (Eventual Consistency).

5. Explain the internals of Redis's single-threaded event loop and how it still achieves high throughput.

People often ask: "If Redis only does one thing at a time, why is it so fast?" Because it lives entirely in RAM, processing a command takes microseconds. The only thing that slows computers down is waiting for network internet traffic. Redis uses special operating system tools to efficiently manage thousands of network connections at once. It grabs a command, instantly processes it in RAM, and grabs the next one, never stopping to wait.

Redis processes commands one at a time using a single main thread, but it manages to handle thousands of client connections at once through something called an event loop, which relies on efficient operating system features to know exactly when a connection has new data to read or write, without wasting time constantly checking every connection. Since most Redis operations are simple and work directly in memory, this single thread can still process hundreds of thousands of operations every second, and it also avoids all the extra complexity and potential bugs that come with multiple threads trying to change the same data at once.

6. What's the production impact of blocking commands like KEYS or FLUSHALL, and how do you mitigate it?

Because Redis only has one "cashier" (single-threaded), commands that take a long time to process will completely block the line. If you run FLUSHALL (which deletes the whole database), every other user has to wait until it finishes, which breaks your app.

For example, running KEYS on a very large dataset, or running FLUSHALL, which wipes the entire database, can cause serious delays or even downtime in a production environment.

To avoid these issues, you should use SCAN instead of KEYS, only run risky or heavy commands during planned maintenance windows, use FLUSHALL with the ASYNC option so the wipe happens in a background thread instead of blocking everything, and consider renaming or disabling particularly dangerous commands in your Redis configuration.

Or to fix this, we use Background Commands like UNLINK. UNLINK hides the data instantly so users can't see it, but slowly cleans up the memory in the background without blocking the line.

bash
1# Avoid these in production - they block the event loop:
2KEYS *
3FLUSHALL
4
5# Prefer non-blocking alternatives:
6SCAN 0 MATCH * COUNT 100
7UNLINK mykey        # async delete instead of DEL/FLUSHALL

7. How does memory fragmentation occur in Redis, and what tools help diagnose/address it?

Fragmentation happens when Redis frees up memory, for example when keys get deleted or expire, but the underlying memory allocator is not able to reuse those freed chunks efficiently, which leaves behind small gaps or holes in memory. Over time, this can cause Redis to actually use much more physical memory than the amount of data it is really storing.

Redis has an Active Defrag feature that slowly shuffles data around in the background to push the empty spaces together. Or we can check for this by running the INFO memory command and looking at a value called mem fragmentation ratio. If that number is much higher than one, it usually means fragmentation is happening.

Common fixes include using a better memory allocator like jemalloc, enabling Redis's built in active defragmentation feature, or occasionally restarting the Redis instance.

8. What happens internally during an AOF rewrite versus an RDB snapshot?

During an RDB snapshot, Redis creates a child process that goes through all the data currently in memory and writes it out into a compact binary file, essentially capturing a point in time copy of everything.

On the other hand, during an AOF rewrite, Redis compacts its ever growing command log by having a child process write out only the minimum set of commands needed to recreate the current data, and then it swaps this new, smaller file in place of the old, bloated log file.

In both cases, Redis uses a separate child process for the heavy work, so the main thread can keep serving normal requests while this happens in the background.

9. What is the gossip protocol in Redis Cluster, and what role does it play?

Instead of having one "Boss" server that manages the whole cluster, Redis uses a Gossip Protocol. It's a decentralized system where servers constantly chatter with random other servers, whispering information about who is alive, who is dead, and who holds what data. This ensures everyone is on the same page without needing a central manager.

In technical terms, Redis Cluster nodes do not rely on any single central controller to manage the cluster. Instead, they continuously exchange small messages among themselves, a process known as gossiping, sharing information about which nodes are currently up, which hash slots each node owns, and any recent failures they have noticed. This constant peer to peer communication keeps every node's understanding of the overall cluster state reasonably accurate, without depending on any single point of failure.

10. How would you design a distributed lock in Redis (e.g., the Redlock algorithm), and what criticisms has it faced?

A Distributed Lock ensures that across all your application servers, only one is allowed to do a specific task at a time (like charging a credit card).

A simple version of a distributed lock can be created using a command like SET lockkey uniquevalue NX PX 30000, where NX means the key will only be set if it does not already exist, ensuring only one client can successfully grab the lock, and PX gives the lock an automatic expiry time as a safety measure in case the client crashes while holding it. The Redlock algorithm extends this basic idea across multiple independent Redis nodes, requiring a majority of them to agree before a lock is considered acquired, which makes it more resistant to a single node failing.

However, some experts, most notably Martin Kleppmann, have argued that Redlock does not fully guarantee correctness in situations involving clock drift or long process pauses, and that it can give people a false sense of strong safety for use cases that genuinely require strict correctness. It is generally considered fine for best effort locking, but not ideal for situations where correctness absolutely cannot be compromised.

bash
1# Simplified single-node lock (Redlock extends this across N nodes)
2SET resource_lock "client123" NX PX 30000
3# NX → only set if not already locked
4# PX 30000 → auto-expires after 30 seconds (avoids permanent deadlock)
5
6# Release (only if you still own the lock) via a Lua script for atomicity
7EVAL "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end" 1 resource_lock client123

11. What Lua scripting capabilities does Redis offer (EVAL/EVALSHA), and when are they useful?

Lua is a lightweight programming language. You can write mini-programs (scripts) and send them inside Redis using the EVAL command. It allows you to safely check a value, do some math on it, and update it, all in one completely atomic step

Redis allows you to run custom Lua scripts directly on the server, either by sending the full script text using the EVAL command, or by loading a script once and running it repeatedly using its hash through the EVALSHA command, which saves you from resending the whole script every time. These scripts run atomically, meaning no other command can run in between the steps of your script, which makes Lua scripting extremely useful when you need several Redis operations to happen together safely as a single unit, such as building custom rate limiters or performing conditional updates.

lua
1-- increment.lua
2local current = redis.call("GET", KEYS[1])
3if not current then current = 0 end
4redis.call("SET", KEYS[1], current + ARGV[1])
5return current + ARGV[1]

12. How does Redis achieve atomicity for multi-key operations without full ACID transaction support?

Redis does not offer full relational style ACID transactions, and in particular it does not support rolling back commands in the middle of a transaction. However, it still achieves atomicity in a few important ways. Traditional databases use complex mathematical locks to ensure transactions are safe (ACID).

Redis achieves Atomicity simply by being single-threaded. Because Redis is single threaded, no other command can ever run in the middle of one that is currently executing. MULTI and EXEC let you group several commands together so they run as one uninterrupted block. And Lua scripts let you write more complex, multi step logic that also runs as a single atomic unit. So while true rollback is missing, these mechanisms guarantee that nothing else can sneak in between your operations, which is good enough atomicity for the vast majority of real world use cases.

13. What is client-side caching in Redis (RESP3 tracking), and how does invalidation work there?

With the newer RESP3 protocol, Redis supports a feature called client side caching, where the client itself keeps a local copy of keys it has recently read, so it does not need to keep asking Redis for the same data again and again. Redis keeps track of which clients have cached which keys, and if any of those keys get changed,

Usually, your app asks Redis for data. But even asking Redis takes network time. With Client-Side Caching, your app saves a copy of the Redis data in its own local memory for zero-wait time. The clever part? Redis remembers that your app has a copy. The moment that data gets changed in Redis, Redis sends a message to your app saying, "Hey, your local copy is old, delete it!" (Invalidation Message).

Redis proactively sends a notification to those specific clients so they know to remove their outdated local copy. This helps avoid serving stale data while still saving a lot of unnecessary round trips for data that has not changed.

14. How would you design a large-scale leaderboard system using Redis Sorted Sets?

We would use a Sorted Set where each member represents a player's ID and the score represents their points or ranking value. Every time a player's score changes, you simply update it using the ZADD command.

To get the top players, you can use ZREVRANGE to fetch the highest scoring members along with their scores, and to find out where a specific player currently ranks, you can use the ZRANK command.

Since Sorted Sets keep everything automatically sorted with very efficient insert and update operations, this approach scales comfortably even with millions of players, without you ever needing to manually sort anything yourself.

Every time they earn points, you use the ZADD command. Because of how Sorted Sets are structured, Redis mathematically updates their rank instantly.

You can ask Redis for the "Top 10 players" or "What rank is User #5029" and it will return the answer instantly, even if there are 10 million players on the board.

bash
1# Add/update a player's score
2ZADD leaderboard 1500 "player:42"
3
4# Get top 10 players, highest score first
5ZREVRANGE leaderboard 0 9 WITHSCORES
6
7# Get a specific player's rank (0-indexed, highest first)
8ZREVRANK leaderboard "player:42"

15. What are the tradeoffs of using Redis as a primary datastore versus a cache-only layer, particularly around durability guarantees?

AspectRedis as a Primary DatastoreRedis as a Cache-Only Layer
PurposeStores the application's main and authoritative data.Stores temporary copies of frequently accessed data to improve performance.
DurabilityRequires strong persistence (AOF and/or RDB) and replication to prevent data loss.Durability is not critical because the original data remains in the primary database.
PerformanceSlower when AOF is configured to save every write due to continuous disk I/O.Faster because persistence can be disabled, allowing Redis to operate entirely in memory.
Data LossData loss can be serious since Redis holds the only copy of the data.Data loss is acceptable because the cache can be rebuilt from the primary database.
RecoveryRecovery depends on persistence files (AOF/RDB) and replication.After a restart, the cache is simply repopulated from the main database.
FeaturesLacks advanced relational database features such as joins, relationships, and constraints.Works alongside a relational database, which continues to provide advanced data management features.

Key Points:

  • Redis as a Primary Datastore

  • Redis becomes the single source of truth for the application.

  • Requires AOF and/or RDB persistence with proper replication to ensure durability.

  • Enabling AOF to save every write improves durability but reduces performance due to constant disk writes.

  • Any data loss can have serious consequences because there is no other copy of the data.

  • Does not provide advanced relational database features like joins, foreign keys, or constraints.

  • Redis as a Cache-Only Layer

  • Redis stores temporary copies of data while the primary database remains the authoritative source.

  • Persistence can be disabled for maximum in-memory performance.

  • If Redis crashes or restarts, cached data is lost but can be rebuilt from the main database.

  • Provides extremely fast read and write performance with minimal durability concerns.

  • Ideal for speed-sensitive applications where temporary data loss is acceptable.

Found this helpful?

Share it with your network

Related Articles

Frontend

JavaScript

Prepare for your next tech interview with the most asked JavaScript interview questions and answers. It includes basic to advanced concepts, coding problems, and real-world scenarios for freshers and experienced developers.

Fullstack

Next Js

Explore the most important Next.js interview questions including SSR, SSG, ISR, routing, performance optimization, and real-world implementation examples.