What’s the best way to keep a list of online users in a web application?
28th November 2011
My answer to What’s the best way to keep a list of online users in a web application? on Quora
It depends on your definition of “online”—for this answer, let’s count anyone who has visited a page within the last 5 minutes.
I’d use redis—it performs 100,000 operations per second quite happily (since it’s all in-memory) so even with dozens of web avers just one redis instance should keep up perfectly happily.
One solution would be to use a redis sorted set. Every time a user views a page or performs an action, set a “score” in the sorted set to the current timestamp (the key should be their user ID). You can count the number of users who acted I the past five minutes using the ZCOUNT command with a timestamp of now-5mins. Periodically delete everything over than five minutes to free up memory.
You could also use redis sets one for every minute of the day, and then call SCARD on the five sets representing the last five minutes and add the results together.
Short version: use redis, it’s perfect for this kind of thing.
More recent articles
- Weeknotes: datasette-enrichments, datasette-comments, sqlite-chronicle - 8th December 2023
- Datasette Enrichments: a new plugin framework for augmenting your data - 1st December 2023
- llamafile is the new best way to run a LLM on your own computer - 29th November 2023
- Prompt injection explained, November 2023 edition - 27th November 2023
- I'm on the Newsroom Robots podcast, with thoughts on the OpenAI board - 25th November 2023
- Weeknotes: DevDay, GitHub Universe, OpenAI chaos - 22nd November 2023
- Deciphering clues in a news article to understand how it was reported - 22nd November 2023
- Exploring GPTs: ChatGPT in a trench coat? - 15th November 2023
- Financial sustainability for open source projects at GitHub Universe - 10th November 2023
- ospeak: a CLI tool for speaking text in the terminal via OpenAI - 7th November 2023