Search code examples
javascriptfirebase-realtime-databaseangularfire2

How to reduce amount of data being transmitted in Firebase Realtime Database?


I am using the Google Cloud Firebase Realtime database to store messages. The messages are saved in

users/$userID/messages/$topic[0..n]/message[0..n]

I am using the official JS library AngularFire. I am listening on new messages via the following code:

this.observable = this.db.list(`users/${user.uid}/topics/${topic}/`).valueChanges();

I can now subscribe to the observable. Imagine the user has 1 million messages in a given topic. Whenever I add a new message, I receive the 1 million messages in the callback.

My question is, how much data is actually transferred behind the scenes if I modify or add a new message? I know the library keeps a local copy of the database.

On top, how do I find out which message got modified? Or do I need to figure this out myself?


Solution

  • If you have an existing listener, and a new message is added, only that new message is sent to that client. You can easily verify this for yourself by looking at the web socket traffic in the network tab of your browser's developer tools.

    But I would recommend to use a query and limit to reduce the number of messages retrieved, as it seems unlikely any user will read 1 million messages, and it's wasteful to retrieve (much) more data than the user will see.

    Based on the AngularFire documentation on querying lists, that should be something like:

    this.db.list(`users/${user.uid}/topics/${topic}/`, 
      ref => ref.orderByKey().limitToLast(20)
    ).valueChanges()