Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 31 ยท Firebase Cloud Firestore

Firebase Realtime Database

Learn the Firebase Realtime Database JSON tree: flatten data, write with set, update and push, listen to child events, query, and detach callbacks.

Firebase has two databases. Cloud Firestore stores documents in collections and is the one this track focuses on. The older Realtime Database stores one big JSON tree and pushes every change to connected clients within milliseconds. It is still a good fit for very frequent, small updates such as presence ("who is online"), typing indicators, cursors in a shared editor and live scores.

This lesson covers how the tree is organized and flattened, how to write and read, the child events (child_added, child_changed, child_removed), the query functions, and how to detach callbacks. For the big picture, compare it with Firestore listeners and read Firebase vs Supabase.

The real SDK needs a Firebase project, so its code is read-only. The runnable examples are plain-JavaScript stand-ins that model the tree, events and queries. They are not the Realtime Database network protocol, offline cache or security rules.

Realtime Database vs Firestore

Realtime Database Firestore
Data shape One JSON tree Collections of documents
Queries One sort key per query, simple filters Compound filters, multiple indexes
Reading a node Always returns everything beneath it Returns one document, no subcollections
Scale Best for frequent small updates, one region per database Scales to huge collections, multi-region
Pricing Mostly by bandwidth and storage Mostly by reads, writes and deletes
Offline Mobile SDKs cache; web has no persistent cache by default Offline persistence on all SDKs

Pick the Realtime Database for chatty, low-latency data. Pick Firestore for richer queries and large collections. Many apps use both.

Data is a JSON tree

Everything lives under a root, and each node is addressed by a path such as /users/ana/name. Values are strings, numbers, booleans, null (which means "does not exist") or nested objects. Arrays are stored as objects with numeric keys, and empty nodes disappear.

JSON
{
  "users": {
    "ana": { "name": "Ana", "email": "[email protected]" },
    "ben": { "name": "Ben", "email": "[email protected]" }
  }
}

Why you must flatten

A read of /users returns every user with every child, and a listener on a node downloads its whole subtree. Deeply nested data therefore makes you pay for things you did not ask for. Compare:

JSON
{
  "blogs": {
    "b1": {
      "title": "Sailing",
      "posts": { "p1": { "text": "...", "comments": { "c1": { "text": "..." } } } }
    }
  }
}

Reading /blogs/b1/title is fine, but listing blogs downloads all posts and comments too. The flat version splits each kind of data into its own top-level node and links them by key:

JSON
{
  "blogs":    { "b1": { "title": "Sailing" } },
  "posts":    { "p1": { "blog": "b1", "text": "..." } },
  "comments": { "c1": { "post": "p1", "text": "..." } },
  "postsByBlog": { "b1": { "p1": true } }
}

Rules of thumb:

  • Keep the tree shallow, up to about three levels.
  • Store lists as keyed objects, not arrays, so two clients never fight over an index.
  • Denormalize on purpose: copy a post's title into a user's feed when you need it there, and update both places in one multi-path write (see below). There are no joins.
  • Keep index nodes such as postsByBlog (key: true) to answer "which posts belong to this blog" without scanning.

Setup and writing data

The modular web SDK needs only a database URL in the config:

JavaScript
import { initializeApp } from "firebase/app";
import { getDatabase, ref, set, update, push, remove } from "firebase/database";

const app = initializeApp({
  apiKey: "...",
  databaseURL: "https://my-project-default-rtdb.firebaseio.com"
});
const db = getDatabase(app);

// set: replace everything at the path
await set(ref(db, "users/ana"), { name: "Ana", email: "[email protected]" });

// update: change only the given keys, and several paths atomically
await update(ref(db), {
  "users/ana/name": "Ana M.",
  "postsByBlog/b1/p2": true,
  "posts/p2": { blog: "b1", text: "Second post" }
});

// push: create a child with a new, time-ordered unique key
const newRef = push(ref(db, "posts"));
await set(newRef, { blog: "b1", text: "Third post" });
console.log(newRef.key);          // like "-OAbc123..."

// remove: delete the node (same as set(ref, null))
await remove(ref(db, "posts/p2"));

Three details matter. set overwrites the whole node, including children you did not mention. update with slash-separated keys changes several places atomically: either all of them or none. push keys sort in creation order, so a list of pushed items is already chronological.

Reading data

Read once with get, or subscribe with onValue:

JavaScript
import { get, onValue, child } from "firebase/database";

const snap = await get(child(ref(db), "users/ana"));
if (snap.exists()) console.log(snap.val());   // { name: "Ana M.", ... }

