In an offline language-learning app with 20,000 flashcards, the due-today screen gets slower as the deck grows; what is happening, and what fixes it?
answer
- a scan plus a sort
- the observer re-runs it
- read the query plan
- equality column first, then the range
- no function around the column
basics
~20 sWithout a matching index the query scans and sorts every card, and the observing screen repeats that after each grade; a composite index on deck and due time turns it into a short, already ordered range read.
solid answer
~40 sThe query filters by deck and due time and sorts by due time. With no matching index the database reads all 20,000 rows and sorts the matches, and because the screen observes the query, that scan re-runs after every graded card. I check the query plan, then add a composite index on `(deck_id, due_at)`, so the database seeks to the deck, reads the due range already in order and stops at the `LIMIT`. I store `due_at` as a number and compute the end of today in the learner's time zone in the app, because wrapping the column in a date function usually stops the index being used. Every index costs disk and write time, so I index the queries the screens actually run.
go deeper
Recall that an index lets a database find rows without reading the whole table, and that every index costs some write time and space.
Explain how a composite index serves an equality filter plus a range and sort, and why column order and a function on the column matter.
Diagnose from the query plan, connect the observed query's re-runs to the stutter, and prevent regressions with a worst-case seeded database in tests.
Set performance budgets for local queries across the app and decide how query plans are reviewed when teams add screens over a shared database.
This is a diagnosis question: the screen was fine in testing with a few hundred cards and grows sluggish for learners who have studied for a year. The interviewer wants the candidate to reason from how an embedded relational database executes the query, not to reach for a bigger thread pool. ## Why it degrades with size The due-today screen runs a query like this one: ```sql SELECT id, front, back, due_at FROM card WHERE deck_id = ? AND due_at < ? -- end of today, computed in the learner's time zone ORDER BY due_at LIMIT 50; ``` With no index on these columns, the database's only option is a **full table scan**. It reads all 20,000 rows, keeps the ones in the deck that are due, sorts them by `due_at` and returns the first 50. The cost grows with the size of the whole deck, not with the number of cards due today. Two things in a mobile app make it worse: - **The query is observed.** The screen subscribes to it, and each graded card writes the `card` table, so while the screen stays subscribed the scan runs again after every grade. Thirty grades in a session mean thirty full scans. - **The badge asks too.** A due-count badge on the home screen often runs a second scan with `COUNT(*)` over the same condition. ## Read the query plan Embedded SQL engines can explain how they will run a query (an `EXPLAIN`-style command). A plan that says it scans the table, or that it builds a temporary structure to sort, confirms the diagnosis. Checking the plan beats guessing, because a query can look indexed and still not use the index. ## The composite index ```sql CREATE INDEX card_deck_due ON card (deck_id, due_at); ``` An index here is a **B-tree** sorted by `deck_id`, then by `due_at` within each deck, pointing at the rows. With it the database: 1. seeks straight to the first entry for the deck, 2. reads entries in `due_at` order while they are before the end of today, 3. stops after 50, with no separate sort step. The work now grows with the number of due cards read, not the deck size, and the badge's count reads only the due range of the index. Assuming, as this scenario does, 150 cards due today, the list reads at most 50 index entries and the count about 150, where each scan read all 20,000 rows. **Column order matters:** put the equality column (`deck_id`) first and the range and sort column (`due_at`) second. Reversed, the range comes first and the deck filter is applied entry by entry across every deck. ## Keep the column indexable - **No function around the indexed column.** `WHERE date(due_at) = today` usually prevents the index from being used, because the index stores `due_at`, not `date(due_at)`. Compare the raw column with precomputed bounds instead. - **Compute "today" in the app.** "Due today" means before the end of the learner's local day; compute that instant in the app, accounting for the learner's time zone, and pass it as a parameter. - **One type per column.** Store `due_at` consistently, for example as seconds since the epoch, so comparisons and ordering behave as the index expects. ## What indexes cost | Benefit | Cost | |---|---| | Range reads and sorted reads without a scan | Every insert or update of the indexed columns also updates the index | | Cheap counts over a range | Extra disk space for the index | | Faster joins on the indexed column | More work in each schema change that touches it | So index the queries the screens actually run, not every column. A card grade writes one row and updates at most a few index entries, which is cheap next to thirty scans. ## Off the UI thread, and kept from regressing Even an indexed query belongs off the UI thread, because a slow storage chip or a busy device can still stall it; moving a scan to a background thread hides jank but leaves the battery and time cost. To stop the problem returning, seed a test database at the scenario's worst case (say 50,000 cards), assert that the main screens' query plans use their indexes and time them on a low-end device before each release.
- Why does column order matter in the composite index?The index is sorted by its first column, then by the second within each value of the first. With the deck first, an equality on the deck and a range on due time read one contiguous, ordered stretch. With due time first, the database walks due entries for every deck and filters by deck as it goes.
- How do you stop this kind of slowdown from coming back as features add queries?Keep a seeded test database at the scenario's worst case, say 50,000 cards, assert in a test that the main screens' query plans use their indexes, and time those queries on a low-end device. A plan that silently falls back to a scan is caught before release rather than by learners.
- An embedded database is local, so every query is fast enough without indexes.
- Indexing every column is free and makes every query faster.
- Wrapping the indexed column in a date function still lets the index be used.
- Moving the slow query to a background thread solves the problem completely.
- Query cost depends only on how many rows the query returns.