Sign in to track progress and bookmarks.
'Is John online?' Presence tracking is a classic real-time feature that requires careful state management on the server.
Every Hub has these two overrideable methods. When a user connects, you can increment a count in Redis or update their 'LastSeen' status in your database. When they disconnect, you do the opposite. Then, you broadcast a UserStatusChanged event to all their friends.
The trick: If a user has 3 tabs open, they are 'Online'. If they close ONE tab, they are still 'Online'. You only mark them 'Offline' when their **Last** connection is closed. This requires maintaining a mapping of UserID -> Set of ConnectionIDs in a distributed cache like Redis.
Q: "Should I use my SQL database for presence?"
Architect Answer: "NO. Presence updates are incredibly frequent. Writing to SQL every time a user refreshes a page will kill your database performance. Use **Redis** with a short TTL (Time-To-Live). This is much faster and automatically 'expires' users if your server crashes and fails to run the OnDisconnected logic."
Quizzes linked to this course—pass to earn certificates.
On this page
1. OnConnected and OnDisconnected 2. Handling Multiple Connections 3. Architect Insight