DEV Community

Cover image for 8 Separate Database Flow Queries Consolidated Into 3 Shared Hot Streams — Performance Impact?
DEVANSHU PATIL
DEVANSHU PATIL

Posted on

8 Separate Database Flow Queries Consolidated Into 3 Shared Hot Streams — Performance Impact?

8 Separate Database Flow Queries Consolidated Into 3 Shared Hot Streams — Performance Impact?

Room's reactive database queries are one of the most powerful features in modern Android development:

// The Room Reactive Dream
@Query("SELECT * FROM transactions WHERE dateTimestamp >= :start")
fun getMonthlyTransactions(start: Long): Flow<List<TransactionEntity>>
Enter fullscreen mode Exit fullscreen mode

You return a Flow, collect it in your ViewModel, and whenever data in SQLite changes, your UI automatically receives the fresh list. It feels like magic.

However, when you start building rich data visualization screens—such as spending analytics, monthly category breakdowns, and yearly net worth charts—that magic can quickly turn into a database bottleneck.

During Hardening Sprint H6 (docs/HARDENING_SPRINTS.md:H6.3), a performance audit of our ReportsViewModel.kt revealed that a single screen was mounting eight independent cold Flow queries against SQLite simultaneously.

Every time a single transaction was logged, SQLite's invalidation tracker triggered eight concurrent database reads, causing disk lock contention and freezing UI scrolling.

Here is how we consolidated eight redundant database observers into three shared hot streams, cutting database churn by 62% and reducing screen load times by 70%.

The Cold Observer Explosion

Consider what happens when a screen needs multiple perspectives on the same financial dataset:

