Entradas


Redis Streams, Consumers, and Blocking Operations

Redis introduced the streams that mimic the log data structure with version 5.0. Stream is an append-only data structure with a richer set of operations than in a log file. It is one of the most complex data types in Redis since it implements additional blocking operations which allow the clients to wait for the new stream data. This is somewhat similar to the behavior of Redis Pub/Sub or blocking lists but fundamental differences are there when it comes to how the consumers consume the Redis stream data.

As shown in the previous illustration, several advantages over Redis Pub/Sub and blocking lists can be seen. Every new data item is delivered to every consumer. Unlike in the lists removing the list item whenever called to BLPOP or BRPOP, the stream items remain as it is in the stream. XREAD command operates as a blocking and non-blocking candidate on the Redis streams.

The XREAD command can fetch the entries from multiple streams simultaneously while the returned entries have an ID bigger than the last received ID for a given consumer. It can operate in both the blocking and non-blocking manner. In the non-blocking nature, the command behaves very similar to the XRANGE command but with some additional features listed in the following:

  • It can fetch the entries starting from the most recent entry that has the greatest ID than any other item in the stream.
  • It can read from multiple streams at the same time.

This command has a linear time complexity when the N number of elements are stored in the stream. Hence, with a fixed return count, the time complexity is constant.

The XREAD command follows the following syntax:

Syntax:

XREAD [COUNT number_of_returned_elements] [BLOCK blocking_time_in_milliseconds] STREAMS key [key …] id [id…]

COUNT <number_of_returned_elements>: The number of elements to be returned by the command. It limits the returned rows to a specified number.

BLOCK <blocking_time_in_milliseconds>: The maximum time to wait for a new item to appear in the stream.

The previous two options are optional to the command.

STREAMS <key>: The key of the stream. This is a mandatory option and must be the last option in the command since it accepts the variable length of keys and entry IDs.

<id>: The ID of the stream entry.

Multiple keys can be specified since the command allows you to read from more than one stream. At the same time, multiple IDs can be provided.

This command returns an array reply. Each array item consists of two elements as shown in the following format:

Example 1: Inspect the Weather Data for Two Locations with Non-Blocking XREAD

Let’s assume that we got two streams containing the weather data for LA and NYC. In our weather data publication site, we need to consume from both streams and fetch the latest weather data for these two locations. The XREAD command is the ideal candidate to use in this scenario with its non-blocking variant.

It’s time to create two streams named weather:nyc and weather:la and populate a couple of entries with some field-value pairs as shown in the following:

xadd weather:nyc * wind 45 humidity 78 temp 12

xadd weather:la * wind 12 humidity 45 temp 22

Both the streams weather:nyc and weather:lc are created successfully and the returned entry IDs are 1658114094434-0 and 1658114110474-0, respectively.

Let’s use the XREAD command to read from both streams at the same time in a non-blocking manner.

xread streams weather:nyc weather:la 0 0

As expected, the output contains the entries from both streams with the ID sequence starting from 0. It is acceptable to specify the incomplete IDs as previously illustrated where both the IDs are 0 which is the millisecond timestamp without the sequence number part. Hence, the previous command can be written as in the following:

xread streams weather:nyc weather:la 00 00

Let’s add a couple of entries to both streams now.

xadd weather:nyc * wind 10 humidity 60 temp 10

xadd weather:la * wind 18 humidity 80 temp 5

Since we already have the latest entry IDs for both streams from the previous commands, let’s call the XREAD command again to fetch all the entries with bigger IDs than the ones that we already queried.

xread streams weather:nyc weather:la 16581140944340 16581141104740

As you could see, the specified IDs are from the previous query. Now, the command call returns all the entries which have greater IDs than the specified ones.

As you can see, the newly added entries are returned from the previous command. Next, what you can do is take the entry IDs returned from the previous command and call the XREAD with those IDs until the returned array is empty.

Example 2: Get the Latest Pizza Promos with Blocking XREAD

