Most Asked Redis Interview Questions and Answers

Redis Interview Questions and Answers

Redis is a popular in-memory database used for a variety of projects, like caching and rate limiting.

1) What is Redis?

Redis is an advanced key-value data store and cache. It has is also referred to as a data structure server as such the keys not only contains strings, but also hashes, sets, lists, and sorted sets. Companies using Redis includes StackOverflow, Twitter, Github, etc.

2) Explain the Replication feature of Redis?

Redis supports simple master to slave replication.  When a relationship is established, data from the master is transferred to the slave. Once this is done, all changes to the master replicate to the slave

3) What is the difference between Memcached and Redis?

                           Redis                           Memcached
Redis also does cache information but has got additional features like persistence and replicationRedis does not support the functionality of LRU (least recently used) eviction of valuesIn Redis you can set a time out on everything when memory is full, it will look at three random keys and deletes the one which is closest to expiryRedis does not support CAS ( Check and Set). It is useful for maintaining cache consistencyRedis has got stronger data structures; it can handle strings, binary safe strings, list of binary safe strings, sorted lists, etc.Redis had a maximum of 2GB key lengthRedis is single threaded Memcached only cache information.Memcached supports the functionality of LRU (least recently used) eviction of valuesIn Memcached when they overflow memory, the one you have not used recently (LRU- least recently used) will get deletedMemcached supports CAS (Check and Set)In Memcached, you have to serialize the objects or arrays in order to save them and to read them back you have to un-serialize them.Memcached had a maximum of 250 bytes lengthMemcached is a multi-threaded
Difference of Redis and Memcached

4) What are the advantages of using Redis?

Advantage of using Redis are

  • It provides high speed
  • It supports a server-side locking
  • It has got lots of client lib
  • It has got command level Atomic Operation (tx operation)

5) What are the limitations of Redis?

  • It is single threaded
  • It has got limited client support for consistent hashing
  • It has significant overhead for persistence
  • It is not deployed widely
467px-Redis_Logo.svg

6) List out the operation keys of Redis?

Operation keys of Redis include

  • TYPE key
  • TTL key
  • KEYS pattern
  • EXPIRE key seconds
  • EXPIREAT key timestamp
  • EXISTS key
  • DEL key

7) Which PHP module can be used with Redis?

In PHP module, PRedis is more preferable than Redid PHP binding or Resident

8) Does Redis give speed and durability both?

No, Redis purposely compromises the durability to enhance the speed. In Redis, in the event of system failure or crash, Redis writes to disk but may fall behind and lose the data which is not stored.

9) How can you improve the durability in Redis?

To improve the durability of Redis “append only file” can be configured by using fsync data on disk.

  • Fsync () every time a new command is added to the append log file: It is safe but very slow
  • Fysnc() one time every second: It is fast, but you may lose 1 second of data if system fails
  • Never fsync(): It is an unsafe method, and your data is in hand of Operating System

10) Mention what are the things you have to take care while using Redis?

While using Redis one must take care of

  • Select a consistent method to name and prefix your keys. Manage your namespace
  • Create a “Registry” of key prefixes that maps each of your internal documents for that application which “own” them
  • For every class you put through into your Redis infrastructure: design, implement and test the mechanisms for garbage collection or data migration to archival storage
  • Design, implement and test a sharding library before you have invested much into your application deployment and make sure that you keep a registry of “shards “replicated on each server
  • Separate all your K/V store and related operations into your own library/API or service

11) What are the disadvantages/limitations of using Redis?

Following are the disadvantages/ limitations of Redis:

  • It is single threaded.
  • It has got limited client support for consistent hashing.
  • It has significant overhead for persistence.
  • It is not deployed widely.

12) What is the difference between Redis and RDBMS?

