Redis interview questions

1. What is Redis? .

What is the data type of Redis?

3, Redis is single process single thread?

What are the advantages of Redis over Memcached?

5. What are the differences between Memcache and Redis?

6. What are the benefits of using Redis?

7. What is the maximum size that a string value can store?

8. What is the Redis persistence mechanism? What are the pros and cons?

Common Redis Performance Problems and Solutions:

10, Redis expired key deletion policy?

11. Redis recycling strategy (elimination strategy)?

12. Why does EDIS need to put all the data in memory?

13. Do you know the synchronization mechanism of Redis?

What is the benefit of a Pipeline and why is it used?

15, Have you ever used Redis cluster? What is the principle of cluster?

16. When will the Redis Cluster solution make the whole cluster unusable?

17. What are the Java clients that Redis supports? Which is the official recommendation?

18. What are the advantages and disadvantages of Jedis compared with Redisson?

19. How to set password and verify password in Redis?

20. What is the concept of Redis hash slot?

21. What is the master-slave replication model of Redis cluster?

22. Will write operations be lost in the Redis cluster? Why is that?

23. How do Redis clusters replicate between each other?

24. What is the maximum number of nodes in the Redis cluster?

How to select database for Redis cluster?

26. How do you test Redis connectivity?

How do you understand Redis transactions?

28. What are the Redis transaction related commands?

29. How to set the expiration time and permanent validity of Redis Key respectively?

How does Redis do memory optimization?

31. How does the Redis recycling process work?

32. What are some ways to reduce Redis memory usage?

33. What happens when Redis runs out of memory?

34, How many keys can a Redis instance store? List, Set, Sorted Set How many elements can they store at most?

35. There is 2000W data in MySQL, but only 20W data in Redis. How to ensure that all data in Redis are hot data?

36. The most suitable scene for Redis?

37. Suppose there are 100 million keys in Redis, and 10W of them begin with some fixed known prefix. If you find all of them?

38, If a large number of keys need to be set to expire at the same time, what should be paid attention to?

39, Have you ever used Redis for an asynchronous queue, how do you use it?

Have you ever used Redis distributed lock? What is it?

I have compiled all the Redis interview questions and answers into PDF as needed
Click here toavailable

The knowledge points about it are summarized as mind maps

1. What is Redis?

Answer: Redis is completely open source and free, in compliance with the BSD protocol, is a high performance key-value database.

Redis and other key-value caching products have the following three characteristics:

  • Redis supports persistent data, which can be stored in memory on disk and reloaded for use when restarted.
  • Redis supports not only simple key-value data, but also lists, sets, zsets, hashes, and other data structures.
  • Redis supports backup of data in master-slave mode.

Redis advantage

  • Extreme performance – Redis can read at 110,000 times per second and write at 81,000 times per second.
  • Rich data types – Redis supports Strings, Lists, Hashes, Sets and Ordered Sets data types for binary cases.
  • Atomic – All operations of Redis are atomic, meaning they either succeed or fail at all. A single operation is atomic. Multiple operations also support transactions, that is, atomicity, wrapped in MULTI and EXEC directives.
  • Rich features – Redis also supports publish/subscribe, notifications, key expiration, and more.

How does Redis differ from other key-value stores?

  • Redis has more complex data structures and provides atomic manipulation of them, which is a different evolutionary path than other databases. Redis data types are based on basic data structures while being transparent to the programmer without the need for additional abstraction.
  • Redis runs in memory but can be persisted to disk, so there is a memory tradeoff when it comes to high-speed reads and writes to different data sets, because the data volume cannot be larger than the hardware memory. Another advantage of an in-memory database is that Redis can do a lot of things with a lot of internal complexity because it is much easier to manipulate in memory than the same complex data structure on disk. At the same time, they are compact and appended in terms of disk formats because they do not require random access.

What is the data type of Redis?

A: Redis supports five types of data: string, hash, list, set, and zsetsorted set.

One of the things that we use a lot in our actual projects is string, hash and if you’re an advanced user in Redis, you need to add the following data structures Hyperloglog, Geo, Pub/Sub.

If you say you’ve played Redis modules like BloomFilter, RedisSearch, and Redis-ML, your interviewer’s eyes will start to light up.

