Firestore in Google Cloud

Firestore in Google Cloud

A complete, friendly guide to Google Cloud's serverless document database: how it stores data, how it stays fast and correct at huge scale, how to keep it secure and affordable, and how to avoid the mistakes that catch real teams.

Imagine you are building an app. It could be a chat app, a food delivery app, a to-do list, or a game scoreboard. Sooner or later you need a place to keep the data: the messages, the orders, the tasks, the scores. That place is called a database. Choosing the wrong one can cost you months of rework. Choosing the right one lets a tiny team serve millions of people without losing sleep.

Firestore is one of the most popular choices on Google Cloud for exactly this job. It is a database that you do not have to install, patch, resize, or babysit. You create it with a few clicks, send data to it, and ask questions about that data. Google runs everything else behind the scenes: the machines, the copies of your data, the backups, and the failover when something breaks.

In this guide you will start from zero. Every new word is explained the first time it appears, with an everyday comparison. By the end you will know what Firestore is, how it works inside, how to design data for it, how to keep it safe, how to watch its cost, and when another database would be the better pick.

1What Is Firestore?

Before any diagrams or details, let us get one clear picture of what this product is and what it is for.

Firestore is a NoSQL document database that runs as a serverless, fully managed service on Google Cloud. That sentence has four big ideas in it, so let us unpack them one by one.

Database simply means a system that stores information safely and lets you find it again quickly. NoSQL means it does not store data in the strict rows-and-columns tables that older databases such as MySQL or PostgreSQL use. The name stands for “not only SQL”, and it covers several different styles of storage. Document database is the style Firestore uses: each piece of data is saved as a flexible document, a bit like a small JSON file, which holds named fields and values.

Serverless does not mean there are no servers. It means you never see them or manage them. You do not pick a machine size, you do not install software, and you do not plan for capacity ahead of time. Fully managed means Google handles upgrades, security patches, replication, and repairs. You focus on your app, and Google focuses on keeping the database alive.

Everyday analogy

Think of a huge, magical filing cabinet in the sky. Each drawer is a collection, such as “Customers”. Each folder in a drawer is a document, such as “Priya’s profile”. Inside a folder are sheets with labels and values: name, city, favourite colour. You never build the cabinet, never carry it, and never fix it when a hinge breaks. You just say “put this folder in the Customers drawer” or “find me every folder where the city is Delhi”, and it happens, even if a million people are asking at the same time.

1 MiB
Maximum size of one document
99.999%
Availability promise for multi-region databases
0
Servers you need to manage

What makes Firestore special

Plenty of databases store documents. Firestore stands out because of the combination of features it offers in one package. Here are the main ones.

Scale

Automatic scaling

It grows and shrinks with your traffic. You never resize anything by hand.

Correctness

Strong consistency

Once a write succeeds, every later read sees it. No stale surprises.

Live data

Real-time listeners

Apps can subscribe to data and get pushed updates the moment something changes.

Mobile

Offline support

Mobile and web apps keep working with no network and sync later.

Safety

Transactions

Several changes can succeed together or fail together, protecting your data.

Reach

Multi-region copies

Your data can live in several places at once, so a regional outage does not stop you.

i
Naming tip

You will see the words “Firebase” and “Firestore” used together. Firebase is Google’s wider toolkit for building apps (sign-in, hosting, analytics and more). Firestore is the database inside that toolkit, and it is also a first-class Google Cloud product that you can use from any backend, with or without the rest of Firebase.

2A Short History: How Firestore Came to Be

Products make more sense when you know the problems that created them. Firestore is the child of two older Google databases.

Google has been in the database business for a very long time. When you search, watch videos, or read email, you are touching systems built to handle enormous traffic. Over the years, Google turned some of those ideas into products that other companies could rent. Firestore grew from two such lines of work.

01

2008: App Engine Datastore

Google launches App Engine, a way to run web apps without managing servers. It comes with Datastore, a NoSQL database that scales automatically. Later it becomes the standalone product Cloud Datastore.

02

Around 2012: Firebase Realtime Database

A startup called Firebase builds a database that pushes live changes to phones and browsers. Developers love how easy it is to build chat apps and shared whiteboards.

03

2014: Google acquires Firebase

Firebase joins Google and grows into a full app-building platform, with sign-in, hosting, messaging and more beside its database.

04

2017: Cloud Firestore arrives in beta

Google combines the best of both worlds: the scale and reliability of Datastore with the live updates and friendly SDKs of Firebase. It adds richer queries and a cleaner data model.

05

2019: General availability

Firestore becomes generally available, meaning Google now promises production-grade support and reliability.

06

Following years: Datastore joins Firestore, new features arrive

Existing Datastore databases move onto the same Firestore storage layer and are offered as “Firestore in Datastore mode”. Google keeps adding capabilities such as aggregation queries (count, sum, average), vector search for AI apps, scheduled backups, point-in-time recovery, and newer editions of the product.

The problem it solves

Before products like this, a team that wanted a database for a growing app had to do a lot of hard work. They rented machines, installed database software, set up copies for safety, planned for peak traffic, and woke up at night when a machine died. If the app went viral, the database often fell over.

Firestore removes most of that pain. It gives you a database that can start tiny and free, then grow to serve very large audiences without a redesign. That is why students, startups, and large companies all use it.

!
Good to know

Because Firestore is a living product, features and limits change over time. Treat the numbers in this guide as a map of the landscape, and always check the official Google Cloud documentation and pricing page for the latest exact values before you finalize a design.

3Core Concepts: The Building Blocks

Everything in Firestore is made from a handful of simple pieces. Learn these and the rest falls into place.

Firestore organizes data in a hierarchy, which means a tree-like structure where things sit inside other things. The pieces are databases, collections, documents, fields, and subcollections.

Level 1

Project and database

A Google Cloud project is your workspace and billing container. Inside it you create one or more Firestore databases. Each database is a separate, isolated store with its own location and settings.

Level 2

Collection

A named container of documents, like a drawer called “orders” or “users”. A collection has no fixed shape of its own. It simply holds documents.

Level 3

Document

One record, like one order or one user. It has a unique ID inside its collection and holds a set of fields. A document cannot be larger than 1 MiB.

Level 4

Field

A named piece of data inside a document, such as “name” or “total”. Every field has a type, and different documents in the same collection can have different fields.

Nesting

Subcollection

A collection that lives inside a document. An order document can own an “items” subcollection. This lets you build deep, organized trees.

Linking

Reference

A special field type that points to another document, like a bookmark. It is a lightweight way to connect records without copying them.

flowchart TD
    P["Google Cloud Project"] --> D["Firestore Database"]
    D --> C1["Collection: users"]
    D --> C2["Collection: orders"]
    C1 --> U1["Document: priya"]
    C1 --> U2["Document: arjun"]
    C2 --> O1["Document: order-1001"]
    O1 --> F1["Fields: total, status, createdAt"]
    O1 --> SC["Subcollection: items"]
    SC --> I1["Document: item-1"]
    SC --> I2["Document: item-2"]
    
