Firestore in Google Cloud: A Serverless Document Database That Updates Live
A complete, plain-English guide to Firestore: how documents and collections hold your data, how queries and indexes work, how real-time updates and offline support reach your apps, and how to design, secure and run it well.
Imagine a huge, tidy filing cabinet in the cloud. Each drawer is a collection, each folder inside is a document, and each folder holds named notes such as “name,” “city” or “last seen.” Anyone with the right key can open the drawer, read a folder, or change a note. The magic is that when one person changes a note, everyone who is looking at that folder sees the change a moment later, without pressing refresh. And if your phone loses signal on a train, the cabinet’s local copy keeps working and catches up when the network returns. That is Firestore.
In this guide we begin from zero. We assume you have never used a database, never heard of a document model, and never designed an index. Every new term is explained with what it is, why it exists, where it is used, an everyday comparison and a practical example. By the end you will understand how Firestore works inside, how data and queries flow through it, how to keep it secure, fast and affordable, and which mistakes to avoid.
1What Is Firestore?
Firestore is a fully managed, serverless document database from Google Cloud, built for web, mobile and server applications that need to scale and stay in sync.
The Short Definition
A database is an organised place where an application keeps its information so it can find it again later. Firestore is a database where information is stored as documents, which are small bundles of named fields, grouped into collections. It is called serverless because you never create, size, patch or restart any servers. You create a database, start reading and writing, and Google runs the machinery and scales it up and down for you.
Why It Exists
Traditional databases were designed for a world where one big server sat in one room and a few applications talked to it. Modern apps are different. Millions of phones and browsers connect at once. Users expect screens to update live, like a chat that shows a new message instantly. Teams do not want to spend their days tuning servers. Firestore was built for this world: it scales automatically, keeps data in sync across devices, and can be reached safely straight from client apps when you add the right rules.
Where It Is Used
Firestore is used in chat and collaboration apps, shopping carts and product catalogues, user profiles and settings, game state and leaderboards, task and booking systems, internet-of-things dashboards, and the back ends of many mobile apps. It suits data that is naturally shaped like records with fields, where reads and writes are frequent but each one is small.
A shared whiteboard in a busy office. Every team has its own section with sticky notes. When anyone edits a note, everybody looking at the board sees it change immediately. There is no need to send the board around by email, and no one needs to own the wall or repaint it when the office grows.
Firestore belongs to the family of NoSQL databases. “NoSQL” simply means the data is not forced into the rigid rows-and-columns tables of the older relational style. It does not mean “no rules” or “no structure.” It means the structure is more flexible.
2Document Databases versus Table Databases
To use Firestore well, first see how thinking in documents differs from thinking in tables.
The Table Way
In a relational database, data lives in tables made of rows and columns, like a spreadsheet. Every row in a table has the same columns. If a customer has several orders, the orders go into a separate table, and a “join” combines the two when you ask a question. This is powerful and precise, and it has served the world for decades.
The Document Way
In a document database, one record is one document: a self-contained bundle of fields. Documents in the same collection do not have to share the same fields. A document can hold simple values such as text, numbers and dates, and also richer values such as lists and small nested groups of fields. Related data is often stored together or placed under the parent document, so that one read gives you everything a screen needs.
| Question | Relational database | Firestore document database |
|---|---|---|
| Basic unit | A row in a table | A document in a collection |
| Structure of records | Same columns for every row | Flexible fields per document |
| Combining related data | Joins at query time | Storing related data together or nearby |
| Scaling style | Usually scale up one big server | Scales out automatically |
| Typical strength | Complex reporting and ad-hoc analysis | Fast app reads and writes at large scale |
Tables are like a library with separate catalogue cards for books, authors and borrowers, and a librarian who cross-references them each time you ask. A document database is like a personal folder per borrower that already contains their borrowed titles, due dates and notes. Opening one folder tells you everything about that person quickly.
Practical Example: A User Profile Screen
A profile screen needs a name, a photo link, a few settings and a short list of favourite items. In a document model, one document holds all of that, so the app reads it in a single step instead of joining several tables.
“Document databases are only for simple apps.” Not true. They power very large systems. But they ask you to design around the questions your app asks, rather than around neat tables. That design habit is the most important skill in this guide.
3Core Concepts and Vocabulary
Eight words unlock almost every document and conversation about Firestore.
Database
The top-level container in your project. A project can hold more than one database, each with its own location, edition and settings.
Collection
A named group of documents, such as “customers” or “orders.” Collections hold only documents and have no fields of their own.
Document
One record made of named fields. Each document has a unique identifier within its collection.
Field
A named value inside a document, such as a string, number, true or false, date, location, list or nested group.
Subcollection
A collection that lives under a particular document, such as the messages inside one chat room.
Index
A sorted lookup structure that lets queries find matching documents fast without scanning everything.
Listener
A live subscription in the app. When the watched data changes, the app is told right away.
Security Rules
Written conditions that decide which signed-in users may read or write which data when apps connect through the client SDKs.
A school office. The database is the whole office. A collection is a cabinet drawer labelled “Students.” A document is one student’s folder. A field is a line on the form inside, like “grade.” A subcollection is the folder of attendance sheets kept inside each student’s folder. An index is the alphabetical card catalogue. A listener is the secretary who calls you whenever a folder changes. Security rules are the office policy on who may open which drawer.
How a Path Looks
Every document has a path made of alternating collection and document names, such as a collection of rooms, then a room, then its collection of messages, then one message. Paths always alternate: collection, document, collection, document. A path that ends on a collection names a group of documents, and a path that ends on a document names exactly one record.
flowchart TD
DB["Database"] --> C1["Collection: rooms"]
C1 --> D1["Document: room A"]
C1 --> D2["Document: room B"]
D1 --> F1["Fields: name, topic, created"]
D1 --> SC["Subcollection: messages"]
SC --> M1["Document: message 1"]
SC --> M2["Document: message 2"]
M1 --> F2["Fields: text, sender, time"]
4Editions and Modes: Standard and Enterprise
Firestore comes in two editions and, within them, different ways of talking to the data. Choosing early matters, because some choices cannot be changed later.
Two Editions
Firestore is offered in a Standard edition and an Enterprise edition. Both are managed, serverless databases that share many abilities. They differ in the query engine, indexing, performance, document size limits and the way charges are counted. Both editions can exist in the same project, and data is compatible between them, so you can try one beside the other.
| Area | Standard | Enterprise |
|---|---|---|
| Query engine | Basic engine for simple comparisons and matches; every query needs an index that covers it | Advanced engine with a very large set of stages and operators; queries can run with or without an index |
| Indexing | Automatic, basic indexing on all fields | Customisable, including unique, dense and sparse indexes |
| Document size | 1 MiB | 1 MiB in Native mode, 16 MiB with MongoDB compatibility |
| MongoDB compatibility | Not supported | Supported |
| Storage | Hybrid of solid-state and hard-disk | Solid-state |
| Performance | Good | Designed for the best performance, especially at the slowest tail of requests, and handles bursts at a higher rate |
| Pricing unit | Documents read and written, plus storage and network egress | Chunks of bytes read and written, plus storage and network egress |
Shared Abilities
Client SDKs with Sync
Native mode SDKs for servers, web and mobile, with real-time sync and offline support.
Triggers
Change notifications that can start your own code when documents are created, changed or deleted.
Observability
Cloud Monitoring, query explain and insight tools, and a database fleet view to understand health and performance.
Backups and Recovery
Scheduled backups and point-in-time recovery to restore data after mistakes.
Encryption Choices
Google-managed encryption keys by default, with customer-managed keys available.
Discounts and Free Use
Committed use discounts for one- or three-year terms, and a daily free usage allowance to get started.
Choosing a Data Access Mode
When you create a database you also choose how applications talk to it. Standard supports the Native mode, which has the rich client SDKs with real-time sync, and the Datastore mode, which is an older style aimed at server-side applications. Enterprise supports Native mode and a MongoDB-compatible mode. This choice is made at creation and cannot be changed afterwards, so decide carefully.
Two models of the same delivery van. The standard model is reliable, cheaper to run and handles everyday jobs very well. The enterprise model has a stronger engine and more flexible cargo options for tougher routes. Both come from the same factory and carry the same kind of parcels, but you pick the model and the steering style when you buy, not later.
Features, limits and pricing for editions change over time. Read the current editions overview in Google Cloud’s documentation before deciding, and try a small test database in each edition against your real queries.
5Architecture and Internal Working
You never see the machines, but knowing the shape of what runs underneath helps you make better design choices.
The Layers
At the top are your clients: phones, browsers and servers using Google’s libraries. Next is the Firestore service, a managed front end that authenticates requests, applies security rules where relevant, routes each request, and coordinates transactions. Below it is a distributed storage layer that stores your documents and indexes in several places at once, so that the loss of a machine, or even a whole building, does not lose data. Google handles splitting data into pieces, moving pieces between machines and balancing load as you grow.
flowchart TD
CL["Clients: mobile, web, servers"] --> FE["Firestore front end"]
FE --> AUTH["Identity and rules check"]
AUTH --> TX["Transaction and query coordination"]
TX --> IDX["Index storage"]
TX --> DOC["Document storage"]
DOC --> REP["Replicated across zones or regions"]
IDX --> REP
FE --> LIS["Real-time listener service"]
LIS --> CL
Replication and Durability
Each write is stored in more than one place before Firestore tells your app it succeeded. This replication is why the database survives hardware failure. It also means a write is a small distributed agreement, which explains why there is a limit on how fast a single document can be updated over time.
A notary who will not stamp a contract until several witnesses in separate offices have each signed their copy. It takes a moment longer than scribbling on one page, but when the stamp lands, the agreement survives a fire in any single office.
Strong Consistency
Consistency is the promise about what you see after a write. Firestore gives strong consistency for reads: once a write has succeeded, any later read sees it. This makes the database simpler to reason about than systems that promise only “eventually.” Your app does not need extra tricks to avoid reading stale data from the server.
Automatic Scaling and Splitting
As data and traffic grow, Firestore automatically splits ranges of data across more machines. This works best when traffic is spread across many documents. If every write targets the same narrow range, such as keys that increase one by one, a single piece becomes the bottleneck. This is called a hotspot, and we return to it in the design chapters.
Firestore scales by spreading work. Your job as a designer is to avoid piling all the work onto one document or one narrow range of keys.
6Data Model: Documents, Types and Limits
What can a document hold, and how should you shape it?
Field Types
Text, Numbers, True or False
The basics. Numbers can be whole or decimal. True or false values are ideal for flags such as “published.”
Timestamps
Exact points in time. Prefer these over text dates so sorting and range queries work correctly.
Geographic Points
A latitude and longitude pair, handy for storing locations of shops or users.
References
A pointer to another document, useful for relating records without copying them.
Maps
Nested groups of fields inside a document, for tidy structure such as an address with street and city.
Arrays
Ordered lists of values, good for small sets such as tags. Avoid very large or fast-growing arrays.
Size Limits
In the Standard edition, and in Enterprise’s Native mode, a document may be at most about one mebibyte in size. That is room for a lot of text, but not for images or videos. Store large files in a file storage service such as Cloud Storage and keep only the file’s path in the document. Very large documents are slow to read, cost more per read and, because they are read whole, waste effort when a screen needs only two fields.
Update Speed of a Single Document
Because writes are replicated, a single document can be updated only at a limited sustained rate, roughly once per second on average. For a counter or a “likes” total that many people change at once, a single document will become a bottleneck. We will see a technique called sharded counters for this later.
Flexible Fields, But Be Consistent
Documents in one collection may have different fields, but your app code and your queries will be happier if documents of the same kind follow the same shape. Treat the flexibility as a way to evolve data gently over time, such as adding a new optional field, not as permission for chaos.
A form with printed boxes. You may leave some boxes empty or add a notes section for special cases, but if every clerk invented their own layout, nobody could find anything. Agree on the common layout and allow small, deliberate variations.
Storing dates as text like “03-11-2026.” Text sorts alphabetically, so the days of one month can be ordered before the days of another. Use real timestamp fields.
7Reading and Writing Data
Everything an app does comes down to a few kinds of operation.
The Basic Operations
Create
Add a new document, either with an identifier you choose or with one Firestore generates for you automatically.
Read One
Fetch a single document by its path. This is the fastest and cheapest kind of read.
Query Many
Ask for all documents in a collection that match conditions, optionally sorted and limited in number.
Update
Change specific fields of a document without rewriting the whole thing, or replace the whole document.
Delete
Remove a document. Note that deleting a document does not automatically delete its subcollections.
Batched Writes and Transactions
Sometimes several changes must succeed or fail together. Moving money between two accounts is the classic case: subtracting from one without adding to the other would be a disaster. Firestore offers two tools for this.
| Tool | What it does | Use when |
|---|---|---|
| Batched write | Groups several writes into one all-or-nothing package | You know all the changes in advance and need them to be atomic |
| Transaction | Reads some data, then writes based on what it read, all as one atomic unit; retries if another change interferes | The new value depends on the current value, such as decrementing stock |
A bank counter that processes a transfer slip. Either both the debit and the credit are stamped, or neither is. If another clerk changes the account while yours is in progress, the counter hands your slip back and asks you to try again with the fresh balance.
Pagination
A screen rarely needs every result at once. Pagination fetches results in pages. The recommended approach is to remember the last document of the current page and ask for the next set starting after it, using a cursor. Skipping a number of results with an offset still counts and charges for the skipped documents, so cursors are both faster and cheaper.
sequenceDiagram
participant A as App
participant F as Firestore
A->>F: Query first 20 messages by time
F-->>A: Page 1 and last document marker
A->>F: Query next 20 after the marker
F-->>A: Page 2 and new marker
A->>F: Continue as user scrolls
Read a document by its path whenever you can. A direct read is simpler and cheaper than a query that has to find the document through an index.
8Queries and Indexes
Firestore is fast because every query is answered from sorted indexes rather than by scanning data.
What an Index Is
An index is like the index at the back of a book. Instead of reading every page to find a topic, you jump to the topic in the index and follow it to the right pages. A database index keeps a sorted list of field values with pointers to the documents that contain them, so a query can jump straight to the matching range.
Single-Field and Composite Indexes
Single-Field Index
Covers one field. In the Standard edition these are created automatically for fields, so simple queries work out of the box.
Composite Index
Covers several fields in a specific order. Needed for queries that filter on one field and sort on another, or combine several conditions.
Exemptions
You may switch off automatic indexing for fields you never query, such as large text, which saves storage and write cost.
Customisable Indexes
The Enterprise edition allows more kinds, such as unique, dense and sparse indexes, and can run queries without a covering index.
The Golden Rule of Queries in Standard
In the Standard edition, every query must be answerable from an index. The database never scans through documents to look for matches. This is why queries stay fast no matter how large the collection grows: the cost of a query depends on how many results it returns, not on how much total data you have. It also means that if you want a new kind of query, you may need to create a new index first, and the error message will usually offer a link to create it.
A library with only card catalogues and no permission to wander the shelves. If a catalogue exists for “author then year,” you find books instantly. If you ask for “year then colour of the cover” and no such catalogue exists, the librarian says “we need to make that catalogue first.” Once made, the answer is instant.
Typical Query Powers
Filters
Equality and range conditions on fields, membership checks against a list of values, and checks for whether an array contains a value.
Sorting and Limits
Order results by a field and take only the first few, such as the ten newest items.
Collection Group Queries
Query every collection that shares the same name wherever it sits in the tree, such as all “reviews” subcollections across all products.
Aggregations
Count, sum and average results on the server side without downloading each document, which saves bandwidth and reads.
What Queries Cannot Do Well
Classic Firestore queries do not perform joins across collections, free-text search inside words, or arbitrary reporting across huge data. For text search, many teams add a dedicated search service. For reporting, they export data to an analytics warehouse. The Enterprise edition lists text and geospatial search among newer capabilities that may be in preview, so check the current status before relying on them.
Designing the data first and discovering the queries later. In a document database the questions your screens ask should shape how data is stored, which fields are indexed and which composite indexes exist.
9Real-Time Updates and Offline Support
This is the feature that makes Firestore feel magical in apps.
Real-Time Listeners
Instead of asking “has anything changed?” again and again, an app can attach a listener to a document or to the results of a query. Firestore sends the current data right away, and then sends small updates whenever something changes. The app simply redraws what changed. A chat screen, a live scoreboard and a shared to-do list all work this way.
Subscribing to a news alert instead of walking to the newsstand every five minutes. The paper is delivered when something new is printed, and only the new page arrives, not the whole newspaper again.
Offline Persistence
The client SDKs for mobile and web can keep a local cache of the data your app has used. When the network drops, reads are served from the cache and writes are queued on the device. When the connection returns, queued writes are sent to the server and the cache is refreshed. Users see the app keep working, and developers write the same code online and offline.
The app attaches a listener
It asks to be told about changes to a document or query.
Initial data arrives
The current results are delivered and stored in the local cache.
The network drops
The app keeps showing cached data and accepts new writes, marking them as pending.
The user makes changes offline
The local view updates immediately, so the app feels instant.
The connection returns
Pending writes are sent to the server, and the latest server data flows back through the listener.
Conflicts are resolved
Generally the most recent write wins. Use transactions or careful design where two people may edit the same field at once.
Attach listeners only where a screen is visible and remove them when it is closed. Each change delivered counts as a read, so forgotten listeners can quietly add to the bill.
Listening to a huge collection when the screen only needs ten items. Every change to any matching document triggers an update. Narrow the query with filters and limits.
10Data Modelling: Designing for Your Questions
Good modelling is what separates a fast, cheap app from a slow, expensive one.
Start from the Screens
List every screen of your app and the data each one shows. Then decide how to store the data so that each screen needs only one or two reads. This is the reverse of how table databases are usually taught, where you first model the world neatly and then write queries to rebuild each screen.
Three Ways to Store Related Data
| Approach | How it looks | Good for | Watch out for |
|---|---|---|---|
| Nested in the same document | Small groups of fields or short lists inside the parent | Data always read with its parent and small in size | Document size limit and update rate limit |
| Subcollection | Child documents beneath the parent | Lists that can grow, such as messages or comments | Deleting the parent leaves children behind |
| Separate top-level collection with references | Related documents in their own collection, linked by identifiers | Data queried on its own across many parents | Extra reads to assemble related data |
Denormalisation: Copying on Purpose
In table databases, copying the same fact in many places is considered a bad habit called duplication. In Firestore it is often a deliberate technique. If a comment list screen needs the author’s name and photo, you may copy those two fields into each comment so that showing the list needs one query instead of one query plus a lookup per author. The price is that when the author changes their name, you may need to update the copies, often with a background function.
Printing the shop’s phone number on every receipt instead of asking customers to look it up in the directory. It is quicker for the customer. If the number ever changes, you reprint the receipts that matter, and you accept that very old ones show the old number.
Choosing What to Duplicate
Duplicate Data That Rarely Changes
Names, titles, categories and small labels are cheap to copy and rarely need updating.
Do Not Duplicate Fast-Changing Data
Prices, stock levels and live counters change often. Keep one authoritative copy and read it when needed.
Keep a Source of Truth
Decide which copy is the master. Copies are views of it, and a function can refresh them.
flowchart LR
S1["Screen: product page"] --> P["Product document with embedded summary"]
S2["Screen: review list"] --> R["Reviews subcollection with author name copied"]
S3["Screen: seller dashboard"] --> Q["Collection group query across reviews"]
U["Author renames profile"] --> FN["Background function"]
FN --> R
Document Identifiers
You can choose your own document identifiers or let Firestore generate random ones. Random identifiers spread writes evenly across the database and are almost always the safest choice. Identifiers that increase steadily, such as simple counters or timestamps at the start of the name, tend to send all new writes to the same narrow range and can create hotspots at high volume.
Using sequence numbers or timestamps as document identifiers in a high-traffic collection. Use random identifiers and store the time in a separate field that you can sort on.
11Security: Rules, IAM and Defence in Depth
Firestore can be reached straight from a phone, which is wonderful and dangerous. Security is not optional.
Two Ways In, Two Systems
| Entry route | Used by | What controls access |
|---|---|---|
| Mobile and web client libraries | Apps on phones and browsers | Firebase security rules, using the signed-in identity |
| Server client libraries and APIs | Back-end services and tools | Google Cloud IAM permissions on a service account |
This split is crucial. Security rules protect requests that come from client libraries. Server libraries using a service account are controlled by IAM instead and are not checked by the rules. So a leaked service account key is far more dangerous than a flaw in a single rule.
Security Rules
Rules are short written conditions stored with the database. They can look at who is signed in, which path is being touched, the data already stored, the data being written, and even other documents. The default stance is “deny unless allowed.” Common rule ideas include letting a user read and write only their own profile, letting members of a group read group data, and requiring that a new document has certain fields with valid values.
Owner-Only Data
A user may read and change only documents that carry their own identifier.
Role-Based Access
Users with a special label, such as admin or moderator, get extra permissions.
Field Validation
Writes must contain required fields of the right type and sensible values, such as a rating between one and five.
Immutable Records
Some documents, such as receipts, may be created but never changed or deleted from the client.
Membership Checks
A rule looks up a membership document to check whether the user belongs to a team before reading team data.
A doorman for the public entrance and a separate set of keys for the staff entrance. The doorman checks each visitor’s pass against a list. Staff with keys walk in through the back without the doorman. If a key is lost, the doorman cannot help, so staff keys must be guarded more tightly than visitor rules.
Layers of Defence
Authentication
Require sign-in so rules know who is asking. Allow anonymous access only on purpose.
Rules and Validation
Write narrow rules and validate the shape of data on write.
App Check
Helps confirm requests come from your genuine app, reducing scripted abuse.
Least-Privilege IAM
Give each service account only the roles it needs, and avoid long-lived keys where possible.
Encryption
Data is encrypted in transit and at rest. For stricter rules, customer-managed keys can be used.
Audit Logs
Turn on data-access audit logging where compliance demands it, to know who read or changed what.
Shipping with open or time-limited test rules left over from early development. Many exposed databases come from rules that were meant to be temporary. Treat rule writing as part of every feature.
12Triggers, Functions and Integrations
Data changes are often just the start of something that needs to happen next.
Change-Based Triggers
Firestore can announce events when documents are created, updated or deleted. You attach small pieces of server code, such as Cloud Functions, that run automatically in response. This is called event-driven design, and it lets you add behaviour without changing the app.
flowchart LR
W["Document written"] --> EV["Change event"]
EV --> F1["Function: send notification"]
EV --> F2["Function: update copies"]
EV --> F3["Function: update counters"]
EV --> F4["Function: sync to search or analytics"]
Everyday Jobs for Triggers
Notifications
Send a push message when a new chat message or order status change appears.
Maintaining Copies
When a profile name changes, update the copies stored in comments or posts.
Aggregates
Maintain totals and summaries in a small document so screens do not have to read thousands of records.
Search and Analytics Sync
Copy changes into a search service for text search or into an analytics warehouse for reporting.
Cleanup
When a user deletes their account, remove their documents, including subcollections, which are not removed automatically with the parent.
Other Google Cloud Partners
Cloud Storage
Holds large files; Firestore holds their paths and descriptions.
BigQuery
For analysis and reporting across large amounts of data, often fed by exports or streaming copies.
Pub/Sub
Carries messages between systems when changes need to reach several consumers reliably.
Cloud Run and Functions
Run your server code for triggers, schedules and back-end logic.
A function that writes to the same document that triggers it, producing an endless loop of events and a surprise bill. Check whether the change really needs another write, and make functions safe to run twice.
13Performance, Hotspots and Scaling Habits
Firestore scales a long way on its own, but a few habits keep it smooth.
Spread the Load
Because Firestore divides data into ranges, work that is evenly spread scales best. Avoid steady streams of writes to documents whose identifiers or indexed values sort next to each other, and avoid a single document that every user updates constantly.
Ramp Up Gradually
When you suddenly send very heavy traffic to a new collection, the database needs a little time to split and rebalance data. Google’s guidance for sudden new heavy workloads is to increase traffic gradually, following a rule of thumb of starting modestly and raising the rate in steady steps. Check the current best-practice page for exact numbers, since the guidance is updated over time.
Sharded Counters
A single document can handle only a limited sustained update rate, so a popular “likes” counter can choke. The fix is to split one counter into several small counter documents, called shards. Each update picks one shard at random, and to show the total, you add up the shards. Writes spread out, and reading a handful of shards is still cheap.
flowchart TD
U1["Likes from many users"] --> R["Pick a shard at random"]
R --> S1["Shard 1"]
R --> S2["Shard 2"]
R --> S3["Shard 3"]
R --> S4["Shard 4"]
S1 --> T["Add shards to show total"]
S2 --> T
S3 --> T
S4 --> T
A stadium with one ticket window versus ten. Fans queue randomly at any window, and at the end the manager adds up the sales from all ten tills. No single clerk becomes the bottleneck.
Keep Reads Small and Few
Fetch only what you need
Use limits and filters so screens load a page, not a whole collection.
Use cursors for paging
Avoid offsets, which still read skipped documents.
Keep documents lean
Move bulky or rarely used data to a subcollection or another store.
Use the cache
Let client libraries serve repeat reads from the local cache where fresh data is not required.
Use server-side aggregation
Ask for counts and sums computed on the server instead of downloading documents to add them up.
Use the query explain and query insight tools to see how queries run and which are slow. Measure first, then change the design.
14Locations, Availability and Resilience
Where you place the database decides speed, resilience and sometimes legal compliance.
Regional and Multi-Regional Locations
When creating a database you choose a location. A regional location keeps data in several zones inside one region, which protects against the failure of a building and usually costs less and serves nearby users with low delay. A multi-regional location spreads data across several regions, which protects against the loss of an entire region and offers higher availability, at a higher price. The location cannot be changed later, so choose with care.
| Choice | Strength | Trade-off | Typical reason |
|---|---|---|---|
| Regional | Lower cost, low delay near the region | An entire-region outage affects you | Most apps with users concentrated in one area |
| Multi-regional | Survives loss of a region, higher availability | Higher cost, possibly more write delay | Critical apps with global users |
Match Location to Your Compute
Place the database in the same region as your servers and functions that use it most. Every round trip across oceans adds delay. For legal reasons, confirm that the chosen location satisfies the rules about where your users’ data may be stored.
Deciding where to keep an emergency generator. One in the building’s basement is cheap and handy, but a flood can take it out with the rest of the building. A second generator in another town costs more, yet the power stays on whatever happens locally.
High Availability Is Built In
Because data is replicated and managed for you, there is no failover to configure. Google publishes availability commitments for the service, which differ by location type. Read the current service level agreement to see the figures that apply to your choice.
Choosing a location by guess and later learning that users are on another continent or a rule demands local storage. Moving means creating a new database and migrating data.
15Backup, Recovery and Data Lifecycle
Replication keeps you safe from hardware failure. It does not protect you from your own mistakes.
Three Safety Nets
Scheduled Backups
Automatic backups taken on a schedule you set, kept for a chosen retention period, and restorable into a database.
Point-in-Time Recovery
Lets you read or restore data as it was at an earlier moment within a recent window, useful after an accidental bulk delete.
Exports
Copies of data written to storage, handy for archives, analytics and moving data between projects.
Delete Protection
A setting that prevents the whole database from being deleted by accident.
A video game with autosave, manual save slots and a rewind button. Autosave protects against crashes. Save slots let you return to a known good time. The rewind button undoes a mistake you just made. You want all three in a game you cannot afford to lose.
Automatic Expiry of Old Data
Time-to-live policies let you mark a date field as an expiry time. Documents whose time has passed are deleted automatically in the background. This is perfect for sessions, temporary codes, logs and caches, and it saves both storage cost and the effort of writing clean-up jobs.
Deleting Properly
Deleting a document does not delete its subcollections. For account deletion and privacy requests, plan a proper clean-up that visits the document and everything beneath it, including copies and exports. Test it before you need it.
Decide recovery goals
How much recent data can you afford to lose, and how fast must you recover?
Turn on backups and recovery
Set schedules, retention and point-in-time recovery as the goals require.
Protect against deletion
Enable database delete protection and restrict who may remove backups.
Practise a restore
Restore into a test database, time it and write down the steps.
A backup you have never restored is only a hope. Schedule a restore rehearsal at least once and after major changes to your data design.
16Monitoring, Logging and Observability
A database that quietly runs for months deserves a few good instruments.
| Signal | Question it answers | Typical action |
|---|---|---|
| Read, write and delete counts | Is traffic normal, and what is it costing? | Find chatty screens or runaway loops |
| Request latency | Is the database responding quickly? | Investigate hotspots or heavy queries |
| Error and denial rates | Are users blocked or attackers probing? | Fix rules or index problems |
| Active listeners and connections | How many live subscriptions are open? | Close unused listeners |
| Storage size | How fast is data growing? | Use expiry policies and index exemptions |
| Slow queries | Which queries are inefficient? | Add indexes or reshape data |
The Tools
Cloud Monitoring charts usage and lets you set alerts. Query insights and query explain show how queries behave. A database fleet view helps teams with many databases compare health. Cloud Logging and audit logs record administrative actions and, if you enable them, data access. A simple dashboard with reads, writes, errors, latency and storage, plus a few alerts, covers most needs.
A car’s dashboard. You do not stare at each engine part, but a few gauges and warning lights tell you early that fuel is low or the engine runs hot, long before the car stops.
Set a billing budget alert on the project on day one. A bug that reads the same collection in a loop can create a large bill within hours, and an alert is the fastest way to notice.
17Cost and Pricing
Firestore bills for what you use, so understanding the meter lets you shape the bill.
What You Pay For
In the Standard edition, operations are counted by documents read and written. In the Enterprise edition, they are counted in chunks of bytes read and written. Storage includes the data and the index entries that support queries. Both editions offer committed use discounts for longer terms and a daily free usage allowance. Exact prices vary by edition and location and change over time, so always check the current pricing page.
What Drives Cost Up
Chatty Screens
A screen that reads hundreds of documents to show twenty items multiplies the bill with every visitor.
Listeners Left On
Every document change delivered to a listener counts as a read, and forgotten listeners keep counting.
Over-Indexing
Every indexed field adds storage and extra work on each write. Index only what you query.
Offset Paging
Skipped documents are still charged. Cursor-based paging avoids that.
Big Documents Read Whole
Reading a large document to use two fields wastes money. Keep documents lean.
Trigger Loops
Functions that rewrite the data that woke them up can multiply operations enormously.
Ways to Reduce Cost
Model for few reads per screen
Embed or copy small pieces of data so screens need one or two reads.
Use caching and limits
Serve repeat views from the local cache and fetch small pages.
Exempt fields from indexing
Switch off indexes for large or never-queried fields.
Expire old data
Use time-to-live policies for temporary documents.
Consider commitments
For steady, predictable use, discounts for one or three year commitments can lower the unit price.
Comparing prices of document databases to table databases by storage alone. The real cost driver is how many operations your app performs, so cost is mostly a design outcome.
18Advantages, Disadvantages and Trade-offs
Every design has a price. Here is an honest balance sheet.
Advantages
- Serverless, with scaling and maintenance handled for you
- Real-time listeners and offline support in client libraries
- Strong consistency, simple to reason about
- Replicated storage with built-in availability
- Direct client access protected by security rules
- Backups, point-in-time recovery and expiry policies available
Disadvantages / Trade-offs
- No joins; related data needs thoughtful modelling and copying
- Every query in Standard needs a supporting index
- Not suited to heavy reporting or ad-hoc analysis
- A single document has a limited sustained write rate
- Cost follows operations, so inefficient screens are expensive
- Database location and mode cannot be changed after creation
The Decision in One Sentence
Choose Firestore when your app needs a scalable, flexible database for record-like data with live updates and offline support, and keep heavy analysis and complex relational work in other systems built for them.
19Comparing Firestore with Other Databases
Google Cloud offers many databases. Choose by the shape of your data and your questions.
| Option | Best known for | Choose it when |
|---|---|---|
| Firestore | Serverless document database with live sync and offline support | Apps need flexible records, real-time updates and automatic scaling |
| Cloud SQL and AlloyDB | Managed relational databases | You need joins, strict schemas and familiar SQL |
| Spanner | Globally distributed relational database with strong consistency | You need relational features at very large, global scale |
| Bigtable | Wide-column store for huge, high-speed workloads | You have massive time-series or analytical key-value data |
| BigQuery | Analytics data warehouse | You analyse large datasets with SQL, not serve app screens |
| Memorystore | In-memory cache | You need very fast temporary data lookups |
| Realtime Database | Firebase’s original JSON tree database with live sync | Very simple, low-latency state sync with a small tree of data |
A Simple Way to Decide
Ask four questions. First, is the data naturally record-shaped and driven by screens? If yes, Firestore is a candidate. Second, do I need complex joins and constraints? If yes, a relational database is likelier. Third, is the main job analysis over huge data? Use a warehouse. Fourth, do I need extreme global scale with relational rules? Look at Spanner.
Choosing containers. Firestore is a set of labelled folders that update live. A relational database is a well-organised ledger with cross-references. A warehouse like BigQuery is the big archive room where analysts spread out papers to study. A cache is the sticky note on your monitor for things you need constantly.
Many systems use several databases together: Firestore for the live app data, a warehouse for analysis, and a search service for text search. Pick each for its strength and connect them with triggers and exports.
20Design Patterns That Work
A pattern is a proven shape for a solution. These appear again and again in healthy Firestore apps.
Pattern: Model by Screen
Design each document so that a screen needs one or two reads. Embed or copy the small pieces that the screen shows together.
Pattern: Subcollection for Growing Lists
Put messages, comments and events into a subcollection under their parent so the parent stays small and the list can grow without limit.
Pattern: Summary Document
Keep a small document of totals and latest items updated by triggers, so dashboards read one document instead of thousands.
Pattern: Sharded Counters
Split hot counters into several shard documents and add them up when reading.
Pattern: Random Identifiers
Let Firestore generate identifiers to spread writes, and keep sortable data in separate fields.
Pattern: Owner-Scoped Documents
Store each user’s private data under their own path or tag it with their identifier, so rules stay short and obvious.
Pattern: Server-Side Validation for Sensitive Actions
Do sensitive operations, such as payments or grants of roles, in trusted server code, and let clients only request them.
Pattern: Soft Delete and Expiry
Mark documents as deleted first, then remove them later with expiry policies, so mistakes can be undone.
flowchart LR
APP["Client app"] --> RULES["Security rules"]
RULES --> FS["Firestore"]
FS --> TRG["Triggers"]
TRG --> SUM["Summary documents"]
TRG --> CPY["Refresh copies"]
TRG --> EXP["Export to analytics"]
APP --> SRV["Trusted server for sensitive actions"]
SRV --> FS
21Anti-Patterns to Avoid
An anti-pattern looks like a good idea but quietly causes trouble. These are the most common.
Problem
Modelling data like relational tables and joining it in the app with many reads.
Why It’s Harmful
Each screen triggers dozens of reads, which is slow and expensive, and it ignores the strengths of a document database.
Correct Approach
Start from the screens, embed or copy the data they show together, and keep copies fresh with triggers.
Problem
One giant document holding an ever-growing list or a global counter.
Why It’s Harmful
It hits the size limit and the update-rate limit, and every read pulls the whole thing.
Correct Approach
Use subcollections for growing lists and sharded counters for hot totals.
Problem
Sequential document identifiers or timestamps as identifiers in busy collections.
Why It’s Harmful
New writes land on the same narrow range and create hotspots, limiting throughput.
Correct Approach
Use random identifiers, and store time in a separate indexed field.
Problem
Open or test-style security rules in production.
Why It’s Harmful
Anyone may read, change or delete your data, or flood it with junk at your cost.
Correct Approach
Start from deny-all, write narrow rules and validation, and review rules before each release.
Problem
Listening to entire large collections from screens that show only a few items.
Why It’s Harmful
Every change in any matching document is delivered and billed as a read.
Correct Approach
Add filters and limits, and detach listeners when a screen closes.
Problem
Using Firestore for heavy reporting and ad-hoc analysis.
Correct Approach
Export or stream data to an analytics warehouse for reporting.
Why It’s Harmful
Scanning large amounts of documents is slow and expensive here, because the database is designed for fast, small, indexed reads.
Problem
No backups, no budget alerts and no delete protection.
Why It’s Harmful
An accidental bulk delete or runaway loop can destroy data or create a large bill before anyone notices.
Correct Approach
Turn on scheduled backups and point-in-time recovery, enable delete protection, and set budget alerts from day one.
22Best Practices and Common Mistakes
A checklist of habits shared by teams that run Firestore calmly.
Do This
- List the screens and queries before designing data
- Use random identifiers and real timestamp fields
- Keep documents lean and growing lists in subcollections
- Write narrow security rules with validation
- Use least-privilege service accounts for servers
- Detach listeners and use cursors for paging
- Turn on backups, recovery and delete protection
- Set budget alerts and watch usage dashboards
Avoid This
- Shipping with open or temporary rules
- Storing dates as text
- Putting large files into documents
- Indexing every field without need
- Using offsets for deep paging
- Triggers that rewrite their own source documents
- Choosing location or mode without thought
Test Rules Like an Attacker
It is easy to test that the right user can reach the right data. It is just as important to test that the wrong user cannot. Try reading another person’s data, writing malformed documents, and acting while signed out. All of these should fail. Use the local emulator during development so you can test safely.
Treat Rules and Indexes as Code
Keep security rules and index definitions in version control, review changes like any other code, and deploy them through a repeatable process. That way a missing index or a loosened rule shows up in review, not in production.
Plan Schema Evolution
Because documents are flexible, old and new shapes will live side by side for a while. Write app code that tolerates missing fields, add new fields gradually, and run background jobs to update old documents when you need consistency.
Watch for Changes in Editions and Pricing
Cloud products evolve. Editions, limits and prices can change. Review the official documentation and your billing page regularly, especially before a launch or a campaign that may bring many new users.
Believing that “serverless” means “no design needed.” The servers disappear, but data modelling, rules, indexes and cost awareness matter even more, because the database will happily scale a poor design into a large bill.
23Real-World and Industry Scenarios
These are illustrative scenarios showing how organisations typically use Firestore, not claims about specific companies.
Chat and Collaboration Apps
Messages live in a subcollection under each room. Listeners show new messages instantly, offline support lets users type on trains, and triggers send push notifications.
E-commerce Catalogues and Carts
Product documents hold the details a product page needs. Carts live under each user. Stock updates use transactions so two buyers cannot take the last item.
Gaming and Leaderboards
Player profiles and match states are small documents. Sharded counters and summary documents keep scores and rankings quick even at peak times.
Logistics and Delivery Tracking
Driver locations update in documents that customers watch live. Expiry policies remove old tracking points automatically.
Education Platforms
Courses, lessons and progress are stored per learner. Rules ensure students see only their own progress, while teachers see their class.
Healthcare and Booking Systems
Appointments are created through transactions to avoid double booking. Strict rules, audit logs and encryption controls protect sensitive records.
Internet-of-Things Dashboards
Devices report small status documents. Dashboards listen to a handful of summary documents instead of thousands of raw readings, while raw data flows to an analytics warehouse.
Internal Business Tools
Teams use Firestore for task lists, approvals and settings, with role-based rules and triggers that notify the right people.
24Frequently Asked Questions
Not exactly. Firestore is a database that is part of Google Cloud and is also used through Firebase. Firebase provides app-focused tools and libraries on top of Google Cloud services, including access to Firestore.
No. Firestore is serverless. Google handles scaling, replication, patching and maintenance.
They differ in the query engine, indexing options, performance characteristics, document size limits, MongoDB compatibility and how operations are priced. Many core abilities, such as client libraries with sync, triggers, backups and encryption choices, are shared. Check the current editions overview before choosing.
No. The data access mode and the location are set when the database is created. To change either, create a new database and migrate the data.
In the Standard edition every query must be answered from an index. Simple queries use automatic single-field indexes, while queries that combine fields need a composite index, which you create once and then reuse.
Not in the way a relational database does. You model related data by embedding, using subcollections, copying small pieces or storing references, and you assemble data with a few reads.
An app attaches a listener to a document or query. Firestore sends current data, then pushes changes as they happen. Each delivered change counts as a read.
Yes in the mobile and web client libraries. They keep a local cache, serve reads from it, queue writes, and sync when the network returns.
No. Rules apply to requests from client libraries. Server libraries use IAM permissions on service accounts, so guard those accounts and keys carefully.
Use a sharded counter: several small counter documents, with writes spread randomly among them and a sum taken when reading.
Documents have a size limit and are read whole, so store images in Cloud Storage and keep only their path in the document.
Use scheduled backups or point-in-time recovery to restore data. Turn these on before you need them, and rehearse a restore.
Model for few reads per screen, limit and page queries with cursors, detach unused listeners, exempt unneeded fields from indexing, expire temporary data, and set budget alerts.
Designing the data like tables and launching with permissive rules. Start from the screens, write narrow rules, and turn on backups and budget alerts before release.
25Summary and Key Takeaways
Firestore is a serverless document database that stores records as documents inside collections, answers every query from indexes, keeps data strongly consistent and replicated, and pushes live updates to apps while letting them work offline. It comes in Standard and Enterprise editions with a shared core of client libraries, triggers, backups and encryption choices, and different query engines, indexing and pricing units. Security is split between rules for client libraries and IAM for servers, and both must be right.
Success comes from a few habits. Model data around the screens, keep documents lean, use subcollections and sharded counters, prefer random identifiers, write narrow rules, use triggers to keep copies fresh, and watch the meter through operations, listeners and indexes. Protect data with backups, point-in-time recovery and delete protection. With these in place, a small team can build apps that feel instant, stay in sync and scale to millions of users.
Key Takeaways
- Documents in collections — Firestore stores flexible records as documents, grouped into collections and subcollections, and is fully serverless.
- Model for your questions — there are no joins, so design around screens, embed or copy small data, keep documents lean and use subcollections for growing lists.
- Indexes power every query — Standard answers all queries from indexes, so create composite indexes deliberately and exempt fields you never query.
- Pick edition, mode and location with care — Standard and Enterprise differ in engine, indexing, limits and pricing, and mode and location cannot be changed later.
- Real-time and offline are built in — listeners and local caches make apps feel instant, but forgotten listeners and wide queries add cost.
- Two security systems — security rules guard client libraries while IAM guards servers, so write narrow rules, validate data, and protect service accounts.
- Protect and observe — use scheduled backups, point-in-time recovery, delete protection, expiry policies, dashboards and budget alerts from day one.