3. What are the benefits of using Redis?

  • Fast, because the data is stored in memory, similar to HashMap, the advantage of HashMap is that the time complexity of search and operation is O1.)
  • Support rich data types, support string, list, set, Zset, hash, etc
  • Transactional support, operations are atomic, the so-called atomic means that the changes to the data are either all or not all executed
  • Rich features: can be used for caching, messages, set expiration time by key, after expiration will be automatically deleted

What are the advantages of Redis over Memcached?

  • Instead of Memcached, where all values are simple strings, Redis supports a much richer data class
  • Redis is much faster than Memcached
  • Redis can persist its data

5. What are the differences between Memcache and Redis?

  • Memecache stores all the data in memory, and it will be hung up after power failure. The data cannot exceed the memory size. Part of Redis is stored on the hard disk, which ensures the persistence of the data.
  • Data support types Memcache has relatively simple data type support. Redis has complex data types.
  • Using the underlying models differs in the underlying implementation between them and in the application protocols used to communicate with clients. Redis built the VM mechanism itself, because a normal system call to a system function would waste some time moving and requesting.

6, Redis is single process single thread?

Answer: Redis is a single process and single thread. Redis uses queue technology to change concurrent access into serial access, eliminating the overhead of traditional database serial control.

7. What is the maximum size that a string value can store?

A: 512 m

8. What is the Redis persistence mechanism? What are the pros and cons?

Redis provides two persistence mechanisms, RDB and AOF:

RDBRedis DataBase)

Recorded all key and value pairs of the Redis database. Write the data to a temporary file at a certain point in time. After the end of persistence, replace the last persisted file with this temporary file to achieve data recovery.

Advantages:

  • There is only one file dump.rdb for easy persistence.
  • Good disaster tolerance, a file can be saved to a safe disk.
  • Performance maximization, fork the child process to complete the write, and let the main process continue to process the command, so I/O maximization. Persistence using a separate child process, the main process will not do any IO operations, to ensure the high performance of Redis.
  • When the data set is large, the startup efficiency is higher than AOF.

Disadvantages:

  • Low data security. RDB is persisted at intervals, and if Redis fails during persistence, data loss will occur. So this approach is more suitable for data requirements are not rigorous

2, AOFAPPend-Only File)

All command line records are fully persisted in Redis Command Request Protocol format (AOF file).

Advantages:

  • Data security, AOF persistence can be configured with the appendfsync attribute, always, and logged to the AOF file for every command operation.
  • If you write files in APPEND mode, even if the server goes down midway, you can use the Redis-Check-AOF tool to solve the problem of data consistency.
  • The REWRITE model for the AOF mechanism. You can delete commands from AOF files (such as flushall) before they are rewritten (when the files are too large, they merge and rewrite commands).

Disadvantages:

  • AOF files are larger than RDB files and are slower to recover.
  • When the data set is large, the startup efficiency is lower than RDB.

Common Redis Performance Problems and Solutions:

  • If Master writes a snapshot of memory, the save command dispatches the RDBSave function, which will block the work of the main thread. When the snapshot is large, the performance will be greatly affected, and the service will be suspended intermittency
  • If the data is important, a Slave starts AOF to backup the data, and the policy is set to one synchronization per second
  • For the speed of master-slave replication and the stability of connection, it is better for Master and Slave to be in the same LAN
  • Try to avoid adding slaves to a stressed-out primary database
  • Master < -slave1 < -slave2 < -slave3… Master < -slave1 < -slave2… This structure is convenient to solve the single point fault problem and realize the replacement of Slave to Master. If the Master fails, you can immediately enable Slave1 as Master, and everything else remains the same.

10, Redis expired key deletion policy?

  • Timed Delete: Create a timer timer while setting the expiration time of the key. Allow the timer to delete the key as soon as the key’s expiration time comes.
  • Lazy deletion: Allow the key to expire, but every time a key is retrieved from the key space, check to see if the obtained key is expired, and if so, delete the key; If it has not expired, the key is returned.
  • Periodic deletion: every once in a while the program checks the database to remove expired keys. It is up to the algorithm to decide how many expired keys to delete and how many databases to check.

