Alternative implementation for last seen in chat application

616

Firebase writes would indeed be a bit costlier since you would be sending in a lot of writes, which, apparently are just for the job of "last seen".

Instead, as you mentioned, having a socket connection with your own server will help reduce the number of queries you make. i.e. As soon as the socket disconnects from the server, you can send a write operation to Firebase. "Every 3 seconds vs Only when the user disconnects".

Plus (not something that you asked for), if you would be setting up a socket server of your own, then it shall help in the following scenarios as well:

  • Typing events (The indication we get when the other person is typing a message)
  • Quicker way to know if the person at the other end is online/offline (because of sockets)
Share:
616
Hassan Shaitou
Author by

Hassan Shaitou

Updated on November 24, 2022

Comments

  • Hassan Shaitou
    Hassan Shaitou over 1 year

    I Will describe my use case with figures attached and everything i can do to be clear so we may get up with a better idea ...

    General idea:

    • Whatsapp chat application with firebase Use case: As we know one of the features of whatsapp is the last seen, when the user did (exited the app, log out, lost wifi connection, etc ..) I tried to use:

    • onDisconnect, but onDisconnect gives bad result when losing wifi connection (because of the socket latency to be timed out)

    • the one I am using now, is every user updates its timestamp every 3 seconds (update document every 3 seconds), when the user loses connection, he won't be able to update his timestamp, right? So, if another user wants to chat with this offline user, I can show him the user's last seen. Hope this this is clear...

    • Developed using Flutter framework

    • Redux to manage app state

    • Firebase, cloud firestore

    The code below is dispatching an action every three seconds, this dispatched action will update the last seen in firebase...

    timer = Timer.periodic(Duration(seconds: 3), (Timer t) {
       // store.dispatch(updateUserOnline());
    });
    

    As you can see in the figure below my data structure of how I am updating last seen for this user every 3 seconds ...

    This implementation is very expensive to get satisfactory results for a last seen for a user, if we have million users and these million users are updating their last seen every 3 seconds it will cost a lot $ per month, as we are doing a write operation, no?

    So, my other solution is to implement a socket connection to my own server and let all the users listen to the onDisconnect socket event on my server instead of Firebase server, is this doable to avoid the huge cost of writing operations?

    image attached: here