skip to content

Firestore & Realtime DB

Firestore's document model, the queries it allows and the indexes they need, listeners, transactions and offline persistence, against Realtime Database. Interviewers probe the query limits.

on this pageshow

explore

questions

6

In Cloud Firestore, how do documents, collections and subcollections fit together, and what happens to a subcollection when its parent document is deleted?

level: juniorimportance: must knowfreq 68%

answer

  1. alternating path segments
  2. a collection holds only documents
  3. 1 MiB ceiling per document
  4. queries read one collection's documents
  5. what a parent delete leaves behind

basics

~20 s

Firestore keeps fields in documents of up to 1 MiB, documents in collections, and lets a document own subcollections, so paths alternate collection and document. Deleting a document leaves its subcollections in place; they must be deleted separately.

solid answer

~40 s

A document is Firestore's unit of storage: a named set of fields (strings, numbers, booleans, timestamps, geo points, blobs, arrays and maps) capped at 1 MiB. Documents live in collections, and a collection holds only documents, never raw fields or other collections. A document can own subcollections, so a path always alternates, as in `projects/apollo/tasks/t42/comments/c1`, and a collection exists as soon as its first document is written. Two consequences come up in interviews: queries are shallow, so reading `tasks` never pulls in each task's `comments`; and deleting `projects/apollo` does **not** delete `projects/apollo/tasks`. Those documents stay readable by their full paths until your own code deletes them.

code

kotlin · 12 lines
kotlin
import com.google.firebase.Firebase
import com.google.firebase.firestore.firestore

val db = Firebase.firestore

// projects/{projectId}/tasks/{taskId}/comments/{commentId}
val task = db.collection("projects").document("apollo")
    .collection("tasks").document("t42")
val comments = task.collection("comments")

// Deleting the task document leaves every document in `comments` in place.
fun deleteTaskOnly() = task.delete()

go deeper

for a junior

Recall the alternating collection-and-document path, the 1 MiB document limit, and that deleting a parent leaves its subcollections behind.

for a middle

Explain why Firestore queries are shallow, how a collection group query reaches across parents, and why it needs a collection-group-scope index first.

for a senior

Show that you plan deleting a project's whole subtree from trusted server code in batches, and keep documents small so reads and listeners stay cheap.

for a principal

Weigh the benefits of deep hierarchy against shallow queries, orphaned subtrees and the 1 MiB ceiling, then set team conventions for paths, IDs and cleanup.

