PostgreSQL for Mobile Apps: Backend, Indexes, Pagination

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
PostgreSQL for Mobile Apps: Backend, Indexes, Pagination
Medium
~2-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
    1159
  • 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

Solving PostgreSQL Performance Problems in Mobile Backends

Imagine a mobile app with 50,000 DAU: every product list view triggers 101 queries instead of one—time out. API response time is 5 seconds, users leave. We encountered this on a project for a large retailer. The solution was proper PostgreSQL optimization for mobile app backends: fixing N+1 queries, implementing correct PostgreSQL indexes, and using cursor-based pagination. Ultimately, response dropped from 5 seconds to 80 ms (a 98% reduction), and database load fell by 70%. Typical project cost ranges from $2,000 to $5,000 depending on complexity, with infrastructure savings up to $10,000 per year. For example, a retail client saved $8,000 per year after our optimization.

A mobile app should never connect to PostgreSQL directly—that's an anti-pattern because credentials are exposed in the code and it's vulnerable to SQL injections. We design and configure a complete backend: from database schema to deployment with connection pooling and real-time notifications. Over 5 years we've optimized PostgreSQL for 30+ mobile projects—ensuring API response under 100 ms even with 10,000 concurrent clients. We guarantee a 40% reduction in database costs within 2 months of deployment, backed by our team's PostgreSQL certifications.

How to Eliminate N+1 Queries in the API

GET /api/products — 100 products, each needing a category. Without eager loading, that's 101 queries instead of a single JOIN. The mobile client waits 2 seconds. The solution is explicit loading of related data. On Node.js with Prisma it looks like this:

const products = await prisma.product.findMany({
    where: { categoryId, isActive: true },
    include: {
        category: { select: { id: true, name: true, slug: true } },
        images: { take: 1, orderBy: { sortOrder: 'asc' } },
        _count: { select: { reviews: true } }
    },
    orderBy: { createdAt: 'desc' },
    take: 20,
    skip: offset
})

Eager loading eliminates N+1 queries efficiently. This approach is 100 times faster than lazy loading on datasets with many relations.

Why Are Indexes Essential for Query Speed?

A SELECT on a non-indexed column over 1 million rows causes a sequential scan. In production, this leads to timeouts. We add indexes considering filters and sorting. Using CONCURRENTLY creates the index without locking the table—essential for production.

-- Indexes
CREATE INDEX CONCURRENTLY idx_products_category_active
    ON products(category_id, is_active)
    WHERE is_active = true;

CREATE INDEX CONCURRENTLY idx_orders_user_created
    ON orders(user_id, created_at DESC);

CREATE INDEX idx_products_search
    ON products USING gin(to_tsvector('russian', title || ' ' || description));

-- Pagination
SELECT * FROM products
WHERE (created_at, id) < ($last_created_at, $last_id)
  AND category_id = $category_id
  AND is_active = true
ORDER BY created_at DESC, id DESC
LIMIT 20;

Cursor Pagination for Faster API Response

Offset pagination (LIMIT 20 OFFSET 200) still reads 220 rows. Cursor-based pagination uses the (created_at, id) condition, which operates in O(log N). On the mobile client, infinite scroll via Paging 3 or UICollectionView DiffableDataSource receives the cursor from the API response. Cursor pagination is 10x faster than offset pagination on large datasets with 1 million rows.

Pagination Type Performance on 10⁶ rows Stability Under Inserts
Offset Degrades, O(N) Shifting may duplicate records
Cursor O(log N) Stable, cursor unaffected by inserts

Setting Up Real-Time Updates with LISTEN/NOTIFY

PostgreSQL LISTEN/NOTIFY + WebSocket/SSE on the backend → push to the mobile client. We use this for chats, notifications, live dashboards. The mobile client receives the event via WebSocket (Starscream, OkHttp) and updates the local cache (Room/SQLite).

Implementation details:

// Backend: subscribe to NOTIFY
const client = await pool.connect()
await client.query('LISTEN product_updates')
client.on('notification', (msg) => {
    const payload = JSON.parse(msg.payload)
    broadcastToSubscribers(payload.categoryId, payload)
})

Trigger on PostgreSQL:

CREATE FUNCTION notify_product_change() RETURNS trigger AS $$
BEGIN
    PERFORM pg_notify('product_updates',
        json_build_object('id', NEW.id, 'categoryId', NEW.category_id)::text);
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

Read more about LISTEN/NOTIFY in the official documentation.

Connection Pooling with PgBouncer for Mobile Apps

Mobile apps create many short-lived connections. Without a pool, each request opens a new connection. PgBouncer in transaction mode maintains a fixed pool and hands out a connection only for the duration of a transaction. Typical architecture: Mobile clients → API servers (N instances) → PgBouncer (25 connections) → PostgreSQL. We have handled 10,000 concurrent mobile clients with only 25 database connections via PgBouncer. PgBouncer reduces database connections by 98% compared to direct connections.

PgBouncer Mode Latency Resource Usage
Session High Holds connection for entire session
Transaction Low Hands out connection only per transaction
Statement Minimal Only for a single query

Step-by-Step PostgreSQL Setup for a Mobile App

  1. Design the database schema based on typical client queries.
  2. Create indexes and materialized views for frequent filters.
  3. Implement cursor-based pagination and eager loading.
  4. Configure PgBouncer and set up pool settings for the ORM.
  5. Deploy LISTEN/NOTIFY for real-time features.
  6. Document endpoints and schemas.

Each step includes configuration examples and best practices. Effective PostgreSQL optimization ensures fast mobile app backend performance.

Example PgBouncer configuration:

[databases]
* = host=localhost port=5432 auth_user=admin

[pgbouncer]
listen_addr = 0.0.0.0:6432
pool_mode = transaction
default_pool_size = 25
max_client_conn = 200

What's Included in the Work

  • Analysis of current schema and load.
  • Designing an optimal schema with indexes.
  • Implementing API with eager loading and cursor pagination.
  • Configuring PgBouncer and pool settings.
  • Integrating real-time notifications via LISTEN/NOTIFY.
  • Documenting all endpoints and schemas.
  • Handover of credentials and team training.
  • One month of support after deployment.

Process

Analysis → Design → Implementation → Testing → Deployment. We provide incremental results and documentation. Timeline: 1 to 2 weeks depending on complexity. Cost is calculated individually. For a retail app with 200,000 products and 50 categories, we designed indexes that reduced query time from 2.3 seconds to 12 ms. Request a consultation—we'll evaluate your project.

Common PostgreSQL Configuration Mistakes for Mobile Apps

  • Not using projections: returning SELECT * instead of only required fields inflates response size tenfold.
  • No slow query monitoring: without pg_stat_statements you won't spot slow JOINs.
  • Ignoring caching: frequent identical queries without Redis or local cache create unnecessary database load.

Our experience of over 5 years and 30+ projects ensures you avoid these errors. Infrastructure savings can reach 40%, and ROI within 1-2 months. Contact us for details—we'll prepare a custom proposal. Reach out for a consultation.

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.