Figure 1: Firestore’s data hierarchy. Collections hold documents, and documents can hold fields and subcollections.

The strict alternation rule

Firestore enforces a simple pattern: collections contain documents, and documents contain collections. They always alternate. A collection can never directly contain another collection, and a document can never directly contain another document. So a path always looks like collection, document, collection, document, and so on. Every document has a full path, such as “orders, then order-1001, then items, then item-1”. That path is its unique address.

Field types

Each field has a data type, which tells Firestore what kind of value it holds. The common ones are:

  • String: text, such as a name or an email address.
  • Number: whole numbers (integers) and decimal numbers (floating point).
  • Boolean: true or false, like “isPaid”.
  • Timestamp: an exact moment in time, great for “createdAt” fields.
  • Array: an ordered list of values, such as a list of tags.
  • Map: a nested group of fields inside a field, like an “address” holding street, city, and postal code.
  • Geopoint: a latitude and longitude pair for locations.
  • Bytes: raw binary data, for small amounts only.
  • Reference: a pointer to another document.
  • Vector: a list of numbers used for AI similarity search, covered later.
  • Null: an explicit “no value”.
Everyday analogy

Picture a school. The school is the database. Each class register is a collection. Each student’s page in the register is a document. The lines on that page, such as name, roll number, and marks, are fields. If a student has a pile of homework notes, that pile is a subcollection attached to their page. And a sticky note saying “see Arjun’s page” is a reference.

i
Tip

Documents in the same collection do not have to match. One user document can have a “phone” field and another can skip it. This flexibility is called being schema-less or schema-flexible. It speeds up development, but it also means your app code must stay disciplined about which fields it expects.

Document IDs

Every document has an ID that is unique within its collection. You can choose the ID yourself, for example a user’s account number, or you can let Firestore generate a random one. Auto-generated IDs are 20 characters long and spread evenly. That even spread matters for performance, a point we return to in the scaling chapter.

4Architecture and Components

Now let us zoom out and see the whole system: who talks to Firestore, what stands in between, and what sits next to it.

Google does not publish every internal detail of Firestore, and those details can change. But the public documentation and Google’s talks give us a reliable high-level picture. Think of Firestore as four layers: the clients that ask for data, the front door that checks and routes requests, the storage layer that keeps data safe, and the helper services around it.

flowchart LR
    subgraph Clients
      W["Web and Mobile Apps (client SDKs)"]
      S["Backend Servers (server SDKs)"]
    end
    W --> GFE["Google Front End and Load Balancing"]
    S --> GFE
    GFE --> API["Firestore API Layer"]
    API --> SEC["Security Rules Check (client traffic)"]
    API --> IAM["IAM Check (server traffic)"]
    SEC --> ENG["Query and Transaction Engine"]
    IAM --> ENG
    ENG --> IDX["Index Layer"]
    ENG --> STO["Replicated Storage Layer"]
    ENG --> LIS["Real-time Listener Service"]
    STO --> R1["Replica Zone A"]
    STO --> R2["Replica Zone B"]
    STO --> R3["Replica Zone C"]
    ENG --> EV["Event Triggers: Cloud Functions, Eventarc"]
    
Figure 2: A simplified view of Firestore’s request path and its main components.

The components, one at a time

Clients

Client SDKs

Libraries for web, iOS, Android, Flutter and more. They talk to Firestore directly from user devices, support offline caching, and open live listeners.

Clients

Server SDKs

Libraries for Node.js, Python, Java, Go, C#, PHP and Ruby that run on your backend, such as Cloud Run or Compute Engine. They use Google Cloud identity and permissions instead of security rules.

Front door

Google Front End

Google’s global edge network accepts connections, handles encryption in transit, and routes requests to the right place.

Gatekeepers

Security rules and IAM

Two ways to decide “is this caller allowed?”. Rules guard direct app access. IAM guards server access.

Brain

Query and transaction engine

Plans how to answer a query, uses indexes to find results, and coordinates multi-step transactions.

Memory

Storage and replicas

Your documents are stored in several copies spread across separate locations, so losing one machine or zone loses no data.

Speed

Index layer

Sorted lookup tables that let queries jump straight to matching documents instead of scanning everything.

Push

Listener service

Remembers which clients are watching which queries and pushes changes to them.

Reactions

Event triggers

Lets you run code, for example a Cloud Function, whenever a document is created, changed, or deleted.

Two ways to talk to Firestore

This distinction trips up many beginners, so it is worth saying clearly. There are two “doors” into the database.

  • The client door. A phone or browser connects directly, signs in with a user identity (through Firebase Authentication, for instance), and every request is checked against security rules that you write. This is what makes Firestore good for apps that talk to the database without a middle server.
  • The server door. Your own backend connects using a service account, which is a robot identity with a defined set of permissions, checked by Google Cloud IAM (Identity and Access Management). Security rules are not consulted at all on this path.
!
Watch out

Server SDKs bypass security rules. If a backend service has broad database permissions and a bug lets an attacker steer it, the rules will not save you. Give each service account only the access it truly needs.

Other ways in

Besides SDKs, Firestore also offers REST and RPC (gRPC) interfaces, the Google Cloud console for browsing and editing data, the command-line tool, and an official emulator you can run on your laptop for testing without touching real data or spending money.

5Internal Working: What Happens on a Read or a Write

Let us follow one piece of data from your app all the way into storage and back out again.

When you save a document, several things happen in a fraction of a second. You never see them, but understanding them explains Firestore’s behavior, its costs, and its limits.

sequenceDiagram
    participant App as Your App
    participant API as Firestore API
    participant Auth as Rules or IAM
    participant Eng as Engine
    participant Rep as Replicas
    participant Lis as Listeners
    App->>API: Write document
    API->>Auth: Is this allowed?
    Auth-->>API: Yes
    API->>Eng: Apply write
    Eng->>Rep: Send to replicas, update indexes
    Rep-->>Eng: Majority confirms
    Eng-->>App: Success
    Eng->>Lis: Notify watchers of change
    
Figure 3: The life of a single write, from your app to confirmed storage and listener updates.

The write path, step by step

1

Your app sends the write

The SDK packages your document and sends it over an encrypted connection to Google’s front end.

2

Permission check

If the caller is a user device, security rules are evaluated. If it is a backend, IAM permissions are checked. A denied request stops here and costs you almost nothing.

3

Engine applies the change

The engine figures out the document’s new contents and also which index entries must be added, changed, or removed because of it.

4

Replication and agreement

The data and its index entries are sent to multiple replicas. The write is only called successful after a majority of replicas have safely recorded it. This is a consensus protocol, a way for several computers to agree on one truth even if some fail.

5

Success returned

Your app receives confirmation. From this moment, every read anywhere sees the new data.

6

Listeners and triggers fire

Clients watching this data get an update, and any event triggers, such as Cloud Functions, are queued to run.

Everyday analogy