11. Redis recycling strategy (elimination strategy)?

  • Volatile-LRU: Picks out the least recently used data from a dataset (server.db[I].expires) that has an expiration date set
  • Volatile-ttl: Selects data to expire from a dataset (server.db[I].expires) that has already expired
  • Volatile-random: Select arbitrary data elimination from a data set (Server.db [I].Expires) that has an expiration date set
  • AllKeys-lru: Selects the least recently used data cull from the dataset (server.db[I].dict)
  • AllKeys-random: Select arbitrary data cull from the data set (server.db[I].dict)
  • No-enviction: It is forbidden to expel data

Note that volatile and allkeys specify whether data should be eliminated from a dataset with an expiration date or from the entire dataset. LRU, TTL, and RANDOM are three different strategies for elimination. Plus a no-enviction never-recyclable strategy.

Use policy rules:

  • AllKeys-LRU is used if the data is power-law distributed, that is, some data is accessed frequently and some data is accessed infrequently
  • If the data is equally distributed, that is, all data access frequency is the same, then allKeys-random is used

12. Why does EDIS need to put all the data in memory?

Answer: Redis reads data into memory for maximum read and write speed and writes data to disk asynchronously. So Redis is fast and data persistent. If you don’t put data in memory, disk I/O speed is a serious impact on Redis performance. In today’s cheaper and cheaper memory, Redis will become more and more popular. If the maximum memory usage is set, new values cannot be inserted after the memory limit has been reached.

13. Do you know the synchronization mechanism of Redis?

Answer: Redis can use master-slave synchronization and slave-slave synchronization. During the first synchronization, the master node makes a bgsave and records subsequent modifications to the memory buffer at the same time. Upon completion, the RDB file will be fully synchronized to the replicated node, and the RDB image will be loaded into the memory after the replicated node receives the RDB image. After the loading is completed, the synchronization process is completed by notifying the master node to synchronize the modified operation records to the replicated node for replay.

What is the benefit of a Pipeline and why is it used?

A: Multiple IO round-trips can be reduced to one if there is no causal correlation between the instructions executed by the PIPELINE. When using Redis-Benchmark to run a test, it can be found that an important factor that affects the QPS peak in Redis is the number of Pipeline batch instructions.

15, Have you ever used Redis cluster? What is the principle of cluster?

  • Redis Sentinal is focused on high availability and will automatically promote slave to master when the master goes down to continue service.
  • Redis Cluster focuses on scalability and uses Cluster for sharding storage when a single Redis is out of memory.

16. When will the Redis Cluster solution make the whole cluster unusable?

A: For A cluster with nodes A, B, and C, without A replication model, if node B fails, the entire cluster will be deemed to lack slots in the 5501-11000 range and will not be available.

17. What are the Java clients that Redis supports? Which is the official recommendation?

A: Redisson, Jedis, lettuce, etc. The official recommendation is Redisson.

18. What are the advantages and disadvantages of Jedis compared with Redisson?

Answer: Jedis is a Java implementation of Redis client, its API provides relatively comprehensive support for Redis commands; Redisson implements a distributed and extensible Java data structure. Compared with Jedis, it has relatively simple functions. It does not support string manipulation, sorting, transactions, piping, partitioning, and other Redis features.

The goal of Redisson is to facilitate the separation of attention from Redisso that users can focus more on dealing with the business logic.

19. How to set password and verify password in Redis?

Set password: config set requirepass 123456

Authorization password: auth 123456

20. What is the concept of Redis hash slot?

Answer: Redis cluster does not use consistent hash, but introduces the concept of hash slot. There are 16384 hash slots in Redis cluster, and each key is modulated to 16384 after CRC16 verification to decide which slot to place. Each node of the cluster is responsible for part of hash slot.

21. What is the master-slave replication model of Redis cluster?

A: To make the cluster usable even if some of the nodes fail or most of the nodes are unable to communicate, the cluster uses a master-slave replication model, where there are n-1 replicas per node.

22. Will write operations be lost in the Redis cluster? Why is that?

A: Redis does not guarantee strong data consistency, which means that in practice the cluster may lose writes under certain conditions.

23. How do Redis clusters replicate between each other?

Answer: Asynchronous replication

