Reputation: 752
I need to design a node.js app in this scenario:
token
record
with this token on redis(?) with a 5 mins TTL. token
s has n
type. So redis(?) should store tokens with types.record
expire, record
's TTL reset to 5 mins again.record
expires, a function is triggered.record
s belongs to a specific type (i.e. type 27).What would be the best way to achieve this problem? Is redis right choice for it? How can I count token
s and trigger 5. step if I use redis?
Using https://github.com/Automattic/kue or something like that would be the nice choice?
Edit: It seems possible duplicate with Event on key expire . In general, I ask, is redis suitable for this problem? If you think it is, could you please give an example pattern I should follow. If not, what are any other solutions maybe even without redis or 3rd party tool.
Also as I said at the 5. item in the list above, redis seems not suitable at querying keys
with a pattern as described here:https://redis.io/commands/keys
. Because there seems no way to put expiration on an individual member of a set (TTL for a set member) , I cannot put tokens in a type
set or hash . Thus I need to query keys in order to get count of a group (type
) and this seems not efficient as described at the link above.
Even if https://redis.io/topics/notifications solves the problem at the 4. item in the list above, I also ask for "Which pattern/algorithm should I go and how" . I don't want you to code for me, but just need a spark. A tutorial, guide, video etc.. would be great. Thanks!
Upvotes: 0
Views: 979
Reputation: 3479
You have many options in order to achieve what you want, but I'm going to provide one here, which is a very efficient one in terms of retrieving speed, but it requires some more space. It all depends on your use-case, obviously.
Say token is 12345, type is A
When adding a token (we'll do it with a transaction):
MULTI
SETEX tokens:12345 300 ""
SET type:12345 "A"
INCR types:A
EXEC
When the key expires (after 300 seconds, or whenever Redis sees it as expired) we get notified using Keyspace notifications (https://redis.io/topics/notifications) listening for the EXPIRED event:
PSUBSCRIBE __keyspace@0__:expired
When that subscription receives a message, in your code you'd need to:
MULTI
GET type:12345 # Returns A
DEL type:12345
DECR types:A
EXEC
In order to get the elements of a specific type:
GET types:A
Any NodeJS Redis client would work just fine for this.
I want to make clear this is only one of the multiple options you have; one of the Redis advantages is it's flexibility.
Upvotes: 1