Wassim Beltaief

Firebase for fast prototyping

Tuesday, August 30, 2016

We need a backend for a side project. Nobody wants to set up a server, write API endpoints, handle auth. We just want to build the app.

A friend says try Firebase. I add the dependency, follow the quick start, and in two hours we have real-time sync between two phones. No server code. No API. Just JSON in a tree.

The setup

compile 'com.google.firebase:firebase-database:9.4.0'

That is it. No backend to deploy.

val database = FirebaseDatabase.getInstance()
val messagesRef = database.getReference("messages")

// write
messagesRef.push().setValue(Message(text = "hello", sender = userId))

// read in real time
messagesRef.addValueEventListener(object : ValueEventListener {
    override fun onDataChange(snapshot: DataSnapshot) {
        val messages = snapshot.children.mapNotNull {
            it.getValue(Message::class.java)
        }
        adapter.submitList(messages)
    }

    override fun onCancelled(error: DatabaseError) {
        Log.e("TAG", error.message)
    }
})

When any client writes to messages, every other client with a listener receives the update instantly. No polling, no WebSockets to manage. It just works.

Offline support

This is the part that impresses me most. Firebase caches data locally. If the device goes offline, writes are queued. When connection returns, everything syncs.

FirebaseDatabase.getInstance().setPersistenceEnabled(true)

One line. Offline support that would take weeks to build manually.

Auth

Firebase Auth connects directly to the database with security rules:

{
  "rules": {
    "messages": {
      ".read": "auth != null",
      ".write": "auth != null"
    }
  }
}

Only authenticated users can read or write. You define these rules in the Firebase console. No middleware, no token verification on a server.

What bites us later

The JSON tree structure is fast when you know your access patterns upfront. But it is easy to nest data in a way that makes queries slow or impossible.

For example, to get all messages from a specific user you need to scan the entire messages node unless you duplicate the data or restructure. In SQL you add an index. In Firebase you rethink your data model.

Also the pricing changes. The free tier is generous for prototypes but real-time listeners on large datasets get expensive fast.

Verdict

For prototypes and small apps, Firebase Realtime Database is still the fastest way to have a working backend. The developer experience is excellent.

For production apps with complex queries, plan the data structure carefully upfront or you will regret it. Alternatively, Firestore (not out yet but coming) promises better querying. We will see.