Imagine a village council deciding a new rule. The rule only becomes official after most of the council members have signed it. Even if two members are away, the rule still passes, and nobody can later claim it never happened. Firestore’s majority agreement works the same way: your data is official only when most replicas have recorded it.

The read path

Reading is simpler. The request is checked for permission, then the engine looks up the document by its path, or uses an index to find documents matching a query. Results are returned from a replica that is guaranteed to be up to date. That guarantee is what “strong consistency” means, and we explore it more in a later chapter.

Why writes touch indexes

Here is a fact that surprises many beginners: every write does more work than saving the document. Firestore automatically keeps a sorted index entry for each field you might filter or sort by. When you change a field, the matching index entries change too. That is why queries are fast, and also why writes have a cost that grows with the number of indexed fields. Both effects come from one design decision, so keep it in mind when choosing what to index.

The lifecycle of a document

Over its life, a typical document is created, indexed, read many times, updated several times, perhaps watched by live listeners, backed up with the rest of the database, and finally deleted, either by your code or automatically by a time-to-live rule you configure. Each stage has a cost and a design consequence, and the next chapters cover them.

6Indexes and Queries

Firestore has a rule that shapes everything about how you ask questions: a query is only allowed if an index can answer it.

An index is a sorted list that points to documents. Think of the index at the back of a textbook. If you want every page that mentions “photosynthesis”, you do not read the whole book. You look in the index, which tells you the page numbers instantly. Firestore indexes work the same way for your fields.

Why this design is special

In Firestore, query speed depends on the size of the result, not the size of the database. If a query returns 20 documents, it takes about the same time whether your collection holds a thousand documents or a billion. Firestore gets this predictability by refusing to run queries it cannot answer straight from an index. It will never quietly scan your whole database and slow down. This is a deliberate trade: fewer kinds of questions are allowed, but each allowed question stays fast as you grow.

Two kinds of indexes

Single-field indexes

  • Created automatically for every field
  • Handle simple filters and sorting on one field
  • Can be switched off per field with an exemption to save cost

Composite indexes

  • Created by you for queries that combine several fields
  • Needed, for example, to filter by status and sort by date
  • Firestore tells you exactly which one is missing, with a helpful link

What you can ask

  • Filters: equals, not equals, less than, greater than, and similar comparisons.
  • Membership filters: “in” and “not in” for a list of allowed values, and array-contains filters for matching inside arrays.
  • OR queries: combine conditions so that matching either one is enough.
  • Ordering and limits: sort results and take only the first few.
  • Cursors: start after the last document you saw, which is the efficient way to build “next page” buttons.
  • Collection group queries: search every subcollection that shares the same name, across the whole database, in one query.
  • Aggregation queries: count, sum, and average computed by the database itself, without downloading every document.
  • Vector search: find documents whose stored numbers are closest to a given list of numbers. This powers “find similar” features for AI apps.
i
Tip

For paging, use cursors rather than offsets. An offset still makes the database walk past the skipped documents, and you are charged a read for each one. A cursor jumps straight to the right place.

What you cannot easily do

Firestore is not built for every question. It does not do joins, which are queries that glue several tables together on the fly. It has no built-in free-text search such as “find documents containing the word ‘sunset’ anywhere”, though you can pair it with a dedicated search service, and the newer Enterprise edition widens the range of query features. And certain combinations of range and inequality filters need careful index planning. If your application is mostly ad-hoc exploration and reporting, a database built for analytics is a better partner, and Firestore can feed it, as the integration chapter shows.

Everyday analogy

A library with a perfect card catalog can answer “all books by this author, newest first” in seconds, but only if someone prepared that exact catalog. Firestore is that library. Asking for a kind of question that has no catalog is refused politely, with instructions on how to create the missing catalog.

Understanding your queries

Firestore offers a query explain feature that shows how a query will run and, if you choose, how it actually ran: which index was used, how many entries were scanned, and how long it took. It is the first place to look when a query feels slow or expensive.

7Data Modeling: Designing for Firestore

Good data design in a document database starts from a different question than in a traditional database.

In a relational database, you usually start by asking “what are the things in my world, and how do I split them into clean tables with no repeated data?” This approach is called normalization. In Firestore, you start by asking “what screens and questions does my app need to serve, and what is the cheapest way to answer each one?” The data is shaped around the reads.

Embed, subcollect, or reference?

For any related piece of data, you have three main choices.

Option A

Embed in the same document

Store related data as a map or array inside the parent. One read gets everything. Best for small, fixed-size data that is always shown together, such as a user’s address.

Option B

Use a subcollection

Store related items as documents under the parent. Best for lists that can grow without limit, such as the messages in a chat room or the items in an order.

Option C

Use a separate top-level collection

Keep items in their own collection and link by reference or ID. Best when you need to query the items across all parents, or the relation is many-to-many.

Denormalization is normal here

Denormalization means deliberately storing the same fact in more than one place so reads become cheap and simple. Suppose a blog post shows its author’s name. In a relational design you would store only an author ID and join to find the name. In Firestore, you would often copy the author’s display name into the post document. Then showing a list of posts needs one query instead of one query plus a lookup per post.

The price you pay is on the write side. If the author changes their name, you must update every post that copied it. So denormalize data that is read very often and changes rarely, such as names, titles, thumbnails, and counts. Do not copy data that changes every minute.

Everyday analogy

A restaurant waiter writes the table number and the dish names on each order slip, instead of only writing “see customer file 482”. The slip is a little repetitive, but the kitchen can work from it without walking to the office. If a customer later changes their mind, the waiter has to update the slip, which is the extra write cost of copying data.

Limits that guide your design

  • Document size: 1 MiB maximum. Never pack an unbounded list into one document, since it will eventually hit the cap and every read will drag the whole list along.
  • Write rate per document: roughly one sustained write per second to the same document. A single “global counter” document updated by thousands of users will choke. The fix is a distributed counter, which spreads the count across several small documents and adds them up when needed.
  • Index entries: each indexed field adds entries, and there is a per-document ceiling on them. Large arrays and maps with many indexed values can add up fast.

A worked example

Consider a small online shop. A sensible design might be:

  • A users collection, one document per customer, with the address embedded as a map.
  • A products collection, one document per product, with price, title, and a few tags.
  • An orders collection, one document per order, holding the customer ID, a status, a total, and a timestamp. The product title and unit price at the time of purchase are copied into each line item, because an old order should keep showing what the customer actually paid even if the product’s price changes later.
  • Order line items stored in an items subcollection under each order if orders can have many lines, or embedded as an array if orders are always small.
i
Tip

Write down your app’s top ten screens and what each one needs to show. Then check that each screen can be served by one or two simple queries. If a screen needs ten queries, the model probably needs more denormalization.

!
Watch out

Deeply nested subcollections look neat but are hard to query across. Remember that you can use collection group queries to search all subcollections with the same name, and decide early whether you will need that.

8Consistency, Transactions, and Batched Writes

When many people change data at once, correctness becomes the hardest problem. Firestore solves much of it for you.