flowchart TD
    subgraph ColdObserverStorm["The Eight Concurrent Cold Observers (Pre-Audit)"]
        RoomDB["Room SQLite Invalidation Tracker"]

        RoomDB --> Q1["Query 1: Monthly Expenses Flow"]
        RoomDB --> Q2["Query 2: Monthly Income Flow"]
        RoomDB --> Q3["Query 3: Category Breakdown Flow"]
        RoomDB --> Q4["Query 4: Yearly Cash Flow Flow"]
        RoomDB --> Q5["Query 5: Liquid Bank Accounts Flow"]
        RoomDB --> Q6["Query 6: Credit Card Balances Flow"]
        RoomDB --> Q7["Query 7: Investment Assets Flow"]
        RoomDB --> Q8["Query 8: Active Categories Flow"]

        Q1 --> Contention["SQLITE DISK LOCK CONTENTION:
        8 parallel background workers competing for SQLite read locks!
        Disk I/O spikes, thread queues block, UI drops frames."]
        Q2 --> Contention
        Q3 --> Contention
        Q4 --> Contention
        Q5 --> Contention
        Q6 --> Contention
        Q7 --> Contention
        Q8 --> Contention
    end

Every time you declare @Query ... : Flow<T> in Room, Room registers a dedicated table invalidation observer.

When you insert a Rs. 200 coffee transaction into SQLite:

  1. Room invalidates the transactions table.
  2. All eight queries wake up simultaneously.
  3. Eight separate database cursor transactions are dispatched to SQLite.
  4. SQLite—which operates with file-level concurrency limits—must serialize these reads, forcing coroutines to wait in disk I/O queues.
  5. Eight separate entity-to-domain mapping loops execute in memory.

We were asking the database to query the exact same table rows four different times just to group them differently!

The Solution: Shared Upstream Hot Streams (combine)

The database is an engine for durable storage, not a formatting playground.

If a screen needs monthly expenses, monthly income, and category breakdowns for November, it does not need three different SQL queries. It needs one single query that loads November's transactions once. The mathematical grouping into income, expenses, and categories should occur in high-speed device RAM!

In Sprint H6, we redesigned the architecture around three shared hot streams:

flowchart TD
    subgraph ConsolidatedPipeline["The Three Consolidated Hot Streams"]
        direction TB

        subgraph Stream1["Stream 1: Monthly Transactions (Shared StateFlow)"]
            DB1["Single Room Query:
            getTransactionsInRange(start, end)"] --> Cache1["Shared In-Memory StateFlow"]
        end

        subgraph Stream2["Stream 2: Active Accounts (Shared StateFlow)"]
            DB2["Single Room Query:
            getAllActiveAccounts()"] --> Cache2["Shared In-Memory StateFlow"]
        end

        subgraph Stream3["Stream 3: Category Taxonomy (Shared StateFlow)"]
            DB3["Single Room Query:
            getAllCategories()"] --> Cache3["Shared In-Memory StateFlow"]
        end

        Cache1 --> CombineNode["Kotlin combine() on Dispatchers.Default"]
        Cache2 --> CombineNode
        Cache3 --> CombineNode

        CombineNode --> MemoryMath["Pure In-Memory Math Kernel:
        - Filters expenses in RAM
        - Groups categories in RAM
        - Computes net cash flow in RAM (< 1.2 ms)"]

        MemoryMath --> FinalUI["ReportsUiState Emitted to Compose"]
    end

1. The Single Upstream Range Query

Instead of four fragmented transaction queries, ReportsViewModel observes a single query:
transactionRepository.getTransactionsInRange(monthStart, monthEnd)
When a transaction is inserted, SQLite executes exactly one read query.

2. High-Speed In-Memory Grouping

Once the list of monthly transactions arrives in memory on Dispatchers.Default, pure Kotlin functions perform the transformations:

  • transactions.filter { it.isExpense } $\rightarrow$ Monthly Expenses
  • transactions.filter { it.isIncome } $\rightarrow$ Monthly Income
  • transactions.groupBy { it.categoryId } $\rightarrow$ Category Breakdown

Executing these filter and grouping operations on 1,000 in-memory Kotlin objects takes less than 1.2 milliseconds—over 50 times faster than spinning up SQLite database cursors!

3. Combining Streams with StateFlow

Using Kotlin's combine(transactionsFlow, accountsFlow, categoriesFlow) operator, the three streams are synthesized into a single, unified ReportsUiState.

Because the upstream flows are shared hot streams (SharingStarted.WhileSubscribed(5000)), navigating between reports tabs or rotating the phone consumes the existing in-memory state instantly without querying SQLite again.

Performance Profile in Sprint H6

Metric 8 Cold Observers (Pre-Audit) 3 Shared Hot Streams (Post-H6)
SQLite Invalidation Observers 8 registered observers 3 registered observers (-62%)
Concurrent Disk Read Locks 8 parallel locks 1 lock at a time
Screen Initial Render Time 185 ms 54 ms (-70%)
Transaction Ingestion Latency 42 ms 8 ms

Key Takeaway

Do not abuse Room's reactive queries by declaring a separate SQL query for every widget on your screen.

Load your datasets in broad, cohesive ranges, consolidate your database observers into shared hot streams, and let your smartphone's multi-core CPU handle filtering and grouping in memory. Your database will stay fast, your disk locks will disappear, and your UI will render smoothly at 60 frames per second.


FinLedger is a privacy-first, offline-first personal finance application for Android that models bank accounts, credit cards, and cash without double-counting.

Explore FinLedger on Google Play: https://play.google.com/store/apps/details?id=com.devanshufinance.app

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The 185ms → 54ms render drop is the number that sells it, but the part I'd watch is the other end of the trade: you moved the grouping out of SQLite and into RAM, which is a clear win at 1,000 objects in under 1.2ms. At what size does that flip — a power user with a few years of transactions inside one month range — or does the month-bounded query keep the list small enough that it never matters? And with WhileSubscribed(5000), does leaving the Reports screen for more than five seconds cost you a re-query on the way back, or is the re-run cheap enough that tab-switching never stutters?