All topics

Redis interview questions

22 questions with answers. 336 open jobs in India ask for Redis.

  1. Memcached vs. Redis?

    Summary (TL;DR)

    Updated June 3rd, 2017

    Redis is more powerful, more popular, and better supported than memcached. Memcached can only do a small fraction of the things Redis can do. Redis is better even where their features overlap.

    For anything new, use Redis.

    Memcached vs Redis: Direct Comparison

    Both tools are powerful, fast, in-memory data stores that are useful as a cache. Both can help speed up your application by caching database results, HTML fragments, or anything else that might be expensive to generate.

    Points to Consider

    When used for the same thing, here is how they compare using the original question's "Points to Consider":

    • Read/write speed: Both are extremely fast. Benchmarks vary by workload, versions, and many other factors but generally show redis to be as fast or almost as fast as memcached. I recommend redis, but not because memcached is slow. It's not.
    • Memory usage: Redis is better.
      • memcached: You specify the cache size and as you insert items the daemon quickly grows to a little more than this size. There is never really a way to reclaim any of that space, short of restarting memcached. All your keys could be expired, you could flush the database, and it would still use the full chunk of RAM you configured it with.
      • redis: Setting a max size is up to you. Redis will never use more than it has to and will give you back memory it is no longer using.
      • I stored 100,000 ~2KB strings (~200MB) of random sentences into both. Memcached RAM usage grew to ~225MB. Redis RAM usage grew to ~228MB. After flushing both, redis dropped to ~29MB and memcached stayed at ~225MB. They are similarly efficient in how they store data, but only one is capable of reclaiming it.
    • Disk I/O dumping: A clear win for redis since it does this by default and has very configurable persistence. Memcached has no mechanisms for dumping to disk without 3rd party tools.
    • Scaling: Both give you tons of headroom before you need more than a single instance as a cache. Redis includes tools to help you go beyond that while memcached does not.

    memcached

    Memcached is a simple volatile cache server. It allows you to store key/value pairs where the value is limited to being a string up to 1MB.

    It's good at this, but that's all it does. You can access those values by their key at extremely high speed, often saturating available network or even memory bandwidth.

    When you restart memcached your data is gone. This is fine for a cache. You shouldn't store anything important there.

    If you need high performance or high availability there are 3rd party tools, products, and services available.

    redis

    Redis can do the same jobs as memcached can, and can do them better.

    Redis can act as a cache as well. It can store key/value pairs too. In redis they can even be up to 512MB.

    You can turn off persistence and it will happily lose your data on restart too. If you want your cache to survive restarts it lets you do that as well. In fact, that's the default.

    It's super fast too, often limited by network or memory bandwidth.

    If one instance of redis/memcached isn't enough performance for your workload, redis is the clear choice. Redis includes cluster support and comes with high availability tools (redis-sentinel) right "in the box". Over the past few years redis has also emerged as the clear leader in 3rd party tooling. Companies like Redis Labs, Amazon, and others offer many useful redis tools and services. The ecosystem around redis is much larger. The number of large scale deployments is now likely greater than for memcached.

    The Redis Superset

    Redis is more than a cache. It is an in-memory data structure server. Below you will find a quick overview of things Redis can do beyond being a simple key/value cache like memcached. Most of redis' features are things memcached cannot do.

    Documentation

    Read the rest at the sourceFrom Stack Overflow: asked by Sagiv Ofek, answered by Carl Zulauf (CC BY-SA 4.0)

  2. Redis strings vs Redis hashes to represent JSON: efficiency?

    This article can provide a lot of insight here: Memory Optimization

    There are many ways to store an array of Objects in Redis (spoiler: I like option 1 for most use cases):

    1. Store the entire object as JSON-encoded string in a single key and keep track of all Objects using a set (or list, if more appropriate). For example:

      INCR id:users
      SET user:{id} '{"name":"Fred","age":25}'
      SADD users {id}
      

      Generally speaking, this is probably the best method in most cases. If there are a lot of fields in the Object, your Objects are not nested with other Objects, and you tend to only access a small subset of fields at a time, it might be better to go with option 2.

      Advantages: considered a "good practice." Each Object is a full-blown Redis key. JSON parsing is fast, especially when you need to access many fields for this Object at once. Disadvantages: slower when you only need to access a single field.

    2. Store each Object's properties in a Redis hash.

      INCR id:users
      HMSET user:{id} name "Fred" age 25
      SADD users {id}
      

      Advantages: considered a "good practice." Each Object is a full-blown Redis key. No need to parse JSON strings. Disadvantages: possibly slower when you need to access all/most of the fields in an Object. Also, nested Objects (Objects within Objects) cannot be easily stored.

    3. Store each Object as a JSON string in a Redis hash.

      INCR id:users
      HMSET users {id} '{"name":"Fred","age":25}'
      

      This allows you to consolidate a bit and only use two keys instead of lots of keys. The obvious disadvantage is that you can't set the TTL (and other stuff) on each user Object, since it is merely a field in the Redis hash and not a full-blown Redis key.

      Advantages: JSON parsing is fast, especially when you need to access many fields for this Object at once. Less "polluting" of the main key namespace. Disadvantages: About same memory usage as #1 when you have a lot of Objects. Slower than #2 when you only need to access a single field. Probably not considered a "good practice."

    4. Store each property of each Object in a dedicated key.

      INCR id:users
      SET user:{id}:name "Fred"
      SET user:{id}:age 25
      SADD users {id}
      

      According to the article above, this option is almost never preferred (unless the property of the Object needs to have specific TTL or something).

      Advantages: Object properties are full-blown Redis keys, which might not be overkill for your app. Disadvantages: slow, uses more memory, and not considered "best practice." Lots of polluting of the main key namespace.

    Overall Summary

    Option 4 is generally not preferred. Options 1 and 2 are very similar, and they are both pretty common. I prefer option 1 (generally speaking) because it allows you to store more complicated Objects (with multiple layers of nesting, etc.) Option 3 is used when you really care about not polluting the main key namespace (i.e. you don't want there to be a lot of keys in your database and you don't care about things like TTL, key sharding, or whatever).

    From Stack Overflow: asked by Henley Wing Chiu, answered by BMiner (CC BY-SA 4.0)

  3. What are the underlying data structures used for Redis?

    I'll try to answer your question, but I'll start with something that may look strange at first: if you are not interested in Redis internals you should not care about how data types are implemented internally. This is for a simple reason: for every Redis operation you'll find the time complexity in the documentation and, if you have the set of operations and the time complexity, the only other thing you need is some clue about memory usage (and because we do many optimizations that may vary depending on data, the best way to get these latter figures are doing a few trivial real world tests).

    But since you asked, here is the underlying implementation of every Redis data type.

    • Strings are implemented using a C dynamic string library so that we don't pay (asymptotically speaking) for allocations in append operations. This way we have O(N) appends, for instance, instead of having quadratic behavior.
    • Lists are implemented with linked lists.
    • Sets and Hashes are implemented with hash tables.
    • Sorted sets are implemented with skip lists (a peculiar type of balanced trees).

    But when lists, sets, and sorted sets are small in number of items and size of the largest values, a different, much more compact encoding is used. This encoding differs for different types, but has the feature that it is a compact blob of data that often forces an O(N) scan for every operation. Since we use this format only for small objects this is not an issue; scanning a small O(N) blob is cache oblivious so practically speaking it is very fast, and when there are too many elements the encoding is automatically switched to the native encoding (linked list, hash, and so forth).

    But your question was not really just about internals, your point was What type to use to accomplish what?.

    Strings

    This is the base type of all the types. It's one of the four types but is also the base type of the complex types, because a List is a list of strings, a Set is a set of strings, and so forth.

    A Redis string is a good idea in all the obvious scenarios where you want to store an HTML page, but also when you want to avoid converting your already encoded data. So for instance, if you have JSON or MessagePack you may just store objects as strings. In Redis 2.6 you can even manipulate this kind of object server side using Lua scripts.

    Another interesting usage of strings is bitmaps, and in general random access arrays of bytes, since Redis exports commands to access random ranges of bytes, or even single bits. For instance check this good blog post: Fast Easy real time metrics using Redis.

    Lists

    Lists are good when you are likely to touch only the extremes of the list: near tail, or near head. Lists are not very good to paginate stuff, because random access is slow, O(N). So good uses of lists are plain queues and stacks, or processing items in a loop using RPOPLPUSH with same source and destination to "rotate" a ring of items.

    Lists are also good when we want just to create a capped collection of N items where usually we access just the top or bottom items, or when N is small.

    Sets

    Sets are an unordered data collection, so they are good every time you have a collection of items and it is very important to check for existence or size of the collection in a very fast way. Another cool thing about sets is support for peeking or popping random elements (SRANDMEMBER and SPOP commands).

    Sets are also good to represent relations, e.g., "What are friends of user X?" and so forth. But other good data structures for this kind of stuff are sorted sets as we'll see.

    Sets support complex operations like intersections, unions, and so forth, so this is a good data structure for using Redis in a "computational" manner, when you have data and you want to perform transformations on that data to obtain some output.

    Small sets are encoded in a very efficient way.

    Hashes

    Read the rest at the sourceFrom Stack Overflow: asked by Homer6, answered by antirez (CC BY-SA 3.0)

  4. Is Redis just a cache?

    No, Redis is much more than a cache.

    Like a cache, Redis stores key-value pairs. But unlike a cache, Redis lets you operate on the values. There are 5 data types in Redis - Strings, Sets, Hashs, Lists and Sorted Sets. Each data type exposes various operations.

    The best way to understand Redis is to model an application without thinking about how you are going to store it in a database.

    Lets say we want to build StackOverflow.com. To keep it simple, we need Questions, Answers, Tags and Users.

    Modeling Questions, Users and Answers

    Each object can be modeled as a Map. For example, a Question is a map with fields {id, title, date_asked, votes, asked_by, status}. Similarly, an Answer is a map with fields {id, question_id, answer_text, answered_by, votes, status}. Similarly, we can model a user object.

    Each of these objects can be directly stored in Redis as a Hash. To generate unique ids, you can use the atomic increment command. Something like this:

    $ HINCRBY unique_ids question 1
    (integer) 1
    $ HMSET question:1 title "Is Redis just a cache?" asked_by 12 votes 0
    OK
    $ HINCRBY unique_ids answer 1
    (integer) 1
    $ HMSET answer:1 question_id 1 answer_text "No, its a lot more" answered_by 15 votes 1
    OK
    

    Handling Up Votes

    Now, every time someone upvotes a question or an answer, you just need to do this:

    $ HINCRBY question:1 votes 1
    (integer) 1
    $ HINCRBY question:1 votes 1
    (integer) 2
    

    List of Questions for Homepage

    Next, we want to store the most recent questions to display on the home page. If you were writing a .NET or a Java program, you would store the questions in a List. Turns out, that is the best way to store this in Redis as well.

    Every time someone asks a question, we add its id to the list:

    $ lpush questions question:1
    (integer) 1
    $ lpush questions question:2
    (integer) 1
    

    Now, when you want to render your homepage, you ask Redis for the most recent 25 questions:

    $ lrange questions 0 24
    1) "question:100"
    2) "question:99"
    3) "question:98"
    4) "question:97"
    5) "question:96"
    ...
    25) "question:76"
    

    Now that you have the ids, retrieve items from Redis using pipelining and show them to the user.

    Questions by Tags, Sorted by Votes

    Next, we want to retrieve questions for each tag. But SO allows you to see top voted questions, new questions or unanswered questions under each tag.

    To model this, we use Redis' Sorted Set feature. A Sorted Set allows you to associate a score with each element. You can then retrieve elements based on their scores.

    Lets go ahead and do this for the Redis tag:

    $ zadd questions_by_votes_tagged:redis 2 question:1 
    (integer) 1
    $ zadd questions_by_votes_tagged:redis 10 question:2 
    (integer) 1
    $ zadd questions_by_votes_tagged:redis 5 question:613 
    (integer) 1
    $ zrange questions_by_votes_tagged:redis 0 5 
    1) "question:1"
    2) "question:613"
    3) "question:2"
    $ zrevrange questions_by_votes_tagged:redis 0 5 
    1) "question:2"
    2) "question:613"
    3) "question:1"
    

    What did we do over here? We added questions to a sorted set, and associated a score (number of votes) to each question. Each time a question gets upvoted, we will increment its score. And when a user clicks "Questions tagged Redis, sorted by votes", we just do a zrevrange and get back the top questions.

    Realtime Questions without refreshing page

    And finally, a bonus feature. If you keep the questions page opened, SO will notify you when a new question is added. How can Redis help over here?

    Redis has a pub-sub model. You can create channels, for example "channel_questions_tagged_redis". You then subscribe users to a particular channel. When a new question is added, you would publish a message to that channel. All users would then get the message. You will have to use a web technology like web sockets or comet to actually deliver the message to the browser, but Redis helps you with all the plumbing on the server side.

    Persistence, Reliability etc.

    Read the rest at the sourceFrom Stack Overflow: asked by Darkwing, answered by Sripathi Krishnan (CC BY-SA 4.0)

  5. What's the Point of Multiple Redis Databases?

    In principle, Redis databases on the same instance are no different than schemas in RDBMS database instances.

    So, with all of that said, why/when would I ever want to use multiple Redis databases instead of just spinning up an extra instance of Redis for each extra database I want?

    There's one clear advantage of using redis databases in the same redis instance, and that's management. If you spin up a separate instance for each application, and let's say you've got 3 apps, that's 3 separate redis instances, each of which will likely need a slave for HA in production, so that's 6 total instances. From a management standpoint, this gets messy real quick because you need to monitor all of them, do upgrades/patches, etc. If you don't plan on overloading redis with high I/O, a single instance with a slave is simpler and easier to manage provided it meets your SLA.

    From Stack Overflow: asked by Eli, answered by raffian (CC BY-SA 4.0)

  6. Why do we need message brokers like RabbitMQ over a database like PostgreSQL?

    Rabbit's queues reside in memory and will therefore be much faster than implementing this in a database. A (good) dedicated message queue should also provide essential queuing related features such as throttling/flow control, and the ability to choose different routing algorithms, to name a couple (RabbitMQ provides these and more). Depending on the size of your project, you may also want the message passing component separate from your database, so that if one component experiences heavy load, it need not hinder the other's operation.

    As for the problems you mentioned:

    • polling keeping the database busy and low performing: Using RabbitMQ, producers can push updates to consumers which is far more performant than polling. Data is simply sent to the consumer when it needs to be, eliminating the need for wasteful checks.

    • locking of the table -> again low performing: There is no table to lock :P

    • millions of rows of task -> again polling is low performing: As mentioned above, RabbitMQ will operate faster as it resides RAM, and provides flow control. If needed, it can also use the disk to temporarily store messages if it runs out of RAM. After 2.0, Rabbit has significantly improved on its RAM usage. Clustering options are also available.

    In regards to AMQP, I would say a really cool feature is the "exchange", and the ability for it to route to other exchanges. This gives you more flexibility and enables you to create a wide array of elaborate routing typologies which can come in very handy when scaling. For a good example, see:


    (source: spring.io)

    and: https://web.archive.org/web/20130730091944/http://blog.springsource.org/2011/04/01/routing-topologies-for-performance-and-scalability-with-rabbitmq/

    Finally, in regards to Redis, yes, it can be used as a message broker, and can do well. However, RabbitMQ has more message queuing features than Redis, as RabbitMQ was built from the ground up to be a full-featured enterprise-level dedicated message queue. Redis on the other hand was primarily created to be an in-memory key-value store (though it does much more than that now; its even referred to as a Swiss army knife). Still, I've read/heard many people achieving good results with Redis for smaller sized projects, but haven't heard much about it in larger applications.

    Here is an example of Redis being used in a long-polling chat implementation: https://web.archive.org/web/20180523045840/http://eflorenzano.com/blog/2011/02/16/technology-behind-convore/

    From Stack Overflow: asked by Yugal Jindle, answered by Jaigus (CC BY-SA 4.0)

  7. Does Redis persist data?

    I suggest you read about this on http://redis.io/topics/persistence . Basically you lose the guaranteed persistence when you increase performance by using only in-memory storing. Imagine a scenario where you INSERT into memory, but before it gets persisted to disk lose power. There will be data loss.

    Redis supports so-called "snapshots". This means that it will do a complete copy of whats in memory at some points in time (e.g. every full hour). When you lose power between two snapshots, you will lose the data from the time between the last snapshot and the crash (doesn't have to be a power outage..). Redis trades data safety versus performance, like most NoSQL-DBs do.

    Most NoSQL-databases follow a concept of replication among multiple nodes to minimize this risk. Redis is considered more a speedy cache instead of a database that guarantees data consistency. Therefore its use cases typically differ from those of real databases: You can, for example, store sessions, performance counters or whatever in it with unmatched performance and no real loss in case of a crash. But processing orders/purchase histories and so on is considered a job for traditional databases.

    From Stack Overflow: asked by Zuriar, answered by Manuel Arwed Schmidt (CC BY-SA 3.0)

  8. Redis cache vs. using memory directly

    Redis is a remote data structure server. It is certainly slower than just storing the data in local memory (since it involves socket roundtrips to fetch/store the data). However, it also brings some interesting properties:

    • Redis can be accessed by all the processes of your applications, possibly running on several nodes (something local memory cannot achieve).

    • Redis memory storage is quite efficient, and done in a separate process. If the application runs on a platform whose memory is garbage collected (node.js, java, etc ...), it allows handling a much bigger memory cache/store. In practice, very large heaps do not perform well with garbage collected languages.

    • Redis can persist the data on disk if needed.

    • Redis is a bit more than a simple cache: it provides various data structures, various item eviction policies, blocking queues, pub/sub, atomicity, Lua scripting, etc ...

    • Redis can replicate its activity with a master/slave mechanism in order to implement high-availability.

    Basically, if you need your application to scale on several nodes sharing the same data, then something like Redis (or any other remote key/value store) will be required.

    From Stack Overflow: asked by hh54188, answered by Didier Spezia (CC BY-SA 3.0)

  9. When to use a key/value store such as Redis instead/along side of a SQL database?

    I can't seem to figure out when it's time to use it in an application.

    I would recommend you to read this tutorial which contains also use cases. Since Redis is rather memory oriented it's really good for frequently updated real-time data, such as session store, state database, statistics, caching and its advanced data structures offers versatility to many other scenarios.

    Redis, however, isn't NoSQL replacement for classic relational databases since it doesn't support many standard features of RDBMS world such as querying of your data which might slow it down. Replacements are rather document databases like MongoDB or CouchDB and Redis is great at supplementing specific functionality where speed and support for advanced data structures comes handy.

    From Stack Overflow: asked by Chris Abrams, answered by yojimbo87 (CC BY-SA 4.0)

  10. Is memcached a dinosaur in comparison to Redis?

    Depends on what you need, in general I think that:

    • You should not care too much about performances. Redis is faster per core with small values, but memcached is able to use multiple cores with a single executable and TCP port without help from the client. Also memcached is faster with big values in the order of 100k. Redis recently improved a lot about big values (unstable branch) but still memcached is faster in this use case. The point here is: nor one or the other will likely going to be your bottleneck for the query-per-second they can deliver.
    • You should care about memory usage. For simple key-value pairs memcached is more memory efficient. If you use Redis hashes, Redis is more memory efficient. Depends on the use case.
    • You should care about persistence and replication, two features only available in Redis. Even if your goal is to build a cache it helps that after an upgrade or a reboot your data are still there.
    • You should care about the kind of operations you need. In Redis there are a lot of complex operations, even just considering the caching use case, you often can do a lot more in a single operation, without requiring data to be processed client side (a lot of I/O is sometimes needed). This operations are often as fast as plain GET and SET. So if you don't need just GET/SET but more complex things Redis can help a lot (think at timeline caching).

    Without an use case is hard to pick the right now, but I think that for a lot of things Redis makes sense since even when you don't want to use it as a DB, being a lot more capable you can solve more problems, not just caching but even messaging, ranking, and so forth.

    P.s. of course I could be biased since I'm the lead developer of the Redis project.

    From Stack Overflow: asked by Industrial, answered by antirez (CC BY-SA 3.0)

  11. How do I delete everything in Redis?

    With redis-cli:

    • FLUSHDB – Deletes all keys from the connection's current database.
    • FLUSHALL – Deletes all keys from all databases on current host.

    For example, in your shell:

    redis-cli flushall
    

    From Stack Overflow: asked by TIMEX, answered by Javier (CC BY-SA 4.0)

  12. How to atomically delete keys matching a pattern using Redis?

    Starting with redis 2.6.0, you can run lua scripts, which execute atomically. I have never written one, but I think it would look something like this

    EVAL "return redis.call('del', unpack(redis.call('keys', ARGV[1])))" 0 prefix:[YOUR_PREFIX e.g delete_me_*]
    

    Warning: As the Redis document says, because of performance maters, keys command should not use for regular operations in production, this command is intended for debugging and special operations. read more

    See the EVAL documentation.

    From Stack Overflow: asked by Alexander Gladysh, answered by mcdizzle (CC BY-SA 4.0)

  13. Redis command to get all available keys?

    Try to look at KEYS command. KEYS * will list all keys stored in redis.

    EDIT: please note the warning at the top of KEYS documentation page:

    Time complexity: O(N) with N being the number of keys in the database, under the assumption that the key names in the database and the given pattern have limited length.

    UPDATE (V2.8 or greater): SCAN is a superior alternative to KEYS, in the sense that it does not block the server nor does it consume significant resources. Prefer using it.

    From Stack Overflow: asked by Lalith, answered by yojimbo87 (CC BY-SA 3.0)

  14. MISCONF Redis is configured to save RDB snapshots

    Restart your redis server.

    • macOS (brew): brew services restart redis.
    • Linux: sudo service redis restart / sudo systemctl restart redis
    • Windows: Windows + R -> Type services.msc, Enter -> Search for Redis then click on restart.

    I had this issue after upgrading redis with Brew (brew upgrade).

    Once I restarted my laptop, it immediately worked.

    From Stack Overflow: asked by Salvador Dali, answered by MandarineBleue (CC BY-SA 4.0)

  15. How can I stop redis-server?

    Either connect to node instance and use shutdown command or if you are on ubuntu you can try to restart redis server through init.d:

    /etc/init.d/redis-server restart
    

    or stop/start it:

    /etc/init.d/redis-server stop
    /etc/init.d/redis-server start
    

    On Mac

    redis-cli shutdown
    

    From Stack Overflow: asked by Qcom, answered by yojimbo87 (CC BY-SA 3.0)

  16. WRONGTYPE Operation against a key holding the wrong kind of value php

    Redis supports many data types. You need to know what type of value that a key maps to. For each data type, the command to retrieve it is different.

    Use the TYPE key command to check the type of value a key is mapping to.

    Here are the commands to retrieve key value(s) for some of the common data types:

    Data Type Command Function
    string GET key Get value
    hash HKEYS key List fields
    HGET key field Get field value
    HMGET key field field… Get multiple field values
    HGETALL key Get all field values
    list LLEN key Get length
    LINDEX key index Get value at index
    LRANGE key start stop Get values in range
    set SMEMBERS key List all set members
    sorted set ZSCORE key member Get score of member
    stream XRANGE key start stop Get stream entries in range

    From Stack Overflow: asked by Trushar Narodia, answered by Phoebe Li (CC BY-SA 4.0)

  17. Check Redis server version

    $ redis-server --version

    gives you the version.

    From Stack Overflow: asked by Aviram Netanel, answered by Aviram Netanel (CC BY-SA 4.0)

  18. Redis key naming conventions?

    What are the normal naming convention for keys in redis? I've seen values separated by : but I'm not sure what the normal convention is, or why.

    Yes, colon sign : is a convention when naming keys. In this tutorial on redis website is stated: Try to stick with a schema. For instance "object-type:id:field" can be a nice idea, like in "user:1000:password". I like to use dots for multi-words fields, like in "comment:1234:reply.to".

    Are you able to query for just the beginning of the key to return all users?

    If you mean something like directly querying for all keys which starts with user: there is a keys command for that. This command should be however used only for debugging purpose since it's O(N) because it's searching through all keys stored in database.

    More appropriate solution for this problem is to create dedicated key, let's name it users, which will store all the users keys, for example, in list or set data structure.

    From Stack Overflow: asked by fancy, answered by yojimbo87 (CC BY-SA 4.0)

  19. How to List All Redis Databases?

    There is no command to do it (like you would do it with MySQL for instance). The number of Redis databases is fixed, and set in the configuration file. By default, you have 16 databases. Each database is identified by a number (not a name).

    You can use the following command to know the number of databases:

    CONFIG GET databases
    1) "databases"
    2) "16"
    

    You can use the following command to list the databases for which some keys are defined:

    INFO keyspace
    # Keyspace
    db0:keys=10,expires=0
    db1:keys=1,expires=0
    db3:keys=1,expires=0
    

    Please note that you are supposed to use the "redis-cli" client to run these commands, not telnet. If you want to use telnet, then you need to run these commands formatted using the Redis protocol.

    For instance:

    *2
    $4
    INFO
    $8
    keyspace
    $79
    # Keyspace
    db0:keys=10,expires=0
    db1:keys=1,expires=0
    db3:keys=1,expires=0
    

    You can find the description of the Redis protocol here: http://redis.io/topics/protocol

    From Stack Overflow: asked by Kevin Meredith, answered by Didier Spezia (CC BY-SA 3.0)

  20. How to connect to remote Redis server?
    redis-cli -h XXX.XXX.XXX.XXX -p YYYY
    

    xxx.xxx.xxx.xxx is the IP address and yyyy is the port

    EXAMPLE from my dev environment

    redis-cli -h 10.144.62.3 -p 30000
    

    REDIS CLI COMMANDS

    Host, port, password and database By default redis-cli connects to the server at 127.0.0.1 port 6379. As you can guess, you can easily change this using command line options. To specify a different host name or an IP address, use -h. In order to set a different port, use -p.

    redis-cli -h redis15.localnet.org -p 6390 ping

    From Stack Overflow: asked by duckertito, answered by gh9 (CC BY-SA 4.0)

  21. Redis is single-threaded, then how does it do concurrent I/O?

    Well it depends on how you define concurrency.

    In server-side software, concurrency and parallelism are often considered as different concepts. In a server, supporting concurrent I/Os means the server is able to serve several clients by executing several flows corresponding to those clients with only one computation unit. In this context, parallelism would mean the server is able to perform several things at the same time (with multiple computation units), which is different.

    For instance a bartender is able to look after several customers while he can only prepare one beverage at a time. So he can provide concurrency without parallelism.

    This question has been debated here: What is the difference between concurrency and parallelism?

    See also this presentation from Rob Pike.

    A single-threaded program can definitely provide concurrency at the I/O level by using an I/O (de)multiplexing mechanism and an event loop (which is what Redis does).

    Parallelism has a cost: with the multiple sockets/multiple cores you can find on modern hardware, synchronization between threads is extremely expensive. On the other hand, the bottleneck of an efficient storage engine like Redis is very often the network, well before the CPU. Isolated event loops (which require no synchronization) are therefore seen as a good design to build efficient, scalable, servers.

    The fact that Redis operations are atomic is simply a consequence of the single-threaded event loop. The interesting point is atomicity is provided at no extra cost (it does not require synchronization). It can be exploited by the user to implement optimistic locking and other patterns without paying for the synchronization overhead.

    From Stack Overflow: asked by Przemysław Pietrzkiewicz, answered by Didier Spezia (CC BY-SA 4.0)

  22. Print number of keys in Redis

    You can issue the INFO command, which returns information and statistics about the server. See here for an example output.

    As mentioned in the comments by mVChr, you can use info keyspace directly on the redis-cli.

    redis> INFO
    # Server
    redis_version:6.0.6
    redis_git_sha1:00000000
    redis_git_dirty:0
    redis_build_id:b63575307aaffe0a
    redis_mode:standalone
    os:Linux 5.4.0-1017-aws x86_64
    arch_bits:64
    multiplexing_api:epoll
    atomicvar_api:atomic-builtin
    gcc_version:9.3.0
    process_id:2854672
    run_id:90a5246f10e0aeb6b02cc2765b485d841ffc924e
    tcp_port:6379
    uptime_in_seconds:2593097
    uptime_in_days:30
    hz:10
    configured_hz:10
    lru_clock:4030200
    executable:/usr/local/bin/redis-server
    

    From Stack Overflow: asked by andy boot, answered by hymloth (CC BY-SA 4.0)

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.