Strong consistency

Consistency describes what a reader sees after someone else writes. In an eventually consistent system, a reader might see old data for a short while, because copies take time to catch up. In a strongly consistent system, once a write is confirmed, every later read sees it. Firestore is strongly consistent for reads of documents and queries. That makes your app logic far simpler, because you do not need to write code that guesses whether data is stale.

Everyday analogy

Think of a train station board. An eventually consistent board might show an old platform for a minute after a change, and passengers run to the wrong place. A strongly consistent board updates the instant the announcement is made, so everyone who looks afterward sees the same truth.

ACID transactions

A transaction is a group of reads and writes that must behave as one unit. Firestore transactions follow the ACID promises:

  • Atomic: all changes happen, or none do.
  • Consistent: the data moves from one valid state to another.
  • Isolated: concurrent transactions do not see each other’s half-finished work.
  • Durable: once committed, the change survives crashes.

A classic use is moving money between two accounts. You read both balances, check there is enough, subtract from one and add to the other. If anything fails halfway, nothing changes. Without a transaction, a crash at the wrong moment could make money vanish.

How transactions behave

  • All reads inside a transaction must come before its writes.
  • Mobile and web SDKs use optimistic concurrency. They assume no conflict, and if another change touched the same documents in the meantime, the SDK automatically retries your transaction. Because of retries, your transaction code must be safe to run more than once, so do not send emails or charge cards inside it.
  • Server SDKs use pessimistic locking. They lock the documents they read, so competing writers wait their turn. This avoids retries but means heavy contention can slow things down.
  • Transactions have a time limit, so keep them short and focused.

Batched writes

A batched write is a simpler tool. It groups several writes, such as set, update, and delete, so that they all succeed or all fail together. Unlike a transaction, it does not read anything first. Use a batch when you already know exactly what to write, such as creating an order and updating a counter together. For loading very large amounts of data, use the dedicated bulk writer in the server libraries, which spreads the load and handles retries and ramp-up for you.

Use a transaction when

  • The new value depends on a value you must read first
  • You are enforcing a rule such as “stock must not go below zero”
  • Two documents must stay in step

Use a batched write when

  • You know every write in advance
  • No read is needed to decide what to write
  • You want several changes to land together

Atomic field operations

Firestore also offers special operations that change a field safely without reading it first, such as increment a number, add to an array, and remove from an array, as well as setting a field to the server’s own timestamp. These are ideal for counters and tag lists, because two users doing the same thing at the same moment will not overwrite each other.

!
Watch out

Do not do “read the value, add one, write it back” in ordinary application code for a shared counter. Two users can read the same old value and one of the two updates will be lost. Use the increment operation or a transaction instead.

9Real-Time Listeners and Offline Support

This is the feature that made Firebase famous: apps that update themselves without being asked.

Normally, to see fresh data your app has to poll, which means asking the database again and again, “Anything new? Anything new?” That wastes battery, bandwidth, and money. With a real-time listener, your app asks once, “tell me about this document or this query, and keep telling me whenever it changes.” Firestore then pushes updates the moment they happen.

Everyday analogy

Polling is like walking to the mailbox every five minutes to see if a letter has arrived. A listener is like having the postman ring your doorbell exactly when a letter comes. You do less work and you hear the news sooner.

How listeners work

When a client starts listening, it first receives the current matching data. After that, it only receives changes: which documents were added, modified, or removed. Behind the scenes, the listener service tracks the query, and every successful write is compared against active listeners to decide who needs to be told. The app then simply re-draws its screen from the new data.

Offline persistence

Mobile and web SDKs can keep a local copy of data that the app has used. When the network drops, the app keeps working. Reads come from the local copy, and writes are queued. When the connection returns, queued writes are sent and fresh changes are pulled in. Firestore also uses latency compensation: when your app writes something, listeners on the same device are told immediately, before the server has confirmed, so the screen feels instant. If the server later rejects the write, the screen corrects itself.

Where real-time shines

  • Chat and messaging apps
  • Shared documents and whiteboards
  • Live dashboards, scoreboards, and order trackers
  • Collaborative to-do lists and project boards
  • Multiplayer game lobbies and presence indicators

Costs and cautions

  • You are charged a read for each document in the initial result, and one more read for each document that later changes. A listener on a busy, broad query can therefore get expensive.
  • If a client is disconnected for a long time, around thirty minutes, the listener must be re-established and the initial results are billed again.
  • Listen to narrow queries, and detach listeners when a screen closes. A forgotten listener keeps costing money and battery.
  • Real-time is a client feature. If your backend needs to react to changes, use event triggers or a listener in a long-running service, not polling.
i
Tip

Listen to “the last 50 messages in this room”, not “every message ever sent”. The first is cheap and fast. The second grows without limit.

10Locations, Replication, and High Availability

Where your data lives decides how fast it feels and how well it survives disasters.

High availability means the system keeps working even when parts of it fail. Computers break, power fails, and whole data centers occasionally go dark. A reliable database expects this and is built so that users never notice.

Choosing a location

When you create a Firestore database you pick its location, and this choice is permanent for that database. There are two families:

Regional

  • Data is replicated across several zones in one region (a zone is an isolated data center area)
  • Lower cost and lower write latency
  • Availability promise of 99.99%
  • Survives the loss of a zone but not of the whole region

Multi-region

  • Data is replicated across several regions, within a large geographic area such as the United States or Europe
  • Higher cost and a little more write latency
  • Availability promise of 99.999%
  • Survives the loss of an entire region
flowchart TB
    U["Users"] --> LB["Google Global Network"]
    LB --> RA["Region A: Replica Set"]
    LB --> RB["Region B: Replica Set"]
    LB --> RC["Witness Region: Tie-breaker"]
    RA  RB
    RA  RC
    RB  RC
    
Figure 4: A multi-region database keeps full copies in more than one region, so one region failing does not stop writes or lose data.

What the availability numbers mean

A promise of 99.99% allows roughly 52 minutes of downtime in a year. A promise of 99.999% allows only about five minutes in a year. For a hobby project, either is far more than enough. For a payments system or a service that must never be down, the extra “nine” can matter a great deal.

99.99%
Regional databases
99.999%
Multi-region databases
~5 min
Yearly downtime allowed at five nines

How to choose

  • Where are your users and servers? Place the database near them. Distance adds delay, because data cannot travel faster than light, and a round trip across an ocean takes a noticeable fraction of a second.
  • How costly is downtime for you? If an outage is a minor annoyance, regional is fine. If it means lost money or safety risks, consider multi-region.
  • Do you have data residency rules? Some laws require data to stay in a country or a union of countries. Pick a location that satisfies them.
  • What is your budget? Multi-region storage and writes cost more.
!
Watch out

You cannot change a database’s location after creating it. If you picked wrongly, the fix is to create a new database in the right place and copy the data across using export and import. Think about location before your first user arrives.

Multiple databases per project

