What’s the best way to keep a list of online users in a web application?
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: Parquet in Datasette Lite, various talks, more LLM hacking - 4th June 2023
- It's infuriatingly hard to understand how closed models train on their input - 4th June 2023
- ChatGPT should include inline tips - 30th May 2023
- Lawyer cites fake cases invented by ChatGPT, judge is not amused - 27th May 2023
- llm, ttok and strip-tags - CLI tools for working with ChatGPT and other LLMs - 18th May 2023
- Delimiters won't save you from prompt injection - 11th May 2023
- Weeknotes: sqlite-utils 3.31, download-esm, Python in a sandbox - 10th May 2023
- Leaked Google document: "We Have No Moat, And Neither Does OpenAI" - 4th May 2023
- Midjourney 5.1 - 4th May 2023
- Prompt injection explained, with video, slides, and a transcript - 2nd May 2023