3

I find it very easy to count number of active connections using

redis_sip = redis.Redis(host="localhost", port=6379, db=0)
redis_sip.setbit(skey, 1, 1)
redis_sip.setbit(skey, 2, 1)
redis_sip.setbit(skey, 3, 0)
redis_sip.setbit(skey, 4, 1)
print(redis_sip.bitcount(skey)) # shows me 3 connections

But for this to work I need to be able to set a TTL for each individual bit.

i.e. when a remote agent makes a connection, I can set the bit to 1. If bitwise expiry is supported, then the bit will be flipped after a length of inactivity.

Is it doable at all in Redis? If not, what is an alterantive?

Anthony Kong
  • 37,791
  • 46
  • 172
  • 304

2 Answers2

5

NO, you cannot expire a bit.

Instead, you can only expire a key. So in order to achieve your goal, when a connection established, you can set a key with a timeout. When you want to get the total number of connections, use the DBSIZE command.

// agent 1 establishes a connection, set a timeout of 60s
SET 1 1 EX 60
// agent 2 establishes a connection, set a timeout of 60s
SET 2 2 EX 60
/// agent 1 closes the connection
DEL 1
// total connections
DBSIZE

Also, you should be careful with SETBIT command. If an agent with a large id, say, 100000000, establishes a connection, when setting the corresponding bit, Redis needs to allocate lots of memory, and might block for a while. See the doc for detail.

for_stack
  • 21,012
  • 4
  • 35
  • 48
3

As noted, Bitmaps do not support bit-level expiry. In fact, none of the core Redis data structures provide nested-element expiry.

An easy alternative would be to use Sorted Sets. For each new connection, ZADD it as a member with a score that is the current timestamp (epoch). Then, in order to obtain a count, do a ZREMRANGEBYSCORE from '-inf' to the current time minus your "TTL" - this will "trim" the zset to include only non-expired connections. Lastly, you can call ZCARD to obtain the cardinality/count of members.

Itamar Haber
  • 47,336
  • 7
  • 91
  • 117
  • 1
    Here [how to store in sorted set with server-side timestamp as score](https://stackoverflow.com/questions/59846503/how-to-store-in-redis-sorted-set-with-server-side-timestamp-as-score) – LeoMurillo Jan 30 '20 at 14:59