A single Google Cloud project can hold several named Firestore databases, in addition to the default one. This is handy for separating environments such as testing and production, or for keeping different applications, each with its own location, security setup, and backup policy, under one billing account.

11Performance and Scalability

Firestore scales a long way on its own, but a few habits decide whether you enjoy that scale or run into its edges.

Performance is how fast individual requests are answered. Scalability is how well the system keeps its speed as the number of users and the amount of data grow. Firestore is designed to scale automatically: as traffic rises, Google spreads your data over more machines behind the scenes. You do not press a “scale up” button.

Why it scales

Firestore divides your data into many small pieces, sorted by document path and by index value, and spreads those pieces across many servers. When one piece gets too busy or too big, the system splits it and moves part of it elsewhere. Because queries are answered from sorted indexes and cost depends on result size, adding more data to the database does not slow down a query that returns the same number of results.

Everyday analogy

Picture a huge dictionary split into many volumes, with each volume kept by a different librarian. When one volume gets very popular, the library splits it into two thinner volumes and gives them to two librarians. Readers still find words quickly, because the dictionary stays sorted and the library keeps adjusting.

The ramp-up rule: 500, 50, 5

Splitting takes a little time. If you send a huge flood of traffic to a brand new, empty collection in the first second, the system has not had time to spread out yet. Google’s guidance is the 500/50/5 rule: start with up to about 500 operations per second against a new collection, then increase traffic by no more than 50% every 5 minutes. Following this lets Firestore prepare in step with you. It matters most for big data imports and sudden launch spikes.

Hotspots: the main scaling trap

A hotspot is one small area of the database that receives far more traffic than the rest. Because data is sorted, documents with neighboring keys live together. If all your new writes land at the very end of the sorted order, they all hit the same piece and cannot be spread out.

  • Sequential document IDs such as 1, 2, 3, or IDs that start with a timestamp, push every new write to the same spot. Use Firestore’s random auto-generated IDs for high-rate writes.
  • Indexed fields that only ever grow, such as a “createdAt” timestamp, create a hotspot in the index at very high write rates. For extreme workloads, consider switching off indexing on such a field or spreading writes using a bucket prefix.
  • A single hot document that everyone updates, such as one global “views” counter. Recall the limit of about one sustained write per second per document.

Spread-out workloads

  • Random document IDs
  • Many documents each updated occasionally
  • Counters split across shards
  • Reads fetch small, targeted result sets

Concentrated workloads

  • Sequential or timestamp-prefixed IDs
  • One document updated constantly
  • Giant collection scans on every request
  • Sudden traffic jumps on an empty collection

Practical speed-ups

  • Keep documents small. Every read downloads the whole document, so a bloated document slows every query that returns it.
  • Return only what you need. Use limits and pagination, and in server libraries use field selection so you do not pull large fields you will not display.
  • Choose the nearest location and put your servers in or near the same region.
  • Cache at the right level. Use the SDK’s local cache on devices, and put an in-memory cache such as Memorystore in front of data that is read constantly but changes slowly.
  • Reuse connections. Create one client object per process and share it, rather than creating a new one for every request.
  • Prefer aggregation queries for counts and sums instead of downloading documents to count them.

Distributed counters in plain words

If one counter document cannot take enough writes, split it into, say, ten small counter documents. Each update picks one of the ten at random and increments it. To get the total, read all ten and add them. Ten small counters can accept roughly ten times the writes of one. This trick is common for “likes”, “views”, and “downloads”.

12Security: Protecting Your Data

A database that is fast but open to everyone is a disaster. Firestore gives you several layers of defense, and you should use them all.

Good security works in layers, like a castle with a moat, a wall, a gate, and guards. If one layer fails, the others still protect you. Firestore’s layers cover who you are (authentication), what you may do (authorization), how data travels, how data is stored, and who is watching.

Layer 1: Identity

Authentication means proving who someone is. For app users, Firebase Authentication offers email and password, phone number, and sign-in with Google, Apple and other providers. For your backend services, Google Cloud service accounts are the robot identities.

Layer 2: Authorization with security rules

Authorization means deciding what an identified caller is allowed to do. For direct app access, you write Firestore Security Rules. These are a set of conditions, written in a small rules language, that Firestore checks on every read and write coming from a client. A rule can say things such as: a signed-in user may read and write only the document whose ID matches their own user ID; anyone may read product listings, but only staff may change them; a new post must contain a title shorter than 200 characters and a valid author field.

  • Rules can check who is signed in, which document is being touched, the data being sent, and even other documents in the database.
  • If no rule allows an action, it is denied. Start from “deny everything” and open up only what is needed.
  • Rules are not filters. A query is allowed only if Firestore can prove that every possible result would pass the rules. If your rule says users may read only their own documents, your query must also ask only for their own documents, or it will be rejected outright.
  • Test your rules with the local emulator and automated tests before shipping, and keep them in version control like any other code.

Layer 3: Authorization with IAM

IAM controls access for backend code and for people using the Google Cloud console. It works through roles that bundle permissions. Firestore uses roles from the Datastore family, such as a viewer role for read-only access, a user role for reading and writing data, and an owner role for full control, plus specialized roles for tasks such as managing indexes or backups. The golden rule is least privilege: give each person and service only the minimum access it needs, and nothing more.

Layer 4: Defending against abuse

Firebase App Check helps make sure requests come from your genuine app and not from a copied or scripted client. It does this by asking the device or browser to present a short-lived proof that it is trustworthy. It is a strong extra layer on top of security rules, especially against bots that try to burn through your quota.

Layer 5: Protecting data in transit and at rest

  • In transit: all connections to Firestore use encryption in transit, so nobody on the network can read the traffic.
  • At rest: data stored by Firestore is encrypted by default using Google-managed keys. If your organization requires control over the keys, Firestore supports customer-managed encryption keys (CMEK) through Cloud KMS, so you can rotate or revoke the keys yourself.

Layer 6: Network boundaries

For sensitive workloads, you can wrap Google Cloud services in a VPC Service Controls perimeter, which limits which networks and projects may talk to Firestore and helps block data from leaving to unapproved places. You can also reach Google APIs over private connections from your own virtual network instead of the public internet.

Layer 7: Watching and recording

Cloud Audit Logs record who did what. Administrative actions, such as creating a database or changing an index, are logged by default. You can also enable data access logs to record who read or wrote data, at the price of extra log volume. Pair this with alerts for unusual activity, such as a sudden spike in reads from one identity.

!
Watch out: the “test mode” trap

Starter setups often allow open access for a limited time so that developers can experiment quickly. It is a very common mistake to ship an app while those wide-open rules are still in place, or to extend them “just for now”. Anyone who finds your project settings could then read or delete everything. Replace open rules with real ones before launch, and review them regularly.

Everyday analogy

Think of an apartment building. The building’s main door checks that you live there (authentication). Each apartment door has its own lock that only opens for that tenant (security rules). The maintenance staff have a master key set that only opens what their job needs (IAM roles). Cameras record who comes and goes (audit logs), and a guard checks that visitors are real people and not robots (App Check).