24. What is the maximum number of nodes in the Redis cluster?

A: 16,384.

How to select database for Redis cluster?

A: The Redis cluster is currently unable to select a database. The default database is 0.

26. How do you test Redis connectivity?

Answer: Use ping command.

How do you understand Redis transactions?

A:

  • A transaction is a single isolated operation: all the commands in the transaction are serialized and executed sequentially. The execution of the transaction will not be interrupted by the command request sent by the other client.
  • A transaction is an atomic operation: either all or none of the commands in the transaction are executed.

28. What are the Redis transaction related commands?

A: Multi, EXEC, DISCARD, WATCH

29. How to set the expiration time and permanent validity of Redis Key respectively?

A: EXPIRE and PERSIST commands.

How does Redis do memory optimization?

A: Use hashes whenever possible. Hashes use very small amounts of memory, so you should abstract your data model into a hash table as much as possible. For example, if you have a user object in your web system, instead of setting a single key for the user’s first name, last name, email address, and password, store all of the user’s information in a hash table.

31. How does the Redis recycling process work?

A: A client runs a new command and adds new data. Redi checks memory usage, and if it is greater than the maxMemory limit, it is recycled according to the set policy. A new command is executed, and so on. So we keep crossing the boundary of the memory limit, by reaching the boundary and then recycling back below the boundary. If the result of a command causes a large amount of memory to be used (for example, the intersection of a large collection to be saved to a new key), it doesn’t take long for the memory limit to be exceeded by the memory usage.

32. What are some ways to reduce Redis memory usage?

A: If you’re using 32-bit Redis instances, make good use of the Hash,list,sorted,set, and other aggregated types of data, because usually a lot of small key-values can be sorted together in a more compact way.

33. What happens when Redis runs out of memory?

A: Redis write commands will return an error message if the upper limit is reached (but read commands will return normally). Or you can use Redis as a cache to configure a culling mechanism that will flush out the old content when the Redis reaches its memory limit.

34, How many keys can a Redis instance store? List, Set, Sorted Set How many elements can they store at most?

A: Theoretically, Redis can handle up to 232 keys, and it has been tested in practice, storing at least 250 million keys per instance. We are testing some larger values. Any list, set, and sorted set can have 232 elements. In other words, the storage limit for Redis is the value of available memory in the system.

35. There is 2000W data in MySQL, but only 20W data in Redis. How to ensure that all data in Redis are hot data?

A: When the size of the Redis memory dataset increases to a certain size, a data culling policy is implemented.

Knowledge: Redis offers six data culling strategies:

  • Volatile-LRU: Picks out the least recently used data from a dataset (server.db[I].expires) that has an expiration date set
  • Volatile-ttl: Selects data to expire from a dataset (server.db[I].expires) that has already expired
  • Volatile-random: Select arbitrary data elimination from a data set (Server.db [I].Expires) that has an expiration date set
  • AllKeys-lru: Selects the least recently used data cull from the dataset (server.db[I].dict)
  • AllKeys-random: Select arbitrary data cull from the data set (server.db[I].dict)
  • No-enviction: It is forbidden to expel data

36. The most suitable scene for Redis?

1. Session Cache

One of the most common scenarios for using Redis is the session cache. Caching sessions with Redis has one advantage over other stores such as Memcached: Redis provides persistence. When maintaining a cache that is not strictly consistent, most people would not be happy if all of their shopping cart information was lost. Now, would they? Fortunately, as Redis has improved over the years, it’s easy to figure out how to properly use Redis to cache session documents. Even popular business platform Magento offers Redis plugins.

2. Full Page Cache (FPC)

In addition to the basic session token, Redis also provides a very simple FPC platform. Returning to the consistency issue, even if the Redis instance is restarted, the user will not see the page load speed decrease due to the persistence of the disk, which is a huge improvement, similar to the PHP native FPC. Take Magento again, which provides a plug-in to use Redis as a full-page caching backend. Also, for WordPress users, Pantheon has a great plugin, WP-Redis, that will help you load the pages you’ve visited as quickly as possible.

3, the queue

