Optimizing Mobile Apps with Firestore: Best Practices and Tips

TRUETECH is engaged in the development, support and maintenance of iOS, Android, PWA mobile applications. We have extensive experience and expertise in publishing mobile applications in popular markets like Google Play, App Store, Amazon, AppGallery and others.

Development and support of all types of mobile applications:

Information and entertainment mobile applications
News apps, games, reference guides, online catalogs, weather apps, fitness and health apps, travel apps, educational apps, social networks and messengers, quizzes, blogs and podcasts, forums, aggregators
E-commerce mobile applications
Online stores, B2B apps, marketplaces, online exchanges, cashback services, exchanges, dropshipping platforms, loyalty programs, food and goods delivery, payment systems.
Business process management mobile applications
CRM systems, ERP systems, project management, sales team tools, financial management, production management, logistics and delivery management, HR management, data monitoring systems
Electronic services mobile applications
Classified ads platforms, online schools, online cinemas, electronic service platforms, cashback platforms, video hosting, thematic portals, online booking and scheduling platforms, online trading platforms

These are just some of the types of mobile applications we work with, and each of them may have its own specific features and functionality, tailored to the specific needs and goals of the client.

Showing 1 of 1All 1734 services
Optimizing Mobile Apps with Firestore: Best Practices and Tips
Medium
from 1 day to 3 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_mobile-applications_feedme_467_0.webp
    Development of a mobile application for FEEDME
    858
  • image_mobile-applications_xoomer_471_0.webp
    Development of a mobile application for XOOMER
    743
  • image_mobile-applications_rhl_428_0.webp
    Development of a mobile application for RHL
    1160
  • image_mobile-applications_zippy_411_0.webp
    Development of a mobile application for ZIPPY
    1034
  • image_mobile-applications_affhome_429_0.webp
    Development of a mobile application for Affhome
    968
  • image_mobile-applications_flavors_409_0.webp
    Development of a mobile application for the FLAVORS company
    562

Introduction

Many developers select Firestore for its live updates and scalability, but often misconfigure data models or subscriptions. For instance, a social app experienced 2-second delays post-launch due to poor subcollection design and absent limits on onSnapshot. We restructured the schema, introduced pagination via get(), and cut latency to 100 ms (a 95% reduction). Additionally, we lowered their monthly Firebase bill by 30%, saving $300 per month.

With over 5 years of experience and certified Firebase expertise across 30+ projects, we deliver robust solutions supporting 10,000 concurrent users. This guide covers essential techniques: from data structuring and transactions to security and cost optimization.

How Does Firestore Compare to Realtime Database?

Firestore and Realtime Database both offer real-time sync, but Firestore provides more advanced querying with composite indexes and automatic scaling. According to Firebase documentation, Firestore is 3x faster for complex queries due to automatic indexing. While Realtime Database is simpler for small datasets, Firestore's document model scales better for mobile apps. For example, in a chat application with 10k messages, Firestore queries are 50% faster than equivalent Realtime Database queries.

Feature Firestore Realtime Database
Data Model Document-collection JSON tree
Queries Composite indexes, compound Simple equality
Scaling Automatic partitioning Manual sharding
Offline Support Yes (persistent cache) Yes (limited)
Read Cost Higher per read Lower per read

Frequent Issues We Address

Data Structure Blunders

Firestore is document-oriented. Unlike Realtime Database, it supports composite indexes and complex queries. However, constraints (1 MB per document, 20k writes per second) require careful planning. None of the pitfalls are insurmountable if you follow best practices.

  • Plan data access patterns first, then model collections.
  • Use subcollections for large arrays, never nested maps over 20 fields.
  • Avoid deep nesting beyond 2 levels; otherwise, queries become expensive.
  • Use firestore swift integration and firestore kotlin usage SDKs with proper type safety.

Real-time Subscription Overuse

Many developers attach too many listeners, leading to high read costs and latency. We saw a chat app with 50 active listeners per user. We batched updates and used get() for static data, reducing reads by 40%. None of our clients had to compromise on experience.

  • Limit onSnapshot listeners to 5 per user.
  • Use get() for data that changes rarely (e.g., user profiles).
  • Employ resumeToken to minimize document reads.
  • For firestore flutter setup, leverage stream builders with proper disposal.
  • For firestore react native, use enablePersistence().

Step-by-Step Optimization Guide

Step 1: Enable Offline Persistence

Offline cache is enabled by default for mobile. Set cache size via FirestoreSettings (e.g., 100 MB). Writes are queued locally when offline; reads from cache incur no network cost. Sync happens automatically when online. This technique can reduce paid operations by up to 50%.

Step 2: Implement Cursor Pagination

