How does Firebase Realtime Database differ from Cloud Firestore in data model, queries, offline behaviour and scale, and when would you still choose it?
answer
- one big JSON tree
- deep reads versus shallow queries
- sort or filter, not both
- presence on disconnect
- about 200,000 connections per database
basics
~20 sRealtime Database is one JSON tree with deep reads, single-property queries, native presence via onDisconnect and very low latency, sharded past one database's limits. Firestore has documents, indexed compound queries and automatic scaling. RTDB suits presence and frequent small state syncs.
solid answer
~50 sFirebase recommends Firestore for new apps, but Realtime Database still fits some jobs. RTDB stores everything as one JSON tree. Reading a node returns its whole subtree, so data must be kept flat. Its queries can sort or filter on one property, but not both, and they need no index, though some slow down as data grows. Firestore stores documents in collections, with shallow, indexed queries that combine filters and sorts. Offline, RTDB disk persistence is opt-in with `setPersistenceEnabled(true)`, while Firestore persists by default on Android. RTDB has native presence: `onDisconnect()` writes run on the server when a client drops, and `/.info/connected` reports the connection. On scale, RTDB reaches about 200,000 concurrent connections and 1,000 writes per second per database before you shard across databases, while Firestore scales automatically but limits writes to a single document. I would pick RTDB for presence and frequent small state syncs where its roughly 10 ms latency matters.
code
kotlin · 20 linesimport com.google.firebase.Firebase
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.ServerValue
import com.google.firebase.database.ValueEventListener
import com.google.firebase.database.database
fun trackPresence(uid: String) {
val db = Firebase.database
val status = db.getReference("status/$uid")
db.getReference(".info/connected").addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.getValue(Boolean::class.java) != true) return
// Registered on the server; runs even if the app crashes or loses network.
status.onDisconnect().setValue(mapOf("online" to false, "lastSeen" to ServerValue.TIMESTAMP))
status.setValue(mapOf("online" to true))
}
override fun onCancelled(error: DatabaseError) = Unit
})
}go deeper
Recall that Realtime Database is one JSON tree whose reads return whole subtrees, while Firestore stores documents in collections.
Explain the query, offline and presence differences: single-property RTDB queries, opt-in RTDB persistence, onDisconnect and .info/connected.
Show you can keep an RTDB tree flat, handle offline transactions that do not survive restarts, and spot when one database's connection or write limits force sharding.
Weigh running both databases, presence in one and app data in the other, against the cost of two rule sets, two billing models and their sync.
## Two databases, one recommendation Firebase has two client-accessible NoSQL databases. Its own comparison recommends that **new customers start with Cloud Firestore**. It describes **Realtime Database** (RTDB) as the classic JSON database, suited to simple data models, simple lookups and low-latency sync with limited scalability. Both can live in the same project, and some apps use both. ## Data model: one tree versus documents - **RTDB** stores all data as **one large JSON tree**. Every value is a node at a path, with keys you choose or keys generated by `push()`. Keys are limited to 768 bytes and cannot contain `.`, `$`, `#`, `[`, `]` or `/`. - **Reads are deep.** Fetching a location returns **all of its children**. Granting access at a node also grants access to everything under it. Data can nest 32 levels deep, but the guide's advice is to keep the tree **as flat as possible**. - **Firestore** stores **documents in collections**, with subcollections for hierarchy. Its queries are shallow and never return subcollection data. In the team task app, nesting tasks and comments under `/projects/$id` in RTDB means that listing project names downloads every task and comment. The flat layout puts `/projects/$id` (metadata), `/tasks/$projectId/$taskId` and `/comments/$taskId/$commentId` at separate paths. ## Queries | | Realtime Database | Cloud Firestore | |---|---|---| | Shape | deep: returns the whole subtree | shallow: one collection or collection group | | Sorting and filtering | sort **or** filter on one property, not both | chained filters combined with sorts | | Indexes | not required; some queries degrade as data grows | required for every query; cost tracks result size | | Granularity | down to a single leaf value | always whole documents | ## Offline and presence - **RTDB persistence is opt-in.** `Firebase.database.setPersistenceEnabled(true)` writes synced data and the queued writes to disk, so they survive an app restart. The default cache keeps **10 MB** of previously synced data. `keepSynced(true)` keeps a path fresh even with no listener. - **RTDB offline queries reuse loaded data.** A query built offline is answered from previously synced data. After an online `limitToLast(4)`, an offline `limitToLast(2)` on the same path is served from the cache, while a query the app never ran online gets no complete `value` event until the device reconnects. - **RTDB transactions are not persisted across restarts**, even with persistence on. They queue while offline but are lost if the app is killed before reconnecting. - **Firestore persists by default on Android**, and its transactions simply fail offline. - **Presence is native to RTDB.** An `onDisconnect()` operation is stored **on the server**, which runs it when the client's connection times out or closes. Rules are checked when you set it up and again when it fires. `/.info/connected` is a client-local boolean that tracks the connection. On Android the SDK closes an idle connection after **60 seconds** when nothing needs it. - **Firestore has no native presence.** The documented approach keeps presence in RTDB and syncs it into Firestore with Cloud Functions. ## Scale, reliability and cost | | Realtime Database | Cloud Firestore | |---|---|---| | Scaling | about 200,000 concurrent connections and 1,000 writes/s per database; beyond that, shard across databases | automatic; no limit on connections or total writes | | Hot spots | no local limit per piece of data | limited write rate per document and per index | | Latency (typical) | 10 ms or less | 30 ms or less | | Uptime (typical) | 99.95%, zonal availability within a region | 99.999%, regional or multi-region | | Billing | bandwidth and storage, at a higher rate | operations (reads, writes, deletes), plus bandwidth and storage at a lower rate | | Transactions | atomic on one subtree | atomic across any documents | Security also differs. RTDB rules **cascade** down the tree and validate with a separate `.validate` rule, while Firestore rules do not cascade and constrain queries. The details belong with security rules. ## When RTDB still wins - **Presence and typing indicators**, where `onDisconnect` does the work a document database cannot. - **High-frequency small state**, such as a shared cursor, live scores or game state, where 10 ms latency and no per-document write limit matter more than rich queries. - **Cost profile**: many tiny reads and writes of small data can be cheaper billed by bandwidth than by operation. Choose Firestore for rich data that the app queries, for availability, and for growth without manual sharding.
- Why can listing project names in Realtime Database download every task and comment?Reading a location returns all of its children. If tasks and comments are nested under each project node, reading `/projects` pulls the whole subtree. Flatten the tree: keep project metadata at `/projects/$id`, tasks at `/tasks/$projectId/$taskId` and comments at their own path, then read each one only when the screen needs it.
- How do teams get presence for a Firestore-based app?Firestore has no native presence. The documented approach uses Realtime Database for the connection status, with `onDisconnect` writes and `/.info/connected`, and syncs that status into Firestore with Cloud Functions. Firestore then holds a status document the app can query and listen to like any other.
- What happens to a Realtime Database transaction made offline if the app is restarted?It is lost. Offline transactions are queued and sent when the connection returns, but even with disk persistence enabled they are not persisted across app restarts. The UI should show them as unsaved, or the app must remember them and run them again. Ordinary writes behave differently: with persistence on, the write queue survives a restart.
- A Realtime Database query can filter on one property and sort on another, like Firestore.
- Reading a Realtime Database node returns only that node's value, not its children.
- Cloud Firestore has built-in presence through onDisconnect.
- Realtime Database bills per document read, the same way Firestore does.
- One Realtime Database instance scales without limit, so sharding is never needed.