One of the great advantages of REIDS in the memory storage engine space is that it provides list and set operations, which makes Redis a good message queue platform to use. The operations used by Redis as queues are similar to the push/pop operations of a list in a native programming language such as Python. If you do a quick Google search for “Redis Queues”, you’ll immediately find a number of open source projects that aim to use Redis to create great back-end tools for all kinds of queues. For example, Celery has a backend that uses Redis as a broker, which you can check out here.

4, Leaderboards/Counters

Redis is very good at incrementing or decrementing numbers in memory. Sets and Sorted sets also make it easy to do these kinds of things, and Redis just happens to provide these two data structures. So, to get the top 10 users from the sort set — we call this “user_scores” — we just do the same thing: assuming, of course, that you’re sorting incrementing by your user’s score. If you want to return the user and the user’s score, you need to do this: Zrange user_scores 0 10 Withscores Agora Games is a good example, implemented in Ruby, where the leaderboards are stored using Redis, as you can see here.

5. Publish/subscribe

Last (but certainly not least) is Redis’ publish/subscribe feature. There are a lot of use scenarios for publish/subscribe. I’ve seen people use it in social networking connections, as a trigger for publish/subscribe based scripts, and even use Redis publish/subscribe to set up chat systems!

37. Suppose there are 100 million keys in Redis, and 10W of them begin with some fixed known prefix. If you find all of them?

A: The Keys directive can be used to scan out the list of keys of the specified mode.

What’s the problem with using the KEYS directive if the Redis is serving an online business?

At this point you need to answer one of the key features of Redis: Redis is single-threaded. The Keys instruction causes the thread to block for a period of time, and the online service to stop until the instruction is completed. At this time, you can use the SCAN instruction. The SCAN instruction can extract the key list of the specified mode without blocking, but there will be a certain probability of repetition. It is enough to do a reduplication in the client, but the overall time will be longer than the direct use of the KEYS instruction.

38, If a large number of keys need to be set to expire at the same time, what should be paid attention to?

A: If a large number of key expiration times are set too centrally, Redis may experience temporary stalling at the expiration point. It is generally necessary to add a random value to the time to spread out the expiration time.

39, Have you ever used Redis for an asynchronous queue, how do you use it?

A: The list structure is generally used as the queue, with RPUSH producing messages and LPOP consuming messages. When there is no message from LPOP, sleep for a while and then try again. If the other side asks, can not use sleep? The list also has an instruction called blpop, which blocks until a message arrives in the absence of a message. And if they ask, can we produce and consume more than once? Using the Pub/Sub Subject Subscriber pattern, a 1:N message queue can be implemented.

What are the disadvantages of pub/sub?

  • In the case of a consumer going offline, the produced messages are lost and professional message queues such as RabbitMQ are used.

If the other side asks Redis how to implement delayed queue?

  • I’m guessing you’d like to beat the interviewer to death right now if you have a baseball bat in your hand. But you are very restrained, and then answer with an air of composure: use SortedSet, take the timestamp as the score, the message content as the key to call Zadd to produce the message, and the consumer uses the ZRangeByScore command to get the data polling before N seconds for processing. At this point, the interviewer has secretly given you the thumbs up. But what he doesn’t know is that now you’re holding up your middle finger, behind the chair.

Have you ever used Redis distributed lock? What is it?

A: If you use SETNX to preclude the lock, then use expire to preclude the lock from being released. A: If you preclude the lock from being released, then use expire to preclude the lock from being released.

You will be told that your answer is good, and then you will be asked what happens if the process before expires crashes after setnx or has to be restarted for maintenance. This is when you have to give the surprising feedback: oh yeah, the lock will never be released. Then you have to scratch your head and think for a moment as if the next result is something you thought about on your own, and answer: I remember the set directive had very complex arguments, and this should have worked with the setnx and expire instructions together! The other side will show a smile at this time, the heart began to silently: press, this guy is not bad.

The last

Xiaobian sorted out more than 1000 JAVA interview questions of more than 400 pages of PDF documents,Click here toavailable



For the above interview asked knowledge I summarizes the Internet company’s Java programmer interview involves most of the interview questions and answers into a document and architecture data Shared with everybody, hope I can help to you and find a good job of before the interview, also save you search for information on the Internet to learn.

Welcome to exchange, collate information is not easy, like the article remember to point a like yo, thank you for your support!!