jahed.dev

Reducing Firebase Real-time Database Connections

One of the challenges with using Firebase's free tier is the low 100 connections limit on its real-time database. This means we can't have more than 100 visitors connected to the database at the same time. Even for small experimental apps it's easy to hit this limit the moment a link is shared publicly.

It's good to design an app so that visitors beyond the 100th connection can still use the app in a limited way. That way even when the database is down, the app can still be usable. However, what tends to happen is that not all visitors are actively using the app, but they'll still hog a connection and pull in data in the background. That's completely unnecessary in most cases.

To resolve this, we can combine some browser APIs with Firebase's APIs.

let timeoutId: number;

const onFocus = (): void => {
  window.clearTimeout(timeoutId);
  firebase.database().goOnline();
};

const onBlur = (): void => {
  window.clearTimeout(timeoutId);
  timeoutId = window.setTimeout(() => {
    firebase.database().goOffline();
  }, 10_000);
};

window.addEventListener("focus", onFocus);
window.addEventListener("blur", onBlur);

Here we've added focus and blur listeners. When the page is out of focus, blur is triggered and we wait 10 seconds before disconnecting. This prevents visitors from spamming disconnect and reconnect calls to the database when they're clicking around and haven't settled in yet. When the window is back in focus, focus is triggered and we reconnect.

It's that simple.

Thanks for reading.