1

Background

I'm trying to build a simple SMS messaging app that has two trees stored at the root level: numbers and messages – and a two-way relationship between them using indices.

I want to be able to quickly fetch the message history for a particular number, send new messages to new numbers, and send new messages to existing numbers, rendering the sent & received messages in real time.

My data structure looks like this:

{
  "messages" : {
    "-KGZyhbh9sGsizizVyyq" : {
      "5551234" : true,
      "body" : "Foo"
    },
    "-KGZykRFPtdWY2fWb62u" : {
      "555000" : true,
      "body" : "Bar"
    }
  },
  "numbers" : {
    "555000" : {
      "messages" : {
        "-KGZykRFPtdWY2fWb62u" : true
      }
    },
    "5551234" : {
      "messages" : {
        "-KGZyhbh9sGsizizVyyq" : true
      }
    }
  }
}

When a new message is sent to a number, the message is added under messages and Firebase returns a unique ID which I then use to store as a key under numbers/:number/messages.

This is what I currently have for reading the data back:

var ref = new Firebase('https://FIREBASE-APP.firebaseio.com/');

function fetchMessages(number) {
  var numberMessagesRef = ref.child('numbers/' + number + '/messages');
  numberMessagesRef.on('child_added', function(snap) {
    ref.child('messages/' + snap.key()).once('value', function(message) {
      displayMessage(message.val()); // Prepends an <li> in the DOM
    });
  });
}

$('#number').focusout(function() {
  var number = $(this).val();
  fetchMessages(number);
});

Questions

  • Is this data structure the correct way to structure data in Firebase?
  • Am I using indices correctly?
  • This seems like it might be really slow to fetch the message history (potentially hundreds of messages) for a number. How do I further optimise?
Benjamin Humphrey
  • 3,770
  • 2
  • 23
  • 41
  • In general loading data in this way from Firebase is a lot faster than you may expect, see [this post where I explain pipelining](http://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786). But also consider if you should really be loading hundreds of items. It is unlikely that the user is going to be watching all those items, so why are you loading them? – Frank van Puffelen Apr 30 '16 at 03:56
  • Yeah, good point. I suppose I just use [Query.limitToLast()](https://www.firebase.com/docs/web/api/query/limittolast.html) to limit the amount of message history I fetch, until the user scrolls up or something, and then fetch some more. – Benjamin Humphrey Apr 30 '16 at 07:30

0 Answers0