13Monitoring, Logging, Metrics, and Cost

You cannot fix what you cannot see, and in a pay-per-use database, you also cannot control costs you do not watch.

What to watch

Observability is the ability to understand what a system is doing from the signals it gives out. For Firestore, these signals come from Google Cloud’s operations tools.

Metrics

Cloud Monitoring

Charts and alerts for document reads, writes and deletes, active real-time connections, request latency, error rates, and storage used.

Console

Usage view

The Firestore page in the console shows recent usage so you can spot a sudden jump in reads or writes quickly.

Logs

Cloud Logging and Audit Logs

A trail of administrative and, if enabled, data access events, plus logs from your own services that call Firestore.

Queries

Query explain

Shows which index a query used and how much work it did, so you can fix slow or costly queries.

Rules

Rules monitoring

Counts of allowed and denied requests help you notice both broken features and probing attempts.

Money

Billing reports and budgets

Budget alerts email you when spending crosses a threshold you choose.

Alerts worth setting up

  • Reads or writes per minute rising far above the normal pattern, which often points to a bug such as an infinite loop or a runaway listener.
  • A jump in permission-denied errors, which can mean a bad rules deployment or an attack.
  • Latency climbing for several minutes in a row.
  • Storage growing faster than expected, which can mean a cleanup job has stopped running.
  • Monthly spending nearing your budget.

How Firestore billing works

Firestore uses a pay-for-what-you-use model. You are billed mainly for the following:

Cost driverWhat countsPlain-language tip
Document readsEach document returned by a query or lookup, each document delivered by a listener, and a minimum of one read per queryFetch less, paginate, and cache
Document writesEach document created or updatedCombine changes into one write when you can
Document deletesEach document removedUse TTL rules to automate cleanup
StorageDocument data plus index entries, per gigabyte per monthRemove unneeded indexes and old data
NetworkData leaving Google Cloud to the internet or other regionsKeep apps and database close together
Backups and recoveryStored backups and point-in-time recovery dataChoose retention that matches real needs

Firestore also has a daily free quota for each project, which covers a modest number of reads, writes, and deletes and a small amount of storage. This is why small apps and learning projects often cost nothing. Exact prices and quotas differ by location and change over time, so always read the current pricing page before estimating a bill.

Cost surprises and how to avoid them

  • Reading a whole collection to count it. Use a count aggregation, which is billed far more cheaply than reading every document.
  • Large result sets in listeners. Every change on every document in the result is billed to every watching client.
  • Over-indexing. Indexes are stored and updated, and they cost both space and write work. Switch off indexing on fields you will never filter or sort by, such as long text bodies.
  • Offset pagination. Skipped documents are still billed.
  • Runaway loops. A function that is triggered by a write and then writes to the same document can call itself forever. Always add a guard, such as checking whether anything meaningful changed.
i
Tip

Set a budget alert on day one, even if your app is tiny. A single coding mistake, such as an endless loop, can generate millions of operations in an hour. An alert turns a nasty surprise into a quick fix.

14Backup, Recovery, and Data Lifecycle

Replication protects you from hardware failure. It does not protect you from human mistakes. For that, you need backups.

Here is a point many beginners miss. Firestore keeps several copies of your data, but if your code accidentally deletes a collection, every copy is deleted instantly and consistently. Replication copies your mistakes as faithfully as your successes. So you need a separate way to travel back in time.

Your recovery toolbox

Rewind

Point-in-time recovery

When enabled, lets you read or restore data as it was at any minute within a recent window, up to seven days. Ideal for “we deployed a bad script an hour ago”.

Snapshots

Scheduled backups

Daily or weekly backups kept for a retention period you choose, which can reach many weeks. You can restore a backup into a new database.

Files

Managed export and import

Copy your data into a Cloud Storage bucket, and load it back later. Useful for moving between projects, for long-term archives, and for analytics.

Guard

Delete protection

A setting that blocks the deletion of the whole database until someone deliberately turns it off.

Automatic cleanup with TTL

TTL stands for time to live. You choose a timestamp field, such as “expireAt”, and tell Firestore to delete documents whose time has passed. Deletion happens in the background, usually within about a day after the time passes, so do not use it for exact-to-the-second expiry. It is perfect for temporary data such as login sessions, one-time codes, shopping carts, and old logs, and it saves you from writing and paying for a cleanup job.

Failure scenarios and recovery

A

A machine or zone fails

Replication keeps serving data from the remaining replicas. You do nothing. Clients may see a brief delay while requests are rerouted.

B

A whole region fails

A multi-region database continues to operate from the surviving regions. A regional database would be unavailable until the region returns, which is the main reason to choose multi-region for critical systems.

C

A bad deploy corrupts data

Use point-in-time recovery or a scheduled backup to restore the earlier state into a new database, compare, and then copy the good data back or switch your app over.

D

Someone deletes a collection by mistake

Restore from point-in-time recovery or a backup. Granting delete permissions sparingly and using delete protection reduce the odds of this happening.

E

A hot document starts timing out

The cause is overload on one document, not a platform failure. Fix the design with sharded counters or by spreading writes across more documents.

Connecting Firestore to the rest of Google Cloud

  • Event triggers: run a Cloud Function or Cloud Run service whenever a document is created, updated, or deleted. Great for sending a welcome email, resizing an uploaded image, or updating a denormalized copy.
  • BigQuery: for analytics and reporting, stream or export your Firestore data into BigQuery, Google’s analytics warehouse, and run heavy SQL there without disturbing your live app.
  • Cloud Storage: store large files, such as photos and videos, in Cloud Storage and keep only the file’s address in the Firestore document. Documents are for structured data, not heavy files.
  • Pub/Sub and workflows: hand off slow or retry-prone work to message queues instead of doing it inside a request.
  • AI features: store embeddings in vector fields and use vector search to power recommendations, semantic lookup, and retrieval for AI assistants.
i
Tip

Make recovery a habit, not a hope. Once a quarter, restore a backup into a scratch database and check that your app can read it. A backup you have never restored is only a theory.

15Modes, Editions, and Neighboring Databases

Firestore comes in more than one flavor, and Google Cloud offers several other databases that may fit your problem better.

Native mode and Datastore mode

When you create a Firestore database you choose a mode. Native mode is the full-featured experience described in this guide, with client SDKs, security rules, real-time listeners, and offline support. Datastore mode keeps the older Datastore programming interface. It is meant for server-side applications and for teams with existing Datastore code, and it does not offer the real-time and mobile features. Both modes now run on the same modern storage layer, so Datastore-mode apps gain Firestore’s scalability and strong consistency. For new projects with no legacy code, Native mode is usually the right start.

Editions

Google has also introduced editions of Firestore. The Standard edition is the classic product covered here. The Enterprise edition is aimed at more demanding needs and adds capabilities such as compatibility with MongoDB’s interface and a broader set of query features. Editions, names, and features evolve, so check the official documentation to see which edition fits your project and what each one currently offers.

Comparing Google Cloud databases

