Room has no lazy loading: when a music app reads artists with their albums and each album's songs through nested @Relation classes, how many queries run, and what does that cost?
answer
- everything arrives before the call returns
- one query per relation level
- keys batched, not one per row
- 999 keys per child query
- load what the screen draws
basics
~20 sRoom reads the whole artist, album and song graph eagerly: one parent query, then one query per relation level for each batch of up to 999 keys. It avoids one query per row, but loads every child row whether the screen shows it or not.
solid answer
~50 sRoom forbids object references between entities and never fetches a relation on property access, because a lazy fetch would usually run on the UI thread. A nested read resolves the whole graph before returning: one query for the artists, one for the albums of all collected artist keys, one for the songs of all collected album keys, each child level split into batches of at most 999 keys. With 500 artists and 2,000 albums that is five queries (1 + 1 + 3), not 2,501. The cost is volume, not round trips: every song of every album is materialised even if the screen shows only names and counts, all inside one `@Transaction`. The fix is shaping each read to its screen: fewer nesting levels, a smaller class via `entity =` and `projection`, or an aggregate join query returning a multimap with `@MapColumn`.
code
kotlin · 25 linesdata class AlbumWithSongs(
@Embedded val album: Album,
@Relation(
parentColumns = ["albumId"],
entityColumns = ["albumOwnerId"]
)
val songs: List<Song>
)
data class ArtistWithAlbumsAndSongs(
@Embedded val artist: Artist,
@Relation(
entity = Album::class,
parentColumns = ["artistId"],
entityColumns = ["artistOwnerId"]
)
val albums: List<AlbumWithSongs>
)
@Dao
interface LibraryDao {
@Transaction
@Query("SELECT * FROM Artist")
suspend fun library(): List<ArtistWithAlbumsAndSongs>
}go deeper
Recall that Room never loads a relation on property access; everything a @Relation describes is read before the DAO function returns.
Explain the query sequence: one parent query, then one query per relation level, with keys batched up to 999 per child query.
Diagnose the real cost as rows materialised rather than round trips, and fix it by cutting levels, narrowing columns with entity and projection, or aggregating in SQL.
Argue for per-screen read shapes over one shared deep model, since Room's eager relations make an all-purpose graph cost every screen its full volume.
## Why Room has no lazy loading Many object-relational mappers let `album.songs` run a query the first time you touch it. Room deliberately does not. Its documentation explains the reasoning: - On a phone, the property access that triggers a lazy load usually happens **on the UI thread**, while drawing. - The UI thread has roughly **16 ms** to lay out and draw a frame; even a 5 ms query can make the app miss frames, and disk contention makes it worse. - The opposite habit, fetching more than needed "just in case", wastes memory, and a model shared between the database and the UI drifts until nobody knows what a screen loads. So Room **disallows object references between entities** and makes you ask for related data explicitly, in a query or a relation result class. A `@Relation` is therefore always **eager**: everything it describes is loaded before the DAO function returns. ## How many queries a nested read runs Take a music library: `Artist`, `Album` (with `artistOwnerId`) and `Song` (with `albumOwnerId`). The nested result classes are `AlbumWithSongs(@Embedded album, @Relation(...) songs: List<Song>)` and `ArtistWithAlbumsAndSongs(@Embedded artist, @Relation(entity = Album::class, ...) albums: List<AlbumWithSongs>)`. Note `entity = Album::class`: the list's element type is a result class, so Room must be told which entity backs it. Calling `@Transaction @Query("SELECT * FROM Artist") suspend fun library(): List<ArtistWithAlbumsAndSongs>` makes Room's generated code: 1. Run your artist query and collect every `artistId`. 2. Run **one album query** for those keys. Room's relation helper splits the keys into batches of at most **999**, one query per batch. 3. Collect every `albumId` from those albums and run **one song query per batch** of up to 999 album keys. 4. Assemble the tree in memory and return it. | Data | Artist queries | Album queries | Song queries | Total | |---|---|---|---|---| | 500 artists, 2,000 albums | 1 | 1 (500 keys) | 3 (999 + 999 + 2 keys) | 5 | | 50 artists, 300 albums | 1 | 1 | 1 | 3 | That is the good news: Room never issues one query per parent row, the classic N+1 pattern. A relation through a `Junction` is resolved the same way, in batched queries per level. ## What it costs The bad news is volume. Every level is fully materialised: - **Memory.** All 2,000 albums and every one of their songs become objects, even if the screen lists artist names with an album count. - **Time inside a transaction.** The whole read runs under one `@Transaction`, so it takes longer than the screen needs and keeps its transaction open for that long. - **Re-reads.** A query observed through a `Flow` re-runs the whole tree when any of the three tables changes; how that invalidation works is covered with Room's coroutine and Flow support. Room's own guide carries the caution: nested relationships make Room manipulate a large volume of data, so use as few as possible. ## Shaping the read to the screen Because nothing is lazy, the lever is the **shape of each DAO function**: - **Drop levels the screen does not draw.** An artist list rarely needs songs; read `ArtistWithAlbums` there and `AlbumWithSongs` on the album screen. - **Read fewer columns.** `entity = Album::class` with a small data class, or `entity = Album::class` plus `projection = ["title"]` with a `List<String>`, keeps the child query narrow. - **Aggregate in SQL.** For counts, a join query such as `SELECT Artist.*, COUNT(Album.albumId) AS albumCount FROM Artist LEFT JOIN Album ON ... GROUP BY Artist.artistId` returned as `Map<Artist, @MapColumn(columnName = "albumCount") Int>` reads one row per artist instead of every album. - **Page the parent.** Fewer parents means fewer child keys; Room's Paging return type is covered with its coroutine and Flow support. ## Diagnosing it in an interview scenario When "the library screen got slow after users imported large collections" comes up, the senior answer names the mechanism: the query count stayed small, but each nested `@Relation` loads its whole level, so cost grows with the number of child rows, not with the number of round trips. Measure what the screen draws, then cut levels and columns until the read matches it: 1. Count the rows each level returns for a heavy user's library, not for the test fixture. 2. Compare them with what the screen actually renders on first draw. 3. Remove the levels and columns that comparison exposes, then measure again.
- Why must the outer `@Relation` set `entity = Album::class`?Its list holds `AlbumWithSongs`, a result class rather than an entity, so Room cannot infer which table to query from the element type. `entity` names the backing entity; Room reads `Album` rows for the outer relation and then resolves the inner relation on each `AlbumWithSongs`.
- The artist screen shows names and album counts. What read replaces the nested relation?A single aggregate join, `SELECT Artist.*, COUNT(Album.albumId) AS albumCount FROM Artist LEFT JOIN Album ON Album.artistOwnerId = Artist.artistId GROUP BY Artist.artistId`, returned as `Map<Artist, @MapColumn(columnName = "albumCount") Int>`. One row per artist, no album or song objects.
Ordering a box set by mail: the whole set arrives in a few deliveries before you open anything, never one courier per disc as you reach for it, so ordering the set when you wanted one disc is the real waste.
- Room fetches album songs lazily the first time the list is read
- A nested relation runs one query per parent row, the N+1 problem
- Using Set instead of List makes Room load fewer child rows
- @Transaction on the read reduces how many rows Room loads
- Kotlin's by lazy on a @Relation property defers Room's query