Sean Clark Hess
Sean Clark Hess

Reputation: 16059

How to clean up inactive players in redis?

I'm making a game that uses redis to store game state. It keeps track of locations and players pretty well, but I don't have a good way to clean up inactive players.

Every time a player moves (it's a semi-slow moving game. Think 1-5 frames per second), I update a hash with the new location and remove the old location key.

What would be the best way to keep track of active players? I've thought of the following

  1. Set some key on the user to expire. Update every heartbeat or move. Problem is the locations are stored in a hash, so if the user key expires the player will still be in the same spot.
  2. Same, but use pub/sub to listen for the expiration and finish cleaning up (seems overly complicated)
  3. Store heartbeats in a sorted set, have a process run every X seconds to look for old players. Update score every heartbeat.
  4. Completely revamp the way I store locations so I can use expire.. somehow?

Any other ideas?

Upvotes: 3

Views: 2194

Answers (1)

doug
doug

Reputation: 70038

Perhaps use separate redis data structures (though same database) to track user activity and user location.

For instance, track users currently online separately using redis sets:

[my code snippet is in python using the redis-python bindings, and adapted from example app in Flask (python micro-framework); example app and the framework both by Armin Ronacher.]

from redis import Redis as redis
from time import time

r1 = redis(db=1)

when the function below is called, it creates a key based on current unix time in minutes and then adds a user to a set having that key. I would imagine you would want to set the expiry at say 10 minutes, so at any given time, you have 10 keys live (one per minute).

def record_online(player_id):
    current_time = int(time.time())
    expires = now + 600     # 10 minutes TTL
    k1 = "playersOnline:{0}".format(now//60)
    r1.sadd(k1, player_id)
    r1.expire(k1, expires)

So to get all active users just union all of the live keys (in this example, that's 10 keys, a purely arbitrary number), like so:

def active_users(listOfKeys):
    return r1.sunion(listOfKeys)

This solves your "clean-up" issues because of the TTL--the inactive users would not appear in your live keys because they constantly recycle--i.e., in active users are only keyed to old timestamps which don't persist in this example (but perhaps are written to a permanent store by redis before expiry). In any event, this clears inactive users from your active redis db.

Upvotes: 5

Related Questions