0

I've seen post here How to count the number of keys matching a pattern? which comments said it is not advisable to count keys in production. Which I believe is true.

My question is.. is it still not recommended when keys expire? expiration deletes keys.

what im trying to do is I am counting the number of active users via storing them in redis key which has expiration. Im doing it with Laravel. I need to count that matching keys for able to get the number of active users.

Any recommendation? Thanks Guys!

JSTR
  • 131
  • 13

1 Answers1

1

Would it not be a way more pragmatic solution to rely on a last_login field or last_active field, you set in the front end. Either on using the Laravel application or an user activity every 15 minutes or similar. Middleware you would set on every call in your application.

class LastActivityMiddleware
{
    public function handle(Request $request, Closure $next, ...$guards)
    {
        $user = Auth::user();
        
        $user->last_activity = now();
        $user->save();

        return $next($request);
    }
}

Which would make it possible to do.

User::where('last_active', '>=', now()->subMinutes(15))->count();

The other solution would have a horrible run time, aparently break the cache and simply be a very complex solution to a simple problem.

mrhn
  • 17,961
  • 4
  • 27
  • 46
  • This was my original solution and thought it would be better to use redis, im trying to explore redis more to learn its application like laravel. but I guess middleware still the best approach though hahaha. Thanks man! – JSTR Oct 15 '21 at 09:49
  • I would think this is best, also redis command has to loop through all users keys, if you have millions that gotta take a while. – mrhn Oct 15 '21 at 09:57