There is another variant of the XREAD command which can be used to wait until the publishers publish a new data to the stream without terminating immediately as a non-blocking call. Let’s assume a scenario where the pizza guys want to push the notifications to all the customers regarding the latest promos available. There might be no promos on certain days. Hence, the customers should wait until the new promos are available. It can be achieved with the XREAD command with the block option in place.

Let’s assume that the pizza company is publishing the promo details to a stream called pizzapromos:daily. Hence, we can use the XREAD command to wait until a new promo item is added to the stream.

xread block 50000 streams pizzapromosnew:daily $

In this case, we specify the entry ID as $ which is interpreted as the top entry ID. Hence, the command will query only the new entries added to the stream and not the historical entries.

Since we have not added new entries to the stream, it will timeout after 50000 milliseconds with a nil return as shown in the following:

Now, let’s add an entry to the stream using the XADD while another consumer is waiting for the data with the XREAD command as shown in the following:

As expected, the added entry is consumed by the consumer immediately. From the next call, we need to make sure that we pass the ID that is returned from this command and not the $. If not, we will miss the entries added in between.

If multiple clients are waiting for the same stream, the newly added data is pushed to all of them immediately. The XREAD command is a very useful and recommended command to use in blocking the nature applications.

To summarize, the XREAD command is one of the widely used commands that operate on the Redis streams. It can operate in both blocking and non-blocking ways. As discussed, the non-blocking variant is very much similar to the XRANGE command with a couple of differences. In addition, this command can be used with the block option to wait until the publishers publish a new data to the stream. Overall, the XREAD command is specialized in consuming the data from multiple streams simultaneously. It is a helpful feature that the modern-day applications are looking for.



Source link


Redis Sorted Set Score and Rank

Redis Sorted Sets are the ordered variant of the typical set data structure. Each sorted set element is associated with two special properties: rank and score. The score value is used to order the sorted set elements in ascending order. Furthermore, the scores can be repeated while the members must be unique for a given set. Since the sorted set elements are ordered, the add, update, and remove operations are faster. In addition, this data structure allows querying the elements in a range by score or rank value with great performance.

As shown in the previous illustration, most of the major commands that operate on Redis sets have the time complexity of O(log(N)) which is faster.

The ZCOUNT Command

The ZCOUNT command is used to query a range of set elements between the specified scores. The returned elements are sorted from the lowest to the highest score. Whenever the multiple elements hold the same scores, those are ordered by lexicographical order. This command also has the O(log(N)) time complexity because it uses the rank property when querying a range of elements. Hence, no linear relationship to the number of elements when measuring the execution time.

The following is the syntax of the ZCOUNT command:

Syntax:

ZCOUNT set_key minimum_score maximum_score

set_key: The key of the Redis sorted set.

minimum_score: The lowest score value of the range specified.

maximum_score: The highest score value of the range specified.

The min and max ends of the range can be specified in different ways. Whenever you have no clue about the lowest and highest possible scores in the sorted set, the -inf and +inf can be used. It ideally fetches all the elements in the sorted set.