const stop = onValue(ref(db, "users/ana"), (snapshot) => {
  console.log("now:", snapshot.val());        // fires immediately, then on every change
});

onValue fires with the full current value and again whenever anything below the node changes. For a large list that is wasteful, which is why child events exist.

Event types

For lists you usually want to hear about one child at a time:

Function Fires when
onChildAdded Once per existing child at the start, then for every new child
onChildChanged A child or anything beneath it changes
onChildRemoved A child is deleted
onChildMoved A child's position in an ordered query changes
onValue Any change below the node, with the whole subtree
JavaScript
import { onChildAdded, onChildChanged, onChildRemoved } from "firebase/database";

const messages = ref(db, "rooms/general/messages");
onChildAdded(messages,   (s) => addToScreen(s.key, s.val()));
onChildChanged(messages, (s) => updateOnScreen(s.key, s.val()));
onChildRemoved(messages, (s) => removeFromScreen(s.key));

A chat screen that renders from onChildAdded receives each message once instead of re-downloading the whole room every time.

Queries

A query orders a node's children, then narrows the result. You choose one ordering:

  • orderByChild("age") sorts by the value of a child key.
  • orderByKey() sorts by key; orderByValue() sorts by the value itself.

Then add filters: limitToFirst(n), limitToLast(n), startAt, endAt, equalTo.

JavaScript
import { query, orderByChild, equalTo, limitToFirst, limitToLast } from "firebase/database";

// the 10 newest messages (push keys sort by time)
const latest = query(ref(db, "messages"), limitToLast(10));

// all users in Berlin
const berlin = query(ref(db, "users"), orderByChild("city"), equalTo("Berlin"));

// the three youngest users
const youngest = query(ref(db, "users"), orderByChild("age"), limitToFirst(3));

Numbers sort before strings, and strings sort alphabetically. For fast queries, add ".indexOn": ["city", "age"] to the rules for that path; without an index the client downloads the node and filters locally, and the SDK warns you.

Detaching callbacks

Every onValue or onChild... call keeps a connection and a callback alive. In single-page apps, forgetting this leads to duplicate renders and wasted bandwidth. Each listener function returns an unsubscribe function:

JavaScript
const stop = onValue(ref(db, "scores"), render);
// later, when the screen closes:
stop();

You can also call off(ref, "value", callback) with the same callback, or off(ref) to remove all callbacks at that location. Use onValue(ref, cb, { onlyOnce: true }) for a one-time read that detaches itself.

Try it: a tree, events and queries

The stand-in below stores a JSON tree, supports path-based set and update, fires child events for a listed node, runs an orderByChild plus limitToFirst query and shows that a detached listener stops hearing changes.

Node.js A tiny realtime tree with child events and queries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first added ana comes from the listener catching up with existing children, exactly like the real onChildAdded. After stopRemoved() the deletion of ben is silent.

The second example shows why flattening and multi-path updates go together: one update call writes a post and its index entry, and a fan-out to followers' feeds works the same way.

Node.js Flat data with a multi-path update

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Security rules and limits

Realtime Database has its own rules language written as JSON, separate from Firestore's. Rules cascade: a .read or .write of true high in the tree grants access to everything below and cannot be revoked lower down. Start from false and open specific paths with checks like auth != null && auth.uid == $uid. Plan for the limits too: roughly 200,000 simultaneous connections on one database, and a single write must stay under a few megabytes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should you flatten data in the Realtime Database?

    A listener or read on a node returns everything beneath it, so deep nesting makes you download data you did not want.
  2. 2. What is the difference between set and update?

    set overwrites the node, including children you did not mention. update merges keys and multi-path updates are all-or-nothing.
  3. 3. Which event fires once for each existing child when you attach it, and then for every new child?

    child_added first replays the current children, then reports new ones, so lists render one item at a time.
  4. 4. How do you stop receiving updates from a listener?

    Listeners stay active until detached. Forgetting to do it wastes bandwidth and causes duplicate callbacks.
  5. 5. How many orderBy functions can one Realtime Database query use?

    A query has a single ordering such as orderByChild; filters like equalTo and limitToFirst then narrow that order.

Summary

  • The Realtime Database is one JSON tree synced in real time; it suits frequent, small updates such as presence and live scores.
  • Reading a node returns its whole subtree, so keep data flat and use index nodes instead of joins.
  • set replaces, update merges and can write several paths atomically, push creates time-ordered keys, remove deletes.
  • Use child events to handle one item at a time, queries with a single orderBy plus limits and filters, and add .indexOn rules.
  • Always detach listeners with the returned function or off().

Next: Supabase and Postgres Fundamentals.