DatabaseData styleShines atThink twice when
FirestoreDocuments in collectionsApp backends, mobile and web, live updates, flexible data, automatic scalingYou need heavy joins, ad-hoc analytics, or full SQL
Cloud SQLRelational tables (MySQL, PostgreSQL, SQL Server)Familiar SQL, joins, existing apps, moderate scaleYou need near-limitless write scaling without sharding work
Cloud SpannerRelational with global scaleHuge, globally distributed, strongly consistent SQL workloadsThe app is small or the budget is tight
BigtableWide-column key-valueEnormous throughput for time series, IoT and analytics-style dataYou need rich queries or multi-row transactions
Firebase Realtime DatabaseOne large JSON treeVery simple, very low latency live syncingYou need complex queries or very large structured data
BigQueryAnalytical warehouseLarge-scale reporting and analysis with SQLYou need fast single-record reads and writes for an app
Everyday analogy

Databases are like vehicles. Firestore is a reliable family car that handles most daily trips smoothly and grows with you. Cloud SQL is the familiar sedan that every mechanic knows. Spanner is a high-speed intercontinental train: amazing, but you would not use it to buy milk. Bigtable is a freight train for enormous cargo. BigQuery is an observation tower from which you study traffic patterns of the whole city.

Many real systems use more than one

It is normal, and healthy, to combine databases. A common pattern is to keep live, user-facing data in Firestore, copy it to BigQuery for analysis, and keep large files in Cloud Storage. Choose each tool for what it does best instead of forcing one database to do everything.

16Advantages, Disadvantages, and Trade-offs

Every technology is a bundle of trade-offs. Knowing them in advance is what separates smart choices from lucky ones.

Advantages

  • No servers to manage, and scaling is automatic
  • Strong consistency and ACID transactions
  • Real-time updates and offline support built in
  • Query speed that depends on the result size, not the database size
  • Multi-region replication with a high availability promise
  • Direct, secure access from apps through security rules
  • A generous free tier that suits learning and small apps
  • Tight links with the rest of Google Cloud and Firebase

Disadvantages

  • No joins, and limited ad-hoc querying
  • Every query must be backed by an index
  • Costs scale with operations, which can surprise careless designs
  • Limits such as 1 MiB per document and about one sustained write per second per document
  • Data location cannot be changed after creation
  • Tied to Google Cloud, so moving elsewhere takes real effort
  • Denormalized data means extra work to keep copies in sync

The big trade-offs, explained

Trade-off 1

Flexibility vs discipline

No fixed schema lets you move fast, but nothing stops one bad write from creating a malformed document. You must enforce structure in rules and code.

Trade-off 2

Fast reads vs costly writes

Indexes and copied data make reads quick, but every write does extra work. Heavy-read apps benefit; heavy-write apps must be careful.

Trade-off 3

Simplicity vs control

Serverless removes chores, but you also give up tuning knobs. You cannot change a storage engine setting to rescue a bad data model.

Trade-off 4

Availability vs cost

Multi-region gives the highest uptime at a higher price. Match the spend to the real cost of downtime.

Trade-off 5

Predictable speed vs query freedom

By refusing un-indexed queries, Firestore keeps performance steady, but you plan your questions in advance.

Trade-off 6

Convenience vs portability

Rich platform features speed up building, but they create ties to one vendor. Keep your data access in a thin layer of code if you worry about this.

On the CAP theorem, which says a distributed system facing a network split must choose between consistency and availability, Firestore chooses strong consistency and invests heavily in availability through multi-zone and multi-region replication, so that real-world splits that block users are rare.

17Design Patterns and Anti-Patterns

Teams keep solving the same problems on Firestore. Here are the solutions that work, and the traps that keep catching people.

Patterns that work

Pattern

Distributed counter

Split one hot counter into several shard documents and sum them on read. Handles heavy “likes” and “views” traffic.

Pattern

Fan-out on write

When a user posts, copy a small summary into each follower’s feed. Writes cost more, but reading a feed becomes one cheap query.

Pattern

Summary document

Keep a small precomputed document, such as “dashboard totals for this month”, updated by triggers, so screens do not scan thousands of records.

Pattern

Time-bucketed documents

Group fast-arriving events, such as sensor readings, into one document per device per hour rather than one document per event, with care for document size.

Pattern

Soft delete with TTL

Mark records as deleted, hide them from queries, and let a TTL rule remove them later. Makes undo easy and cleanup automatic.

Pattern

Idempotent triggers

Write event-handling code so that running it twice has the same result as running it once, since events can be delivered more than once.

Anti-patterns to avoid

ANTI-PATTERN 01Avoid
What it looks like

One document called “stats” holds a global counter or a growing list, and every user action updates it.

Why it hurts

A single document accepts only about one sustained write per second. Under load, requests queue up, time out, and fail. A growing list also drifts toward the 1 MiB ceiling.

Do this instead

Use sharded counters for numbers and subcollections for lists that can grow without bound.

ANTI-PATTERN 02Avoid
What it looks like

The app downloads an entire collection and filters it on the device, because “that is how I would do it with an array”.

Why it hurts

You pay a read for every document downloaded, the app slows down as data grows, and you waste bandwidth. It works in testing with ten records and collapses with ten million.

Do this instead

Ask the database to filter, using queries backed by indexes, and fetch only one page at a time.

ANTI-PATTERN 03Avoid
What it looks like

Document IDs that increase in order, such as an auto-incrementing number or a timestamp prefix, used for a high-write collection.

Why it hurts

All new writes land at the end of the sorted order and create a hotspot that the system cannot spread out.

Do this instead

Use random auto-generated IDs and store the timestamp as a normal field.

ANTI-PATTERN 04Avoid
What it looks like

A trigger function that writes to the same document that triggered it, with no check for whether anything really changed.

Why it hurts

Each write fires the function again, which writes again. The loop can run endlessly and produce a huge bill in minutes.

Do this instead

Compare the before and after values and exit early when nothing meaningful changed, and set budget alerts as a safety net.

18Best Practices and Common Mistakes

A short, practical checklist you can return to before every launch.

Best practices

1

Design from your screens backward

List the questions your app asks, then shape documents so each is answered by one or two simple queries.

2

Keep documents small and bounded

Anything that can grow forever becomes a subcollection or its own collection.

3

Lock down access from day one

Write real security rules, use least-privilege IAM roles, and turn on App Check for public apps.

4

Index with intent

Create composite indexes your queries need, and exempt fields you will never query, particularly large text fields.

5

Use the emulator and automated tests

Test rules, queries, and triggers locally before touching real data. It is free and fast.

6

Plan for recovery

Enable point-in-time recovery and scheduled backups, turn on delete protection, and practice a restore.

7

Watch cost and health from the start

Create dashboards, alerts, and a budget before launch, not after your first scary invoice.

8

Ramp traffic and loads gently

Follow the 500/50/5 guidance for imports and launches, and use the bulk writer for large loads.