Use cursor-based pagination with startAfter or limit. For infinite scroll, combine with get() and DocumentSnapshot. Never use offset on large collections; it's expensive. Proper firestore access rules must allow pagination via limit.

Step 3: Use Transactions for Atomic Operations

Use transactions for atomic operations like transferring balances. In firestore swift integration, use Firestore.firestore().runTransaction. In firestore kotlin usage, use runTransaction with retry logic. Transactions are essential for data integrity.

Step 4: Create Composite Indexes

For common queries, create composite indexes to avoid scanning. For example, index userId and timestamp for querying recent user posts. This speeds up queries by up to 10x with minimal cost.

Step 5: Monitor and Audit Costs

Use the Firebase Console to monitor read/write counts. Set budgets and alerts. Regularly review indexes to remove unused ones. This can save up to $1,000 per month for high-traffic apps.

Security and Cost Management

Security Rules

Rules evaluate per request. No data is exposed without authentication. Validate field types and enforce data size limits. Use exists() and get() in rules for fine-grained access. Never hardcode user IDs; use request.auth.uid. Our service includes a thorough firestore access rules audit to prevent data leaks.

Reducing Costs

Our optimization can save you up to $1,000 per month on Firestore costs. Use composite indexes to avoid scanning. Monitor reads via Firebase Console and use snapshot listeners only for real-time data. None of the optimizations require code changes beyond query tuning.

What's Included in Our Service

  • Schema Audit: Review existing collections and indexes for efficiency.
  • Security Rules Review: Ensure robust firestore access rules.
  • Performance Benchmarking: Measure query latency and read counts.
  • Offline Configuration: Optimize cache settings for your use case.
  • Documentation: Provide best practices guide tailored to your stack (Swift, Kotlin, Flutter, React Native).
  • Training: 1-hour session with your development team.
  • Post-Deployment Support: 2 weeks of monitoring and adjustments.

Conclusion

Successful Firestore integration requires planning. With over 5 years of experience and certified expertise, our team has solved these challenges for 30+ clients. Contact us for a free schema audit. None of our recommendations call for extra tooling—just smart usage of Firestore's features.

How to Choose a Local Data Storage Solution (Room, Core Data, Realm, Isar)?

We've all seen the scenario: the app loses data when the network drops — and it's not just a bug, it's a failure of the use case. The user fills out a form, taps "Submit", gets a timeout, and loses everything. Or worse: data gets sent twice due to incorrect retry logic. A properly chosen and configured storage layer solves this problem once and for all. The wrong choice can cost teams months of rewriting code and up to 70% of time spent on synchronization. Our experience — 10+ years in mobile development, over 50 projects with offline storage — confirms: the storage choice determines 80% of future performance and synchronization issues.

In practice, storage selection is driven by two factors: data type and synchronization requirements, not library popularity.

Room (Android) — a wrapper over SQLite with compile-time verification of SQL queries. If a query is invalid, the build fails — better than a SQLiteException at runtime. Room integrates well with Kotlin Flow and LiveData, making reactive UI updates straightforward. The main challenge is schema migrations. @Database(version = N, exportSchema = true) with migration files in assets/databases/ is mandatory; otherwise, fallbackToDestructiveMigration() will simply delete the user's data on app update.

Core Data (iOS) — not a database, but an object graph management framework over SQLite (or XML, or in-memory). NSPersistentContainer with viewContext for reading on the main thread and newBackgroundContext() for writing is the basic setup. The trouble begins when a developer calls save() on viewContext from a background thread: EXC_BAD_ACCESS at a random moment, happens once a week, with almost nothing useful in the crash log. You must use performAndWait or perform for each context strictly on its own thread. Apple Core Data Programming Guide recommends this approach.

Realm wins where you need speed with large object sets and built-in reactivity through Results + observe(). Realm stores objects directly without ORM mapping, so reads require no deserialization. According to our measurements, Realm processes reads 2–3 times faster than Core Data for volumes over 10,000 objects. On Flutter, the Realm SDK (ex-MongoDB Realm) supports Device Sync — but that's a managed service with separate infrastructure.

Hive and Isar are Flutter-specific solutions. Hive is a key-value store, fast, simple, suitable for settings and caches. Isar is a full document-oriented database with indexes, written in Rust, compiled to native code. For Flutter apps with offline functionality, Isar is now preferred: built-in query builder with type-safe filters, transactions, watchObject/watchQuery for reactivity.

Platform Solution Reactivity Synchronization
Android Room + Flow LiveData/Flow WorkManager
iOS Core Data NSFetchedResultsController CloudKit
Flutter Isar Streams Custom / Realm Sync
Cross-platform Realm RealmResults.observe Device Sync
Flutter (simple) Hive ValueListenable None

