"how to write denormalized data in firebase" Code Answer


great question. i know of three approaches to this, which i'll list below.

i'll take a slightly different example for this, mostly because it allows me to use more concrete terms in the explanation.

say we have a chat application, where we store two entities: messages and users. in the screen where we show the messages, we also show the name of the user. so to minimize the number of reads, we store the name of the user with each chat message too.

    name: "frank van puffelen"
    location: "san francisco, ca"
    questioncount: 12
    name: "legolandbridge"
    location: "london, prague, barcelona"
    questioncount: 4
    message: "how to write denormalized data in firebase"
    user: so:3648524
    username: "legolandbridge"
    message: "great question."
    user: so:209103
    username: "frank van puffelen"
    message: "i know of three approaches, which i'll list below."
    user: so:209103
    username: "frank van puffelen"

so we store the primary copy of the user's profile in the users node. in the message we store the uid (so:209103 and so:3648524) so that we can look up the user. but we also store the user's name in the messages, so that we don't have to look this up for each user when we want to display a list of messages.

so now what happens when i go to the profile page on the chat service and change my name from "frank van puffelen" to just "puf".

transactional update

performing a transactional update is the one that probably pops to mind of most developers initially. we always want the username in messages to match the name in the corresponding profile.

using multipath writes (added on 20150925)

since firebase 2.3 (for javascript) and 2.4 (for android and ios), you can achieve atomic updates quite easily by using a single multi-path update:

function renameuser(ref, uid, name) {
  var updates = {}; // all paths to be updated and their new values
  updates['users/'+uid+'/name'] = name;
  var query = ref.child('messages').orderbychild('user').equalto(uid);
  query.once('value', function(snapshot) {
    snapshot.foreach(function(messagesnapshot) {
      updates['messages/'+messagesnapshot.key()+'/username'] = name;

this will send a single update command to firebase that updates the user's name in their profile and in each message.

previous atomic approach

so when the user change's the name in their profile:

var ref = new firebase('https://mychat.firebaseio.com/');
var uid = "so:209103";
var nameinprofileref = ref.child('users').child(uid).child('name');
nameinprofileref.transaction(function(currentname) {
  return "puf";
}, function(error, committed, snapshot) {
  if (error) { 
    console.log('transaction failed abnormally!', error);
  } else if (!committed) {
    console.log('transaction aborted by our code.');
  } else {
    console.log('name updated in profile, now update it in the messages');
    var query = ref.child('messages').orderbychild('user').equalto(uid);
    query.on('child_added', function(messagesnapshot) {
      messagesnapshot.ref().update({ username: "puf" });
  console.log("wilma's data: ", snapshot.val());
}, false /* don't apply the change locally */);

pretty involved and the astute reader will notice that i cheat in the handling of the messages. first cheat is that i never call off for the listener, but i also don't use a transaction.

if we want to securely do this type of operation from the client, we'd need:

  1. security rules that ensure the names in both places match. but the rules need to allow enough flexibility for them to temporarily be different while we're changing the name. so this turns into a pretty painful two-phase commit scheme.
    1. change all username fields for messages by so:209103 to null (some magic value)
    2. change the name of user so:209103 to 'puf'
    3. change the username in every message by so:209103 that is null to puf.
    4. that query requires an and of two conditions, which firebase queries don't support. so we'll end up with an extra property uid_plus_name (with value so:209103_puf) that we can query on.
  2. client-side code that handles all these transitions transactionally.

this type of approach makes my head hurt. and usually that means that i'm doing something wrong. but even if it's the right approach, with a head that hurts i'm way more likely to make coding mistakes. so i prefer to look for a simpler solution.

eventual consistency

update (20150925): firebase released a feature to allow atomic writes to multiple paths. this works similar to approach below, but with a single command. see the updated section above to read how this works.

the second approach depends on splitting the user action ("i want to change my name to 'puf'") from the implications of that action ("we need to update the name in profile so:209103 and in every message that has user = so:209103).

i'd handle the rename in a script that we run on a server. the main method would be something like this:

function renameuser(ref, uid, name) {
  ref.child('users').child(uid).update({ name: name });
  var query = ref.child('messages').orderbychild('user').equalto(uid);
  query.once('value', function(snapshot) {
    snapshot.foreach(function(messagesnapshot) {
      messagesnapshot.update({ username: name });

once again i take a few shortcuts here, such as using once('value' (which is in general a bad idea for optimal performance with firebase). but overall the approach is simpler, at the cost of not having all data completely updated at the same time. but eventually the messages will all be updated to match the new value.

not caring

the third approach is the simplest of all: in many cases you don't really have to update the duplicated data at all. in the example we've used here, you could say that each message recorded the name as i used it at that time. i didn't change my name until just now, so it makes sense that older messages show the name i used at that time. this applies in many cases where the secondary data is transactional in nature. it doesn't apply everywhere of course, but where it applies "not caring" is the simplest approach of all.


while the above are just broad descriptions of how you could solve this problem and they are definitely not complete, i find that each time i need to fan out duplicate data it comes back to one of these basic approaches.

By matm on March 18 2022

Answers related to “how to write denormalized data in firebase”

Only authorized users can answer the Search term. Please sign in first, or register a free account.