Does Firebase cache the data?

I read somewhere a claim that Firebase caches the data.

So I ran this test that reads a semi large volume of data (about 400KB).

Here is the relevant code.

firebase.initializeApp(config);

var counter = 0;

console.time('firebase answered in');
firebase.database().ref('texts').once('value',onData);

function onData(snapshot){
  console.timeEnd('firebase answered in');

  counter ++;
  if(counter > 20) return;

  setTimeout(function(){
    console.time('firebase answered in');
    firebase.database().ref('texts').once('value',onData);
  },2000);
}

As you can see, the first time it loads data it takes a while, and subsequent calls take much less time.

firebase answered in: 1279.422ms

firebase answered in: 236.378ms

firebase answered in: 228.595ms

firebase answered in: 202.700ms

firebase answered in: 208.371ms

firebase answered in: 214.807ms

etc

But, still, if the data is cached locally ~200ms (sometimes more) seems like a lot of time to access local data. Enough for the user to perceive a delay when rendering the UI.

So is Firebase caching the data? What is happening in those ~200ms?

Answers:

Answer

Firebase caches the data (in memory) for as long as there is an active listener for that data.

Since your code uses only once() listener, the listener is detached immediately when the data is received (before your callback is invoked) and the data is cleared from the cache. That means that is has to get the data from the servers for each once(), which apparently is a 200ms round-trip in your case. The first load is slower, because the connection is likely established in that call.

A quick trick to verify this is to add a permanent listener before starting your loop:

firebase.initializeApp(config);

var counter = 0;

console.time('firebase answered in');
firebase.database().ref('texts').on('value',function() {});
firebase.database().ref('texts').once('value',onData);

function onData(snapshot){
  console.timeEnd('firebase answered in');

  counter ++;
  if(counter > 20) return;

  setTimeout(function(){
    console.time('firebase answered in');
    firebase.database().ref('texts').once('value',onData);
  },2000);
}

With that simple change, the logging turns into:

firebase answered in: 580.575ms

firebase answered in: 4.040ms

firebase answered in: 7.569ms

firebase answered in: 5.739ms

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.