Common mistakes

  • Treating it like a relational database. Forcing normalized tables and expecting joins leads to many slow round trips. Embrace denormalization where it is justified.
  • Leaving rules open. Wide-open rules are the single most dangerous mistake and the easiest to prevent.
  • Forgetting that rules are not filters. Queries that could return forbidden data are rejected, even when the actual matching data would be allowed.
  • Unbounded growth. Arrays, maps, and collections that grow forever, with no archive or TTL plan.
  • Ignoring listener hygiene. Forgetting to detach listeners, or listening to huge queries.
  • Storing big files in documents. Use Cloud Storage and keep only a link.
  • Mixing environments. Testing against production data. Use separate databases or projects.
  • Doing side effects inside transactions. Sending emails or charging cards inside code that may be retried.
  • Assuming the data is backed up because it is replicated. Replication is not backup.
!
Common myth

“Firestore is infinitely scalable, so I do not need to think about design.” The platform handles servers and capacity, but it cannot rescue a model with a single hot document, a sequential key, or a query that downloads everything. Scale is a partnership between Google’s infrastructure and your data design.

19Real-World Usage Scenarios

These illustrative scenarios show how the ideas in this guide combine in typical products. They are teaching examples, not descriptions of any specific company.

A ride-sharing style app: live location and trip status

Each trip is a document with a status field such as requested, accepted, arrived, or completed. The rider’s app listens to its own trip document and sees the driver’s progress the moment it changes. Driver positions are written often, so they are kept in a small, separate document per driver, with random IDs and time-limited history cleaned up by TTL. Matching and pricing logic runs on backend servers using service accounts, while riders can only read their own trips through security rules.

A chat application: messages that arrive instantly

Each room is a document, and its messages live in a subcollection so a room can grow without limit. Clients listen to the latest fifty messages and load older ones page by page with cursors. Offline support lets people write messages on a train and have them sent on reconnection. A trigger updates the room’s “last message” preview, so the inbox list needs only one cheap query.

An e-commerce catalog and cart

Products are documents that can be queried by category, price, and availability using composite indexes. Carts are documents with a TTL so abandoned carts disappear on their own. Checkout uses a transaction to reduce stock and create the order together, so a popular item can never be oversold. Order history is copied into BigQuery for the analytics team, keeping heavy reports off the live database.

A multiplayer game backend

Player profiles, inventories, and leaderboards need reliable, consistent updates. Profiles are small documents. Leaderboard scores use sharded counters or periodically computed summary documents so thousands of simultaneous updates do not choke one record. Lobbies use real-time listeners so players see each other join without refreshing.

An internal tool for a company

A small team builds a request-tracking app with sign-in through the company’s identity provider. Security rules limit each employee to their own department’s records, with manager roles allowed wider views. Because Firestore needs no server care, the tool runs for years with almost no maintenance and costs close to nothing at its tiny size.

An AI-powered help assistant

Help-center articles are stored as documents with a vector field holding a numerical fingerprint of their meaning. When a customer asks a question, the app turns the question into the same kind of fingerprint and uses vector search to fetch the closest articles. Those articles are passed to a language model as context to craft an accurate answer. Firestore handles both the structured data and the similarity search in one place.

20Frequently Asked Questions

Quick answers to the questions beginners ask most often.

Q1Is Firestore free?
It has a daily free quota per project, covering a modest number of reads, writes, and deletes plus a small amount of storage. Many learning projects and small apps stay inside it. Beyond that, you pay for usage. Check the current pricing page for exact numbers.
Q2Is Firestore SQL or NoSQL?
It is NoSQL. Data is stored as documents in collections, and you query it with SDK methods and filters, not with traditional SQL joins. The newer Enterprise edition widens query and compatibility options, so check the current documentation if you need something specific.
Q3What is the difference between Firebase and Firestore?
Firebase is Google’s app development platform with many services. Firestore is one of its databases and also a standalone Google Cloud product. You can use Firestore without using the rest of Firebase.
Q4How big can a document be?
Up to 1 MiB. If your data can grow past that, split it into subcollections or separate documents.
Q5Is Firestore strongly consistent?
Yes. After a write is confirmed, later reads and queries see it. This holds across zones and, for multi-region databases, across regions.
Q6Why does Firestore refuse some of my queries?
Because it only runs queries that an index can answer, which keeps performance predictable. The error message usually includes a link that creates the missing composite index for you.
Q7Can I run joins?
Not in the traditional database sense. You model data so common reads need no joins, by embedding or copying data, or you perform several lookups in your code. For heavy analysis, copy the data to BigQuery.
Q8Do security rules apply to my backend code?
No. Server libraries use IAM permissions, and security rules apply only to requests from client SDKs. That is why backend service accounts should have minimal permissions.
Q9Can I change the location of my database later?
No. The location is fixed at creation. To move, create a new database in the desired location and migrate data by export and import.
Q10Does Firestore work offline?
Mobile and web SDKs support offline persistence. Reads come from a local cache, and writes are queued until the network returns.
Q11How do I count documents cheaply?
Use an aggregation count query. It is computed in the database and billed much more cheaply than reading every document.
Q12Is my data backed up automatically?
Your data is replicated automatically, which protects against hardware failure. Backups and point-in-time recovery, which protect against mistakes, are features you turn on and configure.
Q13When should I not use Firestore?
Avoid it as your main store when the work is dominated by complex relational queries, heavy ad-hoc analytics, extreme write rates against a few keys, or when you must run on a different cloud or on your own hardware. Pair it with other databases when needs mix.
Q14How do I test safely before going live?
Use the Firestore emulator on your computer for rules, queries, and triggers, and keep separate databases or projects for development, staging, and production.

21Summary and Key Takeaways

If you remember only a few things from this guide, remember these.

Firestore is Google Cloud’s serverless document database. It grew from the scale of Datastore and the real-time friendliness of Firebase, and it gives developers a database that is easy to start, strongly consistent, and able to grow with an app’s audience without servers to manage. It works best when you design data around the questions your app asks, keep documents small, spread writes, protect access carefully, and watch both health and cost.

A good Firestore design is not about storing data neatly. It is about answering your app’s questions quickly, safely, and cheaply.

Key Takeaways

  • Think in documents and collections. Data lives in documents inside collections, with subcollections for lists that can grow, and documents are limited to 1 MiB.
  • Queries need indexes. Speed depends on result size, not database size, and composite indexes unlock multi-field queries.
  • Model for reads. Denormalize data that is read often and rarely changed, and avoid unbounded arrays and single hot documents.
  • Correctness is built in. Strong consistency and ACID transactions protect your data, and atomic operations such as increment keep counters safe.
  • Choose location wisely. Regional gives 99.99% availability, multi-region gives 99.999%, and the location cannot be changed afterward.
  • Secure every layer. Combine authentication, security rules, least-privilege IAM, App Check, encryption, and audit logs, and never ship open rules.
  • Plan for people and money. Replication is not backup, so enable point-in-time recovery and backups, and set budgets and alerts because you pay per operation.