There are a lot of differences between Redis and RDBMS:

  • Redis is a NoSQL database while RDBMS is an SQL database.
  • Redis follows the key-value structure while RDBMS follows the table structure.
  • Redis extremely fast while RDBMS is comparatively slow.
  • Redis stores all the dataset in primary memory while RDBMS stores its dataset in secondary memory.
  • Redis is generally used to store small and frequently used files while RDBMS is used to store big files.
  • Redis provides only official support for Linux, BSD, Mac OS X, Solaris. It doesn?t provide official support for Windows currently while RDBMS provides support for both.

13) What are the Operation Keys of Redis?

  • TYPE key
  • TTL key
  • EXPIRE key seconds
  • EXPIREAT key timestamp
  • EXISTS key
  • DEL key

14) What are the different data types used in Redis?

There are mainly 5 types of data types supported by Redis:

  • Strings
  • Hashes
  • Lists
  • Sets
  • Sorted Sets

15) We all know that Reds is fast, but is it also durable?

In Redis, there is always a trade-of between durability and speed. In the case of system failure, it may lose data which is not stored.


16) How can you enhance the durability of Redis?

  • Whenever a new command is added to the append log file, call Fsysnc() each time.
  • Keep calling Fsysnc() in every second. Despite of the 1 second data lose in the case of system fails.

17) What are the concerned things while using Redis?

  • Consistent method selection in order to name and prefix the keys. Namespace management.
  • Make key prefixes registry which can map every documents to their owner applications.
  • Designing, implementing and testing the Garbage collection mechanism for each class we keep into the redis architecture.
  • Maintain a sharding library before investing so much into the application.

Click here to read more blogs

Click here to read more Technical Q&A

Click here to read more latest interview questions and answers

What is an in-memory database?

Traditional databases keep part of the database (usually the “hot” or often-accessed indices) in memory for faster access, and the rest of the database on disk.

Redis, on the other hand, focuses a lot on latency and the fast retrieval and storage of data. So it operates completely on memory (RAM) instead of storage devices (SSD/HDD). Speed is important!

Redis is a key-value database. But don’t let it fool you into thinking it’s a simple database. You have a lot of ways to store and retrieve those keys and values.

Why do you need Redis?

You can use Redis in a lot of ways. But there are two main reasons I can think of:

  1. You are creating an application where you want to make your code layer stateless. Why? – Because if your code is stateless, it is horizontally scalable. Therefore, you can use Redis as a central storage system and let your code handle just the logic.
  2. You are creating an application where multiple apps might need to share data. For example, what if somebody is trying to bruteforce your site at payments.codedamn.com, and once you detect it, you’d also like to block them at login.codedamn.com? Redis lets your multiple disconnected/loosely connected services share a common memory space.

Redis Basics

Redis is relatively simple to learn as there are only a handful of commands you’ll need to know. In the next couple sections, we’ll cover a few main Redis concepts and some useful common commands.

The Redis CLI

ezgif.com-gif-maker

Redis has a CLI which is a REPL version of the command line. Whatever you write will be evaluated.

The above image shows you how to do a simple PING or hello world in Redis in one of my codedamn Redis course exercises (the course is linked at the end if you want to check it out).

This Redis REPL is very useful when you’re working with the database in an application and quickly need to get a peek into a few keys or the state of Redis.

Common Redis commands

ezgif.com-gif-maker--1-
Trying out common commands on Redis CLI in codedamn course

Here are a few very commonly used commands in Redis to help you learn more about how it works:

SET

SET allows you to set a key to a value in Redis.

Here’s an example of how it works:

SET mehul "developer from india"

This sets the key mehul to the value developer from india.

GET

GET allows you to get the keys you’ve set.

Here’s the syntax:

GET mehul

This will return the string “developer from india” as we set above.

SETNX

This key will set a value only if the key does not exist. This command has a number of use cases, including not accidentally overwriting the value of a key which might already be present.

Here’s how it works:

SET key1 value1
SETNX key1 value2
SETNX key2 value2