In addition, the specified minimum and maximum values are inclusive of the range. If you want any of these values to be exclusive, the “(“ character can be used as in the ZRANGEBYSCORE command.

This command returns an integer value which is the number of elements in the specified range.

Use Case – Count the Players with a Gold Count Between a Given Range

Redis sorted set data structure is an ideal candidate for storing the leaderboard data. Let’s assume a scenario where an online game offers an amount of gold for its players when the missions are completed. Based on each player’s gold amount, a leaderboard needs to be implemented. We can easily use the Redis sorted sets to implement such leaderboard. The gold amount can be mapped as the score of each member.

Let’s create a sorted set GameLeaderBoard and add some players with gold amounts as shown in the following. The ZADD command is used to create and add players to the sorted set stored at the key GameLeaderBoard:

zadd GameLeaderBoard 1000 «Jack» 450 «Rexy» 3000 «John» 1600 «Mary» 450 «Rakesh»

Let’s use the ZRANGEBYSCORE command to check whether the members are added and sorted properly.

zrangebyscore GameLeaderBoard -inf +inf

As expected, the members are stored and sorted by scores. Since “Rexy” and “Rakesh” got the same scores, they are ordered lexicographically with “Rakesh” being the top member of the returned list.

Let’s count the number of elements in the sorted set using the ZCOUNT command:

zcount GameLeaderBoard -inf +inf

Since we got five set members, the returned value is 5 because the range is from the -infinity to +infinity which covers the whole set.

Let’s specify a range starting from 1000 to 3000.

zcount GameLeaderBoard 1000 3000

Let’s first inspect our set with the ZRANGEBYSCORE command as shown in the following:

zrangebyscore GameLeaderBoard -inf +inf withscores

There are three members within the range of 1000 to 3000. Since the 1000 and 3000 are inclusive by default, the previous ZCOUNT command should return 3.

Let’s use the “(“ character to exclude the 1000 and 3000 scores with the same example shown in the previous example:

zcount GameLeaderBoard (1000 (3000

Since the 1000 and 3000 scores are excluded, the only left member is “Mary” with a 1600 score. Hence, the returned count is 1.

Whenever you need to count the members between a range of scores, it is recommended to use the ZCOUNT command which is immensely faster.

Conclusion

In summary, the ZCOUNT command is used to count the number of elements in a given range of score values. It has an O(log(N)) time complexity. As discussed, it can be used with minimum and maximum values to define a range of scores as in the ZRANGEBYSCORE command. The min and max values are inclusive by default. As shown previously, the “(“ character can be used to exclude the score values. Overall, the ZCOUNT command is simple to use and operates with great performance.



Source link


Set Intersection

A set is a collection of elements such as numbers, letters, or real-world objects. Each of these members is distinct or unique for a given set. They alone can’t do many things. Hence, there are requirements to make the relationships among two or more sets to generate meaningful insights. As we all know, numbers have fundamental operations such as addition, subtraction, multiplication, and division. In the same way, sets come with four main operations: union, intersection, difference, and complement.

In this guide, we will focus on the Redis command which operates on the sorted sets to compute the intersection of two or more of them. Hence, this section explains the set intersection operation. As the name suggests, the set intersection operation computes the set of common elements belonging to a given list of sets.

The given VENN diagram is a representation of two sets with an intersection. There are three members who visit both sites A and B. If we take the site A and B visitors as set A and set B, the mentioned three members are called the set intersection of set A and set B.

Redis supports the sorted set data structure out of the box with general-purpose operations to add, remove, and query the elements. Furthermore, Redis supports more advanced operations on sorted sets like set intersections. The following section describes the ZINTERSTORE command which helps in computing the set intersection in Redis:

Redis ZINTERSTORE Command

The ZINTERSTORE command operates on two or more sorted sets to compute the intersection of those. This command creates a new sorted set from the intersection of the specified sets.

Since, the Redis sorted set elements are associated with score values, each of these scores is summed per common element and stored in the destination set as shown in the following illustration:

Syntax:

The following is the basic syntax of the ZINTERSTORE command:

ZINTERSTORE destination_set number_of_sets set_key [set_key …] [WEIGHTS weight [weight …]] [AGGREGATE SUM | MIN | MAX]

destination_set: The key of the sorted set that holds the intersection of the specified sorted sets.

number_of_sets: The number of sorted sets that the set intersection is computed against.

set_key: The key or unique identifier of the sorted set.

WEIGHTS: The multiplication creador for each element’s score in the source sets.

AGGREGATE: This option specifies a way to aggregate the resulting scores per element in the intersection.

By default, it takes the SUM of the scores per element among the given source sets. It is possible to specify the minimum or maximum scores per element across the source sets that it belongs to.

Both the WEIGHTS and AGGREGATE arguments are optional to the ZINTERSTORE command.

The ZINTERSTORE command returns an integer value which is the number of members in the destination sorted set at destination_set.

Use Case – Inspect the Common Visitors Across Multiple Websites with Their Visitor Counts

Let’s assume a scenario where we got two websites A and B. To get an overall picture of the site visitors, we need to query the users who are visiting both A and B sites. Furthermore, we have a requirement to count the number of visits by each member.

Let’s create two sets, setA and setB, as shown in the following:

zadd setA 600 «John» 150 «Mary» 300 «Nick»

zadd setB 300 «Mary» 100 «Nick» 760 «Doe»

We can use the ZINTERSCORE command to find out the intersection of the setA and setB. Ideally, “Mary” and “Nick” should be the intersection of the previous two sets:

zinterstore commonsitevisitors 2 setA setB

In this example, we used the commonsitevisitors as the key of the destination sorted set. It is mandatory to specify the number of sets that we use to compute the intersection. In this case, it is 2.

The returned value is 2 which means that the two members should be stored in the destination sorted set. Let’s inspect the resulting sorted set commonsitevisitors using the ZRANGEBYSCORE command:

As expected, the “Nick” and “Mary” members are in the resulting sorted set with the summed score values. In this example, the member “Nick” has 300 and 100 scores in setA and setB, respectively. Hence, the intersection of these two sets has summed the relevant score values for “Nick”. The same has happened with the member “Mary”.

Let’s use the multiplication creador 2 and 3 for setA and setB, respectively:

zinterstore commonsitevisitors 2 setA setB weights 2 3

The score of “Nick” is calculated by multiplying 300 and 100 by 2 and 3, respectively and summing the results. Hence, the final score should be 900. The same procedure is followed by the ZINTERSTORE command for the other member as well.

By default, the scores are aggregated by summing them, but the other options are also available. We can use the MIN and MAX arguments that keeps the minimum or maximum score per member in the resulting sorted set.

zinterstore commonsitevisitors 2 setA setB aggregate MAX

As expected, the maximum score value for both members is 300 and it is kept in the destination sorted set.

Conclusion

In summary, the ZINTERSTORE command is used to compute the intersection for the multiple sorted sets provided. It is capable of extracting the intersection and storing it in a new sorted set. As previously mentioned, the scores per member across source sets are summed by default. The minimum and maximum arguments can be passed to the command where the scores are aggregated by the minimum or maximum score in the source sets. At the same time, it is possible to specify a multiplication creador for the scores of each element in the intersection set. Overall, the ZINTERSTORE command is reliable and fruitful in computing the set intersections.

 



Source link


The list is a popular Redis data type that stores a sequence of strings based on the insertion order. One list can hold more than 4 billion elements. The unique fact about the Redis list is it maintains the HEAD and TAIL properties where the elements can be inserted from both sides. Usually, the LPUSH and RPUSH commands are used to insert the elements into a list. Meanwhile, the brand new list is created with the specified key. All the list commands behave the same way where a new list is created when passed with a non-existing key.


In addition, when all the elements are popped from the list, the associated key will be deleted from the Redis key space. Redis list is the ideal candidate for the low latency applications because the insertion and deletion operations have constant time complexity at the HEAD and TAIL. It doesn’t matter if five or thousand elements are in the list. The time for the insertion and deletion takes a constant time near the left and right ends.

There are some practical needs to remove the elements from the tail or head of a given list. The BRPOP and BLPOP commands are introduced from the Redis version 2.0.0 to fulfill the mentioned requirement. The BRPOP command is evaluated in this guide.

The BRPOP Command

The BRPOP is the advanced version of the RPOP command. The RPOP command pops an element from the tail of the list that is stored at a given key. As the name suggests, the BRPOP command is the Blocking version of the RPOP. When the key doesn’t exist, The BRPOP command won’t return with the nil value right away as in the RPOP command. Instead, it waits until a new list is created at that key. Upon the creation of a new list at the mentioned key, the BRPOP command pops the tail element. Also, this command accepts the multiple keys and only pop the elements from the first non-empty key.

Syntax:

The following is the syntax for the BRPOP command:

BRPOP list_key [list_key …] timeout

 
list_key: This is the key of the list.
timeout: This is the timeout value in seconds where the client is blocked until this timeout reaches.

Usually, the BRPOP command returns an array output:

If a non-empty list is specified, the command returns the popped element value and the key of the containing list as in the following format:

 

When no single element is to be popped from any of the lists specified and the timeout has expired, the nil value is returned.

 

Example: Radiodifusión Station Playlist Manipulation with BRPOP

Let’s assume that a radiodifusión station needs to play songs from a daily playlist. The playlist contains the song IDs to play. The songs should be ordered in the insertion order. Each song is picked from the end of the playlist to play.

We can use the Redis list data structure to implement the mentioned playlist and the list operations to manipulate the playlist songs. Let’s create a playlist called MidNightPlaylist and add some song IDs as shown in the following. The LPUSH command is used for that:

lpush MidNightPlaylist song001 song004 song010 song100 song101

 
This would create a list as shown in the following:

head> song101 | song100 | song010 | song004 | song001 <tail

 
Non-Blocking Behavior of the BRPOP Command

Now is the time to start a show. We should pick some songs from the end of the playlist. Hence, song001 should be removed from the playlist and it has to be played by the recorder. We use the BRPOP command to pop the song001 from the playlist and to get the song ID to the client listener.

 
The timeout argument is specified as five seconds. Since the MidNightPlaylist contains elements, the BRPOP command behaves in a non-blocking way. Hence, it pops and returns the tail element to the client.

Blocking Behavior of the BRPOP Command

The previous results can be achieved through the RPOP command as well. Hence, let’s look into the vivo advantage of the BRPOP command with the blocking behavior. Let’s remove all the elements from the MidNightPlaylist key using the RPOP command.

 
This removes all the remaining elements from the list and the MidNightPlaylist key is deleted from the Redis key space as well.

Let’s execute the BRPOP command with 60 seconds timeout and the non-existing key MidNightPlaylist. Now, the command behaves in a blocking manner. It waits for the key to be created and the element to be present in the playlist MidNightPlaylist.


Let’s push an element to the MidNightPlaylist via another terminal window that is connected to the same Redis data store.

lpush MidNightPlaylist song400

 
Upon the creation of the MidNightPlaylist list with the element song400, the client window which executed the BRPOP command pops the element song400 from the playlist and returns the song ID as output instantly.


Pick a Song from Multiple Playlists

There can be multiple playlists created by the radiodifusión station. Hence, we should pick a song from the given playlists at a given time. Let’s assume we got three playlists: MidNightPlaylist1, MidNightPlaylist2, and MidNightPlaylist3. The MidNightPlaylist1 is already empty while the other two playlists are non-empty.

lpush MidNightPlaylist2 song1002 song1005
lpush MidNightPlaylist3 song3000

 
Let’s call the BRPOP command with all the three keys as shown in the following:

brpop MidNightPlaylist1 MidNightPlaylist2 MidNightPlaylist3 10

 
Since the first key MidNightPlaylist1 is empty, it is ignored by the command here. It checks for the first non-empty key from the available key list. Hence, the command locates the MidNightPlaylist2 as the first non-empty key from the order of keys. As expected, the song1002 is removed from the MidNightPlaylist2.


The BRPOP command has constant time complexity near the head and tail when a single key is specified. The time complexity becomes O(N) when multiple keys are specified in the command. Furthermore, this command is very efficient to use in the low latency applications such as a queue, stack, timeline in social media, etc.

Conclusion

To summarize, a Redis list is a collection of string elements stored at a given key while sorted in the insertion order. Several commands are available to operate on the Redis lists with constant time complexity near the head and tail. As stated, The BRPOP command is used to remove the elements from the right side of the Redis list stored at a given key with the support of blocking. The BRPOP command blocks the client connection when no elements are available to remove from the specified lists. As you know, this command accepts multiple keys where an element pops from the first non-empty list where each key is checked in the order in which they are passed to the command.



Source link


Redis Sorted Set Members

Redis sorted sets store unique elements in an ordered manner. Hence, it can be used in low latency applications such as priority queues, real-time leaderboards, secondary indexing, etc. Each of these set elements is assigned a rank and placed in ascending order based on the score value. Several commands are available to add, update, and remove the sorted set members efficiently. The most important thing about sorted sets is that after the addition or removal of a set member, it still manages to maintain the member ranks and order.


The above figure shows the Redis sorted set element removal scenario and how it behaves when multiple members are removed from it. It manages to keep the correct order and index values by placing each member accordingly. In the next section, we will be looking into the sorted set remove operation in a detailed manner.

Removing Members With ZREM Command

The ZREM command is used to remove one or more members from a sorted set stored at a specified key. This command has logarithmic time complexity. If the command is used to remove one element, then the time complexity is proportional to the logarithmic value of the number of elements. If multiple elements have been specified to remove, then it will be O(number_of_elements_to_remove* log(total_number_of_set_elements)).

Syntax

ZREM sorted_set_key member [member …]

 
sorted_set_key: This is the unique identifier where the sorted set is stored at.
member: This is the member supposed to be removed.

The ZREM command will remove the specified members from the sorted set. It will return an integer reply which is the number of removed members. Whenever you specify a non-existing member, it will be skipped. Also, the command will throw an error if the given key doesn’t hold a sorted set.

Example – Manage Customer Order Queue With Redis ZREM

Let’s take a real-world scenario where a restaurant serves its customers based on the first-comers assigned with the highest priority. Upon serving the highest priority customers first, the restaurant should remove each customer entry from the queue. Redis sorted set will be an ideal data structure to implement this scenario in a memory-effective and efficient manner.
Each member of the Redis sorted set looks like the following.


As shown in the above illustration, each time a customer has been served by the restaurant, that member needs to be removed from the sorted set. We can use the ZREM command to achieve that.

Let’s add the four customers shown in the above figure. We will be using the ZADD command to create the sorted set customerqueue and add four members, as shown in the following.

zadd customerqueue 1 customer:10
zadd customerqueue 9 customer:1
zadd customerqueue 7 customer:6
zadd customerqueue 5 customer:2

 

Let’s inspect the sorted set using the ZRANGE command.

zrange customerqueue 0 10 WITHSCORES

 
Output:


As expected, the sorted set customerqueue has been ordered based on the priority value.

Delete a Member from the Sorted Set

The customer:10 who has the highest priority will be served first. Hence, the customer:10 members have to be removed from the sorted set. Let’s use the ZREM command to remove the member.

ZREM customerqueue customer:10

 
Output:


As expected, the return value is 1, which means one entry has been removed. Let’s inspect the customerqueue again.


The member customer:10 has been deleted successfully.

Delete Multiple Members from the Sorted Set

Let’s say both customer:2 and customer:6 have been served from two windows parallelly. Hence, we should delete both the members from the sorted set. We can use the ZREM command to delete both members at merienda.

ZREM customerqueue customer:2 customer:6

 
Output:


As expected, the return value is 2, which indicates two members have been deleted. Let’s inspect the whole sorted set again.


The ZREM command is recommended to use whenever you need to remove elements from a sorted set.

Conclusion

To summarize, the ZREM command is used to remove one or multiple elements from a Redis sorted set stored at a given key. It simply deletes the specified members from the sorted set. Also, the order will be kept in the resulting sorted set. As stated above, it has a logarithmic time complexity which makes the command to be used in real-time applications. Hence, the ZREM command is recommended to use whenever you need to remove elements from a sorted set.



Source link


Redis uses the key-value pair approach to store its data. Hence, all the data values stored in a Redis database are referenced by a unique key.

These keys tend to live forever until you delete them. Usually, we can use the ‘SET’ command to create a new key and assign a value to it. In some scenarios, you might need to set a timeout for a key.

Example – Set password reset link expiration with Redis key

Let’s assume that a user needs to reset his/her Twitter account password. The usual process is that the user clicks on the ‘forgot password’ button in the login window. This would send an email to the user with a password reset link. These links live only for a few minutes or days. Then the link will expire. We can achieve this kind of behavior by passing a Redis key in the URL. Whenever the user clicks on this link, it will redirect to the password reset page if the given key has not expired.

Create a key in Redis

Redis ‘Set’ command can be used to create a new key-value pair in the Redis data store, as shown in the following.

set passwordexpirationlink:user:01 oldpass:123456

The ‘passwordexpirationlink:user:01’ is the Redis key and the value is ‘oldpass:123456’.

Set a timeout for the key

Since the key has been created, we can set a timeout on this key. There are two ways to set a timeout.

  1. Using the Redis ‘SET’ command
  2. Using the Redis ‘EXPIRE’ command

1. Using the Redis ‘SET’ command

The ‘SET’ command has a parameter called ‘EX’ that can be used to set the timeout in seconds. Let’s create a key with a timeout value.

set passwordexpirationlink:user:02 oldpass:123456 ex 120

The key ‘passwordexpirationlink:user:02’ will expire in 120 seconds.

2. Using the Redis ‘EXPIRE’ command

The ‘EXPIRE’ is the most popular command to set a timeout value on a key.

expire passwordexpirationlink:user:02 120

This is quiebro straightforward compared to the ‘SET’ command. The ‘passwordexpirationlink:user:02’ key will expire in 120 seconds.

Now, there should be a way to calculate or query the remaining time to live of a key. The ‘PTTL’ command allows Redis users to query this.

The ‘PTTL’ command

The ‘PTTL’ returns how much time is left before a Redis key expires. If there is no timeout value associated with a key, then this command will return -1. If the Redis key doesn’t exist, it will return -2.

Syntax

The ‘key’ is the Redis key name.

If the Redis key exists and the key is associated with an expiration time, then the ‘PTTL’ command will return the remaining time to live in milliseconds. This command is very similar to ‘TTL’, where the only difference is that ‘TTL’ returns the remaining time to live in seconds.

Let’s set the ‘passwordexpirationlink:user:02’ key’s expiration time to 120 seconds as in the previous example.

expire passwordexpirationlink:user:02 120

Then we can use the ‘PTTL’ command to check the remaining time to live for the key ‘passwordexpirationlink:user:02’.

pttl passwordexpirationlink:user:02

Output after executing the above command several times:

We have set the expiration time to 120 seconds, which is 120000 milliseconds. The output verifies that. The first PTTL command returns 112030, which means the ‘passwordexpirationlink:user:02’ key will expire after 112030 milliseconds or 112.03 seconds.

In the last line, the -2 has been returned. That says the ‘passwordexpirationlink:user:02’ key is already deleted or doesn’t exist anymore. It means the key has already met the expiration time and is gone forever.

The ‘PTTL’ command on a key with no expiration time

Let’s run the ‘PTTL’ command on a key that doesn’t have an expiration time associated with it. First, we are going to create a new key ‘passwordexpirationlink:user:05’.

set passwordexpirationlink:user:05 oldpass:123456

Next, we will be running the ‘PTTL’ command on key ‘passwordexpirationlink:user:05’.

pttl passwordexpirationlink:user:05

Output:

As expected, it returned -1 which means there is no timeout associated with this key.

Based on the return value of the ‘PTTL’ command, we can let the password reset link expire that we discussed in the previous example.

Conclusion

Since Redis is a key-value-based data store, keys are the direct reference for any data value. Redis ‘SET’ command is used to create key-value data in the database. This command allows us to set a timeout when creating the key-value pair. Another way of setting timeouts for keys is using the ‘EXPIRE’ command. In both ways, you can set the expiration time in seconds. The ‘PTTL’ command comes in handy when we need to query the remaining time to live for a Redis key. It returns the remaining time in milliseconds, which is different from the ‘TTL’ command.



Source link