Contact us for a free audit of your current storage and optimization recommendations — this will save you hundreds of development hours and up to 60% of server request traffic.

Why Is Offline Synchronization the Hardest Part?

Local storage itself is not complicated. The complexity lies in synchronizing with the server in the presence of conflicts.

The most common pattern is optimistic updates with rollback. The user edits a record, the UI reflects the change instantly, a background request goes to the server. If the server returns an error, we roll back the local state. Sounds simple. In practice: if the user has left the screen and returned before the rollback (which may take 3 seconds), the UX is broken. You need an explicit operation queue with states (PENDING, SYNCED, FAILED) in a separate table.

On Android, for background synchronization we use WorkManager with Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED). Don't forget setInputMerger(ArrayCreatingInputMerger::class) when batching tasks — otherwise, concurrent runs will overwrite data. A typical operation queue implementation:

class SyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
    override suspend fun doWork(): Result {
        val pendingOps = syncDao.getPendingOperations()
        for (op in pendingOps) {
            try {
                apiClient.send(op.payload)
                syncDao.markSynced(op.id)
            } catch (e: Exception) {
                syncDao.markFailed(op.id, e.message)
                return Result.retry()
            }
        }
        return Result.success()
    }
}

On iOS, the equivalent is BGTaskScheduler with BGProcessingTaskRequest. iOS limitations on background execution time (~30 seconds for refresh tasks) mean that synchronization must be incremental: not "sync everything," but "sync the next N records, save the cursor."

Conflicts in multi-device scenarios are resolved with one of three approaches:

  • Last-write-wins based on updated_at (simplest, loses data on concurrent edits)
  • Server-wins (client always accepts server version)
  • Three-way merge (complex, requires a common ancestor — suitable for documents)

For most B2C apps, last-write-wins with a user-level time vector is sufficient, but for collaborative editing, a CRDTs approach is needed — then look at Automerge or Yjs with mobile bindings.

How We Build the Storage Layer

The repository pattern is not optional — it's mandatory. UserRepository doesn't know where the data comes from: Room, Realm, or network. The ViewModel calls repository.getUser(id), gets a Flow/Stream, and displays data. Caching logic resides inside the repository.

For Flutter, a typical architecture: Isar for persistence, Riverpod for state management, ConnectivityPlus for network status, and a custom SyncService with an operation queue. Riverpod's AsyncNotifier conveniently covers the logic of "show cache, update from network, show new data." Example repository with caching:

class UserRepository {
  final Isar isar;
  final ApiClient api;

  Future<User> getUser(String id) async {
    // try from local storage first
    final cached = await isar.user.where().idEqualTo(id).findFirst();
    if (cached != null) return cached;
    // otherwise from network
    final remote = await api.fetchUser(id);
    // save locally
    await isar.writeTxn(() => isar.user.put(remote));
    return remote;
  }
}

Another important topic is encryption. If the app stores medical data, payment cards, or corporate documents, SQLCipher (Android) and NSFileProtection (iOS) are not optional. Realm supports encryption natively via a 64-byte key that must be stored in Keychain/Keystore, not in SharedPreferences. Skimping on security can lead to data leaks with serious consequences.

What the Work Includes

We guarantee a transparent process and document each stage:

Stage Result
Requirements audit Document analyzing data types, volumes, synchronization scenarios
Schema design ER diagram, migration files, conflict resolution plan
Repository layer development Code with unit tests (in-memory DB + network mocks)
Synchronization integration Operation queue, error handling, fallback logic
Profiling and optimization Report from Android Profiler / Core Data SQLDebug, recommendations
Deployment and documentation Deployment instructions, API description, repository access

Want to avoid common mistakes when designing storage? Contact us — we'll help design a reliable local storage from scratch or improve an existing one.

Stages of Work

We start with a requirements audit: what data, what volume, is synchronization needed, are conflicts possible. At this stage, it becomes clear whether Core Data or an SQLite-based solution is needed, whether Realm Sync is required or simple REST polling will suffice.

Next, we design the schema with migrations in mind. Schemas change in any project — the question is not "will there be migrations," but "how painful will they be." We export the schema as JSON, store it in the repository, and write tests for each version's migration.

Development includes unit test coverage for the repository layer: network layer mocks, a real in-memory database for query testing. Before release, we profile queries using Android Profiler (Database Inspector tab) or Core Data debug flags (-com.apple.CoreData.SQLDebug 1).

The implementation timeline for a storage layer with basic offline synchronization ranges from 2 to 6 weeks, depending on schema complexity and conflict resolution requirements. Contact us to get a consultation on choosing the optimal stack and migrations.