What You'll Learn
- 1Separate Firestore Native mode from Datastore mode and pick the right one for a pipeline
- 2Model documents and subcollections so a single read returns everything a job needs
- 3Wire Firestore into a Dataflow pipeline with the FirestoreIO connectors
- 4Diagnose query limits, index errors, and per-document write throttling
Cloud Firestore and Datastore are one product family with two behavioural modes, and the distinction matters more to a data engineer than to an app developer. Native mode adds real-time listeners, offline client caches, and client SDK synchronization, all of which are built for mobile and web front ends. Datastore mode keeps the classic server-side API with strongly consistent ancestor queries and batch operations that suit backend jobs. Both store documents in collections, both expose the same structured query model, and both bill per entity read, write, and delete.
Firestore vs. Datastore
Choosing between them comes down to who reads the data and how. An application that renders a user profile wants a live subscription that pushes changes to the browser, which only Native mode provides. A nightly job that walks a collection, transforms rows, and writes results cares about sequential page tokens, batch writes, and predictable throughput, which is where Datastore mode is stronger. The two modes also differ in limits, and those limits are what usually decides the question in production.
| Behaviour | Firestore Native mode | Datastore mode |
|---|---|---|
| Primary client | Mobile and web SDKs | Server libraries, Dataflow |
| Listeners and offline cache | Supported | Not supported |
| Query consistency | Strongly consistent | Strongly consistent |
| Batch write limit | 500 operations | 500 operations |
| Typical write throttling | One write per second per document | Entity group throughput limits |
| Best fit for pipelines | Light, event-driven updates | Bulk reads and batch writes |
Comparison
Data Modeling for Data Engineering
A document is the unit of billing and the unit of consistency, so the shape of a document decides the cost of every read that touches it. Firestore charges one entity read for a document even if the query only projects two fields, which pushes designs toward denormalization: store what the reader needs in the same document rather than joining across collections at read time. The ceiling is one megabyte per document, and anything larger belongs in a subcollection, in Cloud Storage with a pointer, or split across records that are loaded in parallel.
Document Structure
from google.cloud import firestore
# Initialize Firestore client
db = firestore.Client()
# User profile document
user_ref = db.collection("users").document("user_123")
user_ref.set({
"user_id": "user_123",
"email": "[email protected]",
"profile": {
"name": "John Doe",
"age": 30,
"preferences": {
"theme": "dark",
"notifications": True
}
},
"events": [
{"event_type": "login", "timestamp": "2025-01-15T10:00:00Z"},
{"event_type": "purchase", "timestamp": "2025-01-15T10:05:00Z"}
],
"created_at": firestore.SERVER_TIMESTAMP,
"updated_at": firestore.SERVER_TIMESTAMP
})
# Subcollection for event history
events_ref = db.collection("users").document("user_123").collection("events")
events_ref.add({
"event_type": "login",
"timestamp": firestore.SERVER_TIMESTAMP,
"metadata": {
"device": "mobile",
"ip": "192.168.1.1"
}
})
Schema Design Patterns
Dataflow Integration
Two integration paths exist and they suit different cadences. The batch path is the managed export service, which writes a consistent snapshot of a collection into Cloud Storage in Firestore's own export format; the file is then loaded into BigQuery or opened directly by Spark. It is cheap, it does not touch live traffic, and it is the right answer for a nightly mirror. The streaming path is the Dataflow FirestoreIO connector, which reads the current contents or follows change streams and writes continuously.
Change streams deserve a specific warning: they emit the changes that happen after the stream starts, not the historical state of the collection. A pipeline that subscribes to a change stream over an empty table writes nothing, so a backfill must run first and the streaming job must be able to resume from a recorded timestamp. Reads are also metered, so a DoFn that fetches one document per element can quietly turn a transformation into the most expensive step in the job.
Reading from Firestore
import apache_beam as beam
from apache_beam.io.gcp.firestoreio import ReadFromFirestore
from apache_beam.options.pipeline_options import PipelineOptions
def run_firestore_to_bigquery():
"""Read from Firestore and write to BigQuery."""
pipeline_options = PipelineOptions([
'--project', 'my-project',
'--runner', 'DataflowRunner',
'--region', 'us-central1',
'--temp_location', 'gs://my-bucket/temp/'
])
with beam.Pipeline(options=pipeline_options) as pipeline:
# Read from Firestore
users = (
pipeline
| 'Read Firestore' >> ReadFromFirestore(
database='(default)',
collection='users'
)
)
# Transform and write to BigQuery
(
users
| 'Format' >> beam.Map(lambda x: {
'user_id': x['user_id'],
'name': x.get('profile', {}).get('name'),
'email': x.get('email'),
'created_at': str(x.get('created_at'))
})
| 'Write to BQ' >> beam.io.WriteToBigQuery(
'my-project:analytics.users',
schema='user_id:STRING,name:STRING,email:STRING,created_at:TIMESTAMP',
write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND
)
)
Writing to Firestore
from apache_beam.io.gcp.firestoreio import WriteToFirestore
# Write Dataflow results to Firestore
(
processed_data
| 'Write to Firestore' >> WriteToFirestore(
database='(default)',
collection='processed_events'
)
)
â¨
Best Practice: For data engineering pipelines, prefer Datastore mode over Firestore Native mode. Datastore provides better batch operations, higher throughput, and is designed for backend data workloads rather than real-time applications.
Indexing and Query Limits
Every Firestore query runs against an index, and the automatic single-field indexes cover only the simple cases. A query that filters on one field and orders by another, or that filters two fields with an inequality, needs a composite index declared ahead of time. The failure is visible rather than silent: the error message names the query and hands you a link that creates the missing index, so the workflow is to run the query once, follow the link, and wait for the index to build.
Three limits shape how pipelines are written. A query returns at most thirty documents in one page, which means every reader must chase the page token instead of assuming a collection fits in one call. Inequality filters are supported on at most one field, so range comparisons across two columns need restructuring or a second query. And a single document is capped at one megabyte, which pushes large payloads into subcollections.
// firestore.indexes.json - composite index for a pipeline query
{
"indexes": [
{
"collectionGroup": "events",
"queryScope": "COLLECTION",
"fields": [
{ "fieldPath": "event_type", "order": "ASCENDING" },
{ "fieldPath": "timestamp", "order": "DESCENDING" }
]
}
]
}
# Deploy the index definition and watch it build
gcloud firestore indexes composite create \
--collection-group=events \
--query-scope=COLLECTION \
--field-config field-path=event_type,order=ascending \
--field-config field-path=timestamp,order=descending
gcloud firestore indexes list --format="table(name,state)"
Reading the Bill: Entities, Not Bytes
Firestore does not meter bytes; it meters operations. A query that scans ten thousand documents and returns two hundred still charges for the documents examined, an entity read each, and a write charges per entity modified. That pricing model makes the expensive pattern obvious: filtering in application code after fetching everything. The filter belongs in the query, where the index does the pruning, because a server-side equality predicate on an indexed field avoids reading the rows it eliminates.
The second cost lever is batch size. A loop that issues one write per element pays a round trip and a per-operation charge for each row, while a batched write groups up to five hundred operations into one call. For pipelines that replay historical data, running a backfill through a batched writer rather than an individual one is often the difference between a job that costs dollars and one that costs hundreds.
Common Mistakes
Fetching a collection and filtering in Python
Fix: Push the predicate into the query so the index prunes unread documents and you stop paying entity reads for rows you discard.
Assuming a query returns the whole collection
Fix: Page through results with the page token; a single query response stops at thirty documents.
Following a change stream without a backfill
Fix: Load the historical state first, then start the stream and checkpoint the resume timestamp so no window is skipped.
Best Practices
- Denormalize so one document read serves the reader, and accept the write cost that duplication implies
- Deploy composite indexes from an index file rather than by following links in error messages
- Batch writes at a few hundred operations to cut round trips and per-operation overhead
- Keep pipeline documents under a megabyte and split large payloads into subcollections
Key Takeaways
- Native mode serves clients with listeners; Datastore mode serves pipelines with batch-friendly server APIs
- Billing is per entity operation, so query-side filtering and batched writes dominate cost control
- A query page holds thirty documents and inequality filters work on one field, so readers must paginate
- Change streams carry new events only, which makes a backfill a hard prerequisite for any streaming job
Interview Questions
Q1: When would you use Firestore instead of Bigtable?
Firestore fits document data with rich queries, real-time listeners, and moderate throughput such as user profiles and session state. Bigtable fits high-volume time series such as IoT and metrics, where row key design and scan patterns matter far more than ad hoc queries.
Q2: How do you export Firestore data into BigQuery?
Run the managed export service to write a consistent snapshot into Cloud Storage, then load that export into BigQuery with a load job. For continuous mirroring, run a Dataflow job over Firestore change streams and write upserts into a partitioned BigQuery table.
Q3: What are the main query limitations to design around?
Thirty documents per page, inequality filters on a single field, no server-side aggregation, and a one megabyte document cap. Composite indexes are required for multi-field queries, so index definitions belong in source control alongside the code that issues the queries.
Q4: Which mode should a data pipeline use, and why?
Datastore mode, because it targets server-side workloads with batch operations and stronger throughput characteristics, while Native mode is optimised for client listeners and offline caches that a pipeline never uses.
Common Interview Questions
Q1: When would you use Firestore vs. Bigtable?
Answer: Firestore is for document-based data with complex queries and real-time updates. Bigtable is for high-throughput time-series data (IoT, metrics, logs). Firestore is better for user profiles, session data, and moderate-throughput workloads. Bigtable is better for high-volume, low-latency analytics workloads.
Q2: How do you export Firestore data to BigQuery?
Answer: Use the Firestore export service to export to GCS, then load into BigQuery. For continuous syncing, use Dataflow with FirestoreIO. The export creates Firestore Datastore backup files that can be imported into BigQuery using the bq load command.
Q3: What are the query limitations of Firestore?
Answer: Firestore has limitations: maximum 1MB per document, 30 query results limit (can paginate), no inequality filters on multiple fields, limited aggregation options. For complex analytics, export data to BigQuery. For high-throughput reads/writes, consider Bigtable.
Q4: How do you optimize Firestore performance for data pipelines?
Answer: 1) Denormalize data to reduce document reads, 2) Use composite indexes for complex queries, 3) Batch writes instead of individual writes, 4) Use parallel reads for large collections, 5) Consider Datastore mode for backend data workloads.
Q5: What is the difference between Firestore Native and Datastore mode?
Answer: Firestore Native mode supports real-time listeners and offline sync, designed for mobile/web apps. Datastore mode provides traditional server-side operations with higher throughput, designed for backend/data engineering workloads. Datastore mode is recommended for data pipelines.