Optimize Database Performance

There are a few different ways to improveFirebase Realtime Databaseperformance in your app. To find out what you can do to optimize yourRealtime Database performance, gather data through the differentRealtime Databasemonitoring tools, then make changes to your app orRealtime Database use accordingly.

MonitorRealtime Database performance

You can gather data about yourRealtime Database's performance through a fewdifferent tools, depending on the level of granularity you need:

  • High-level overview: Use thethe profiler toolfor a list of unindexed queries and a realtime overview of read/writeoperations.
  • Billed usage estimate: Use theusage metricsavailable in theFirebase consoleto see your billed usage and high-level performance metrics.
  • Detailed drilldown: UseCloud Monitoringfor a more granular look at how your database is performing over time.
Check for bugs:Before you start implementing any changes to your app, verify that it'ssyncing data the way you originally intended. To pinpoint issues, turn on debuglogging in theAndroid,Objective-C, andWeb SDKs. Check background and sync processes in your app to make sure it's downloading data at the frequency and volume you intended.

Improve performance by metric

Once you've gathered data, explore the following best practices and strategiesbased on the performance area you want to improve.

Performance improvement strategies at-a-glance
MetricDescriptionBest practices
Load/UtilizationOptimize how much of your database's capacity is in use processing requests at any given time (reflected in **Load** or **io/database_load** metrics).Optimize your data structure
Shard data across databases
Improve listener efficiency
Limit downloads with query-based rules
Optimize connections
Active connectionsBalance the number of simultaneous, active connections to your database to stay under the 200,000-connection limit.Shard data across databases
Reduce new connections
Outgoing bandwidthIf the downloads from your database seem higher than you want them to be, you can improve the efficiency of your read operations and reduce encryption overhead.Optimize connections
Optimize your data structure
Limit downloads with query-based rules
Reuse SSL sessions
Improve listener efficiency
Restrict access to data
StorageMake sure you're not storing unused data, or balance your stored data across other databases and/or Firebase products to remain under quota.Clean up unused data
Optimize your data structure
Shard data across databases
UseCloud Storage for Firebase

Optimize connections

RESTful requests likeGET andPUT still require a connection, even thoughthat connection is short-lived. These frequent, short-lived connectionscan actually add up to significantly more connection costs, database load, andoutgoing bandwidth than realtime, active connections to your database.

Whenever possible, use the native SDKs for your app's platform, instead of theREST API. The SDKs maintain open connections, reducing the SSL encryption costsand database load that can add up with the REST API.

If you do use the REST API, consider using an HTTP keep-alive to maintain anopen connection or useserver-sent events,which can reduce costs from SSL handshakes.

Shard data across multiple databases

Splitting your data across multipleRealtime Database instances, otherwise known asdatabase sharding, offers three benefits:

  1. Increase the total simultaneous, active connections allowed on your app bysplitting them across database instances.
  2. Balance load across database instances.
  3. If you have independent groups of users that only need access to discretedata sets, use different database instances for higher throughput and lowerlatency.

If you're on theBlaze pricing plan, you can create multipledatabase instances within the same Firebase project, leveraging a common userauthentication method across database instances.

Learn more about how and when toshard data.

Build efficient data structures

BecauseRealtime Database retrieves the data from a path's child nodes as well asthe path, it makes sense to keep your data structure as flat as possible.This way, you can selectively retrieve the data you need, without alsodownloading unnecessary data to clients.

In particular, consider writes and deletes when you're structuring your data.For example, paths with thousands of leaves are potentially expensive to delete.Splitting them up into paths with multiple subtrees and fewer leaves per nodecan speed up deletes.

Additionally, each write can take up 0.1% of your total database utilization.Structure your data in a way that allows you to batch writes into a singleoperation as multi-path updates through either theupdate() methods in theSDKs or RESTfulPATCH requests.

To optimize your data structure and improve performance, follow thebest practices for data structures.

Prevent unauthorized access

Prevent unauthorized operations on your database withRealtime Database Security Rules. For example, using rules could avoid a scenario where amalicious user repeatedly downloads your entire database.

Learn more aboutusing Firebase Realtime Database Rules.

Use query-based rules to limit downloads

Realtime Database Security Rules restrict access to data in your database, but they can alsoserve as limits on data returned through read operations. When you usequery-based rules, as defined byquery. expressions likequery.limitToFirst,queries only retrieve the data bounded by the rule.

For example, the following rule limits read access to only the first 1000results of a query, as ordered by priority:

messages: {  ".read": "query.orderByKey &&            query.limitToFirst <= 1000"}// Example query:db.ref("messages").limitToFirst(1000)                  .orderByKey("value")

Learn more aboutRealtime Database Security Rules.

Index queries

Indexing your data reduces the totalbandwidth you use for each query your app runs.

Reuse SSL sessions

Reduce SSL encryption overhead costs on resumed connections by issuingTLS session tickets. This is particularlyhelpful if you do require frequent, secure connections to the database.

Improve listener efficiency

Place your listeners as far down the path as you can to limit the amount of datathey sync. Your listeners should be close to the data you want them to get.Don't listen at the database root, as that results in downloads ofyour entire database.

Add queries to limit the data that your listen operations return and uselisteners that only download updates to data — for example,on() instead ofonce(). Reserve.once() for actions that truly don’t require data updates.Additionally, sort your queries usingorderByKey(), whenever possible, for thebest performance. Sorting withorderByChild() can be 6-8 times slower, andsorting withorderByValue() can be very slow for large data sets, since itrequires a read of the entire location from the persistence layer.

Make sure to also add listeners dynamically, and remove them when they're nolonger necessary.

Clean up unused data

Periodically remove any unused or duplicate data in your database. You canrunbackups to manually inspect your data orperiodically back it up to aGoogle Cloud Storage bucket. Alsoconsider hosting stored data throughCloud Storage for Firebase.

Ship scalable code you can update

Apps built into IoT devices should include scalable code that you canupdate easily. Make sure to test use cases thoroughly, account for scenarioswhere you might grow your userbase exponentially, and build in the abilityto deploy updates to your code. Carefully consider major changes you might needto make down the line, if, for example, you decide to shard your data.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-11 UTC.