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: Llama 3, AI for Data Journalism, llm-evals and datasette-secrets - 23rd April 2024
- Options for accessing Llama 3 from the terminal using LLM - 22nd April 2024
- AI for Data Journalism: demonstrating what we can do with this stuff right now - 17th April 2024
- Three major LLM releases in 24 hours (plus weeknotes) - 10th April 2024
- Building files-to-prompt entirely using Claude 3 Opus - 8th April 2024
- Running OCR against PDFs and images directly in your browser - 30th March 2024
- llm cmd undo last git commit - a new plugin for LLM - 26th March 2024
- Building and testing C extensions for SQLite with ChatGPT Code Interpreter - 23rd March 2024
- Claude and ChatGPT for ad-hoc sidequests - 22nd March 2024
- Weeknotes: the aftermath of NICAR - 16th March 2024