After running this example, your key1 will have the value value1 and key2 as value2. This is because the second command will have no effect as key1 was already present.

MSET

MSET is like SET, but you can set multiple keys together in one command. Here’s how it works:

MSET key1 "value1" key2 "value2" key3 "value3"

Right now we are using key and value as the prefix for keys and values. But in reality when you write such code it’s easy to lose track of what is a key and what is a value in such a long command.

So one thing you can do is always quote your value using double quotes, and leave your keys without quotes (if they are valid keynames without quotes).

MGET

MGET is similar to GET, but it can return multiple values at once, like this:

MGET key1 key2 key3 key4

This will return four values as an array: value1value2value3 and null. We got key4 as null because we never set it.

DEL

This command deletes a key – simple enough, right?

Here’s an example:

SET key value
GET key # gives you "value"
DEL key 
GET key # null

INCR and DECR

You can use these two commands to increment or decrement a key which is a number. They are very useful and you’ll use them a lot, because Redis can perform two operations in one – GET key and SET key to key + 1.

This avoids roundtrips to your parent application, and makes the operation also safe to perform without using transactions (more on this later)

Here’s how they work:

SET favNum 10
INCR favNum # 11
INCR favNum # 12
DECR favNum # 11

EXPIRE

The EXPIRE command is used to set an expiration timer to a key. Technically it’s not a timer, but a kill timestamp beyond which the key will always return null unless it’s set again.

SET bitcoin 100
EXPIRE bitcoin 10

GET bitcoin # 100
# after 10 seconds
GET bitcoin # null

EXPIRE uses a little bit more memory to store that key as a whole (because now you have to also store when that key should expire). But you probably won’t ever care about that overhead.

TTL

This command can be used to learn how much time the key has to live.

Example:

SET bitcoin 100
TTL bitcoin # -1
TTL somethingelse # -2

EXPIRE bitcoin 5
# wait 2 seconds
TTL bitcoin # returns 3
# after 1 second
GET bitcoin # null
TTL bitcoin # -2

So what can we learn from this code?

  1. TTL will return -1 if the key exists but doesn’t have an expiration
  2. TTL will return -2 if the key doesn’t exist
  3. TTL will return time to live in seconds if the key exists and will expire

SETEX

You can perform SET and EXPIRE together with SETEX.

Like this:

SETEX key 10 value

Here, the key is “key”, the value is “value”, and the time to live (TTL) is 10. This key will get unset after 10 seconds.

Now that you have fundamental knowledge of basic Redis commands and how the CLI works, let’s build a couple of projects and use those tools in real life.

Project 1 – Build an API Caching System with Redis

Screenshot-2021-04-13-at-4.20.13-AM
Preview of API caching system building lab on codedamn

This project involves setting up an API caching system with Redis, where you cache results from a 3rd party server and use it for some time.

This is useful so that you are not rate limited by that third party. Also, caching improves your site’s speed, so if you implement it correctly it’s a win-win for everyone.

You can build this project interactively on codedamn inside the browser using Node.js. If you’re interested, you can try the API caching lab for free.

If you’re only interested in the solution (and not building it yourself) here’s how the core logic will work in Node.js:

app.post('/data', async (req, res) => {
	const repo = req.body.repo

	const value = await redis.get(repo)

	if (value) {
		// means we got a cache hit
		res.json({
			status: 'ok',
			stars: value
		})

		return
	}

	const response = await fetch(`https://api.github.com/repos/${repo}`).then((t) => t.json())

	if (response.stargazers_count != undefined) {
		await redis.setex(repo, 60, response.stargazers_count)
	}

	res.json({
		status: 'ok',
		stars: response.stargazers_count
	})
})

About Author


After years of Technical Work, I feel like an expert when it comes to Develop wordpress website. Check out How to Create a Wordpress Website in 5 Mins, and Earn Money Online Follow me on Facebook for all the latest updates.

Leave a Comment