Skip to content Skip to sidebar Skip to footer

How To Make User Presence Mechanism Using Firebase?

I want to change user status to show either he is online or not. I want to change user status to false in database when User close application or when he loses connection with serv

Solution 1:

There are two ways the user can get disconnected from the Firebase Database.

  1. a clean disconnect, where the client sends a signal to the server before it disconnects.
  2. a dirty (for lack of a better term) disconnect, where the connection gets closed before the client can send a signal.

In the case of a clean disconnect, your onDisconnect handlers will immediately fire and thus your database will immediately be updated.

In the case of a dirty disconnect, Firebase depends on the socket layer to signal when the remote client is gone. This may take anywhere up to a few minutes. But eventually the server will detect/decide that the client is gone, and your onDisconnect handlers will fire.


A small note in your data structure: you that there is a 1:1 relation between a user and a connection. That is unfortunately not the case.

  • A user may be connected from multiple devices. If they now disconnect from one of those devices, the onDisconnect from that device will set online to false while they may still be connected on another device.
  • Mobile devices/networks have a habit of going through occasional disconnect/reconnect cycles. This means that you may have multiple connections, even on a single device. In case of a dirty disconnect, the onDisconnect handler may be fired much later, when you've already set online to true for the new connection. In such a case, your lingering onDisconnect handler will set online to false while the user may already be reconnected.

All this is to say that you should not rely on having a 1:1 relation between a user and their connection(s). The samples in the Firebase documentation treat connections as a collection and assume that the user is connected as long as there is any "connect ID" (generated by push()) left for that user. I recommend you do the same to prevent hard to debug race conditions and connection problems.

Post a Comment for "How To Make User Presence Mechanism Using Firebase?"