Kamil Zielinski
Kamil Zielinski

Reputation: 171

Redis session with concurrent user licensing

I want to use Redis for session. Users will be stored in Redis with expire which will be updated on each request. I would like to implement concurrent license.

How can I count number of currently stored keys?

I found out that there is KEYS command but it should not be used on production. I also thought about some triggers when key expires but again it's not what I should rely on.

How can I implement concurrent user licensing with Redis?

Upvotes: 1

Views: 320

Answers (1)

Eli
Eli

Reputation: 38989

This is not a great use for EXPIRE or the top level of Redis keys. If you ever want to store anything else in Redis, it will mess up your logic. Also, although you can count the total number of keys with a command like DBSIZE, it may be inaccurate because Redis does not actively expire items. In my impression, Redis is built so that the exact number of keys in the top level should not be important.

For cases where an exact number of keys is important, Redis has some great datastructures you can make use of. In your case, I'd recommend a sorted set where the key is a user_id and the score is the expiration date in Unix time. This would look something like:

ZADD users_set 1453771862 "user1"
ZADD users_set 1453771563 "user2"
ZADD users_set 1453779999 "user3"

Then, any time you need to know how many current users there are, you can just do a ZCOUNT for all expiration times higher than the current time:

ZCOUNT users_set 1453771850
>>> 2

ZADD operations are idempotent, so you can also easily add/update expiration times on users:

ZADD users_set 1453779999 "user2"
ZCOUNT users_set 1453771850
>>> 3

This way you get an exact count of relevant users every time you do a ZCOUNT, and every operation you're doing is a relatively cheap O(log(n)).

Finally, if literally removing/expiring users from the sorted set is important to you, you can do this as a pretty cheap batch job with ZREMRANGEBYRANK on whatever interval you like.

Upvotes: 2

Related Questions