Home > Mobile >  Efficiency or cost of many calls to Firebase
Efficiency or cost of many calls to Firebase

Time:12-14

My app produces pages of 20 content items that may include items liked by the current user and other users. I use Firebase Realtime Database to keep track of the likes but the content is stored elsewhere and the pages are server-rendered, so a completely new page is served each time. I need to identify and mark the liked items and show the status of each item in real time:

  1. Its number of likes, and
  2. Whether it has been liked by the current user.

To get the number of likes in real time, I loop through the items with this function, modified from the Firebase Friendlypix demo:

function registerForLikesCount(postId, likesCallback=null) {
  const likedRef = firebase.database().ref(`/liked/${postId}`);
    likedRef.on("value", function(snapshot) {
      if (snapshot.val()) {
        likesCallback(snapshot.val().count);
      }
    });
  }

That's 20 calls for each page plus an event listener is set, right? It's fast but I don't know about the cost. What resources are used for all those listeners a) if nothing happens, or b) if a like is registered and transmitted to say, 100 concurrent users?

To keep track of whether the current logged-in user has liked any of the items, I've tried two ways:

  1. For each page, grab the user's likes from their Firebase node. That's one call to Firebase, possibly grabbing a few dozen IDs (not more) and, during the above-mentioned loop, check if any of the IDs are included.

  2. Or, using a snippet from Friendlypix, for another 20 calls to Firebase:

function registerToUserLike(postId, callback) {
    // Load and listen to new Likes.
    const likesRef = firebase.database().ref(`likes/${postId}/${firebase.auth().currentUser.uid}`);
    likesRef.on('value', (data) => callback(!!data.val()));
  }

registerToUserLike has the advantage of keeping any of the user's open tabs or devices updated and shows off the magic of realtime, but at what price?

I would like to understand what resources are consumed by this activity in order to estimate the cost of running my application.

CodePudding user response:

The overhead on the Firebase protocol for all these listeners is minimal, each sends the path it wants to listen to the server (not a paid operation for Firebase, but your mobile provider may charge for the bandwidth) and then receives the data from the path it listens to and updates to the data at that path.

The number of calls is not a significant part of the cost here, so the only way to reduce the cost would be to listen to less data. In a nutshell: it matters very little whether you have 20 calls listening to 1 node, or 1 call listening to 20 nodes in Firebase.

For more on why this is, see my answer to the questions about Speed up fetching posts for my social network app by using query instead of observing a single event repeatedly

  • Related