## The document is the unit of storage Cloud Firestore is a NoSQL **document database**. A **document** is a named record holding **fields**, each mapping a name to a value. Supported values include booleans, numbers, strings, timestamps, geo points, binary blobs, **arrays** and nested objects called **maps**. Documents look a lot like JSON, but they carry extra types and a hard size limit. Firestore is **schemaless**: two documents in the same collection may hold different fields. The documentation still advises keeping the same fields and types across a collection, because that makes the documents easier to query. The limits that shape every design: - a document can be at most **1 MiB (1,048,576 bytes)**; - a document's full name (its path) can be at most **6 KiB**; - maps and arrays can nest at most **20** levels inside one document; - a single field value can be at most 1 MiB minus 89 bytes. The guide describes Firestore as *optimized for storing large collections of small documents*. That sentence is the design rule in miniature. ## Collections and the alternating path A **collection** is a container for documents and nothing else. It cannot hold raw fields, and it cannot directly contain another collection. You do not create a collection explicitly. It appears when its first document is written and disappears when its last document is deleted. Every document is identified by its location, so paths always **alternate**: collection, document, collection, document. You cannot reference a collection inside a collection or a document inside a document. In client code there are two distinct reference types: - `CollectionReference`, used to query or add documents; - `DocumentReference`, used to read, write or delete one document. Creating a reference performs **no network operation**. It is only a pointer, and it is valid whether or not data exists there. Document IDs can be your own keys, such as a user ID, or automatic IDs. An ID must be valid UTF-8 and no longer than 1,500 bytes. It cannot contain `/`, cannot be `.` or `..`, and cannot match `__.*__`. ## Subcollections in a team task-list app Take a team task app with projects, tasks and comments. A natural layout is: ```kotlin val db = Firebase.firestore val comment = db.collection("projects").document("apollo") .collection("tasks").document("t42") .collection("comments").document("c1") // The same reference, built from a slash-separated path: val same = db.document("projects/apollo/tasks/t42/comments/c1") ``` A **subcollection** is a collection attached to one document. Here each task owns its `comments`. Subcollections can nest up to **100** levels deep. They keep the parent small: a task document does not grow with every comment, and comments can be paged and listened to separately. The general trade-off between embedding and referencing belongs to document modelling as a whole. What is specific to Firestore is the 1 MiB ceiling and the fact that every read downloads a whole document. ## Queries are shallow A Firestore query returns documents from **one collection** (or one collection group), and it returns **whole documents**. It never includes subcollection data. Reading `projects/apollo/tasks` returns task documents only. Each task's `comments` need their own query. To search across parents, use a **collection group query**: `db.collectionGroup("comments")` covers every collection whose ID is `comments`, wherever it sits. If that query filters or orders, it needs an index with **collection-group scope**, because automatic indexes are maintained only at collection scope by default. Whether a client may run the query at all is a matter for the security rules, covered with that topic. ## Deleting a parent does not cascade This is the behaviour interviewers probe most. The Firestore guide warns that **deleting a document does not delete its subcollections**. After deleting `projects/apollo`, the documents under `projects/apollo/tasks` and their comments still exist and stay readable by their full paths, even though the parent no longer does. To delete a project completely you must: 1. list the documents in each subcollection, at every level; 2. delete them, in reasonably sized batches; 3. delete the parent document. For large subtrees, run this from trusted server code. The guidance on batched writes recommends server client libraries for bulk data operations, not a mobile SDK. | Limit | Value | |---|---| | Document size | 1 MiB (1,048,576 bytes) | | Document name | 6 KiB | | Subcollection depth | 100 | | Map or array nesting in one document | 20 | | Document or collection ID | 1,500 bytes, no `/` | ## What a weak answer gets wrong - It assumes a delete cascades the way a file-system folder delete does. - It treats a collection as a table with columns that every document must match. - It expects a read of `tasks` to include each task's `comments`. - It grows one document forever, for example an unbounded comments array, until a write hits the 1 MiB limit. - It uses sequential IDs such as `task1`, `task2`. Firestore scatters automatic IDs to avoid hotspots, and the best-practices guide warns against monotonically increasing IDs.

  • Why store a task's comments in a subcollection rather than an array field on the task document?
    A read always downloads the whole document, and a document is capped at 1 MiB. An unbounded comment array makes every task read heavier and eventually fails the write. A `comments` subcollection keeps the task small, lets comments be paged with their own query and listener, and lets each comment be written without rewriting the task.
  • How do you find every comment one member wrote across all tasks and projects?
    Use a collection group query: `db.collectionGroup("comments").whereEqualTo("authorId", uid)`. It covers every collection whose ID is `comments`. Because it filters, it needs a single-field index with collection-group scope on `authorId`. Automatic indexes are maintained only at collection scope by default, so the first run fails with an error that links to creating the index.
  • Why prefer automatic document IDs over sequential IDs like task1, task2?
    Firestore allocates automatic IDs with a scatter algorithm, so new documents spread across the key range. Monotonically increasing IDs concentrate writes on lexicographically close documents. The best-practices guide calls this hotspotting, and it brings higher latency and contention errors at high write rates. Use `document()` with no argument, or `add()`, unless a natural key such as a user ID already exists.

  • Deleting a project document also deletes its tasks and comments subcollections.
  • A collection can hold fields of its own alongside its documents.
  • Reading the tasks collection also returns each task's comments subcollection.
  • A document can grow without limit as long as each field stays small.
  • You must create a collection explicitly before writing its first document.
open as a page

In Cloud Firestore on Android, why does whereEqualTo on assigneeId combined with orderBy on dueDate fail at runtime, and how do you fix it?

level: middleimportance: must knowfreq 75%

basics

~20 s

Firestore serves every query from an index, and automatic indexes cover single fields only. Equality on one field plus ordering by another needs a manual (composite) index. Until one exists the query fails with FAILED_PRECONDITION and a link to create it.

open as a page

In Cloud Firestore on Android, when do you use runTransaction instead of a WriteBatch, and what rules must a transaction function follow?

level: middleimportance: must knowfreq 66%

basics

~20 s

Use runTransaction when a write depends on data you read, such as claiming an unassigned task; use a WriteBatch for atomic writes that need no reads. A transaction function reads before writing, may rerun, must avoid side effects, and fails offline.

open as a page

In Cloud Firestore on Android, how do snapshot listener metadata flags reveal unsynced writes and cached data, and how is offline persistence configured?

level: middleimportance: should knowfreq 55%

basics

~10 s

Android snapshot listeners fire at once for local writes, flagged by hasPendingWrites, and mark cache-served data with isFromCache; metadata-only changes need MetadataChanges.INCLUDE. Persistence is on by default and tuned with setLocalCacheSettings and PersistentCacheSettings.

open as a page

How does Firebase Realtime Database differ from Cloud Firestore in data model, queries, offline behaviour and scale, and when would you still choose it?

level: middleimportance: should knowfreq 48%

basics

~20 s

Realtime 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.

open as a page

In a Firestore task app, every task change also updates an openTaskCount field on the project document; why does this degrade as the team grows, and what do you change?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Every task change funnels a write into one project document, and a single Firestore document sustains only a limited write rate, so contention brings latency, retries and errors. Use FieldValue.increment, shard the counter across documents, or compute it with count().

open as a page