LazyColumn throws the key was already used error when two rows return the same key. The full message is IllegalArgumentException: Key "43" was already used. Two causes stack up. First, keys share one namespace across the whole LazyColumn. A post that sits in both a “Pinned” section and a “Latest” section gets it.id twice. Each items() call doesn’t get its own key space. Second, Compose doesn’t validate keys up front. The check runs inside SubcomposeLayout while a row is composed. It only fails when both copies are composed in the same measure pass. So the screen works for weeks while the pinned post is old and far down the list. Then someone pins a fresh post that also sits near the top of Latest. The app crashes on the first frame for every user who opens the feed. The fix is a unique key per section. Prefix them like "pinned:$id" and "latest:$id". Keep them stable and Bundle-saveable.
A pinned post that crashes the feed only when it is also new
The running example is a community feed. The top of the screen shows pinned posts. Below that comes every post, newest first. A pinned post appears in both places on purpose. The screen below is trimmed to the list itself.
data class Post(val id: Long, val title: String, val pinned: Boolean)
@Composable
fun FeedScreen(latest: List<Post>) {
val pinned = latest.filter { it.pinned }
LazyColumn {
item { SectionHeader("Pinned") }
items(pinned, key = { it.id }) { post -> PostRow(post) }
item { SectionHeader("Latest") }
items(latest, key = { it.id }) { post -> PostRow(post) }
}
}
Each items() block looks correct on its own. Every post has a unique database ID. Each block uses that ID as the key. The Compose lists guide recommends exactly this pattern. On most days, nothing goes wrong. The pinned post is a rules post from last month. It sits 25 rows down in Latest. Then a moderator pins post 43. It was published an hour ago. The app now crashes as soon as the feed opens, with this message.
java.lang.IllegalArgumentException: Key "43" was already used. If you are using LazyColumn/Row please make sure you provide a unique key for each item.
Keys share one namespace across every items() block in the LazyColumn
The first cause is a wrong mental model. Candidates picture each items() call as its own little list. It isn’t. The LazyColumn DSL appends every item and items call into one list of intervals. The NearestRangeKeyIndexMap source walks all those intervals and builds one key-to-index map for the whole layout. The KDoc on LazyListScope.items states the rule. The same key for multiple items “in the list” isn’t allowed. The list means the entire LazyColumn.
So the feed above produces these keys, in order. The two headers have no explicit key. Compose gives them a default key based on their index. That default type can’t equal a Long, so the headers are safe.
index: 0 1 2 3 4 5 6 7 key: header 43 header 45 44 43 42 41
Rows 1 and 5 both claim key 43. The data is valid, because the same post really is in two sections. The keys are invalid, because one namespace now holds two entries for one value.
There’s a quieter effect even when nothing crashes. The key map stores map[key] = i for each row in order, so a repeated key keeps its last index. LazyListScrollPosition uses that map to keep the first visible item in place after the data changes. With a duplicate key, that lookup can land on the wrong copy.
The key was already used check runs only when both copies compose in one pass
The second cause explains why the bug hides. Compose never scans the key list for duplicates. A lazy list only composes the rows it needs to measure. Each row is composed through SubcomposeLayout. The row’s key becomes its slot ID. The check lives in subcompose() in the androidx source. During a measure pass, Compose looks up the node for each slot ID. If that node already sits at an earlier position in the same pass, requirePrecondition throws. That’s the IllegalArgumentException above.
So the duplicate only matters when both rows land in the same pass. A pinned row near the top and an old copy 25 rows down never meet. By the time the old copy scrolls in, the pinned row has left composition. To show this outside an Android project, we modeled the slot check in plain Kotlin. The model keeps the source’s lookup, position check and cleanup of unused nodes.
class Node(val key: Any?)
class Slots {
val folded = mutableListOf<Node>()
val byKey = mutableMapOf<Any?, Node>()
var current = 0
fun pass(keys: List<Any?>) {
current = 0
keys.forEach(::subcompose)
while (folded.size > current) byKey.remove(folded.removeLast().key)
}
fun subcompose(key: Any?) {
val node = byKey.getOrPut(key) { Node(key).also { folded.add(current, it) } }
val at = folded.indexOf(node)
require(at >= current) { "Key \"$key\" was already used." }
if (at != current) folded.add(current, folded.removeAt(at))
current++
}
}
data class Header(val index: Int) // stands in for the default index key
fun feedKeys(latest: List<Long>, pinned: List<Long>, prefix: Boolean): List<Any> =
listOf(Header(0)) + pinned.map { if (prefix) "pinned:$it" else it } +
listOf(Header(1 + pinned.size)) + latest.map { if (prefix) "latest:$it" else it }
fun main() {
val latest = (45L downTo 20L).toList()
for ((label, pinned) in listOf("pin old post 22" to listOf(22L), "pin new post 43" to listOf(43L))) {
val keys = feedKeys(latest, pinned, prefix = false)
val top = runCatching { Slots().pass(keys.subList(0, 8)) }
val bottom = runCatching { Slots().pass(keys.subList(keys.size - 8, keys.size)) }
println("$label | top rows: ${top.exceptionOrNull()?.message ?: "OK"} | bottom rows: ${bottom.exceptionOrNull()?.message ?: "OK"}")
}
val fixed = feedKeys(latest, listOf(43L), prefix = true)
println("prefixed, pin 43 | top rows: ${runCatching { Slots().pass(fixed.subList(0, 8)) }.exceptionOrNull()?.message ?: "OK"}")
}
Each pass composes eight rows to stand in for one screen. We built it with kotlinc 2.4.20 and ran it on JDK 27. The output:
pin old post 22 | top rows: OK | bottom rows: OK pin new post 43 | top rows: Key "43" was already used. | bottom rows: OK prefixed, pin 43 | top rows: OK
The old pinned post never fails, at the top or the bottom. The new one fails on the first screen. That matches the field report. Whether it crashes depends on which rows share a screen. Tests with a short fake feed can pass forever. A taller phone or a tablet can widen the window enough to trigger it. The model is a simplification. Real Compose also prefetches rows beyond the viewport. Its window is a bit larger than the visible rows.
The fix gives each section its own key prefix
The pinned row and the Latest row are two different rows that show the same post. Their keys should say so. Prefix each key with its section. A String is the simplest choice, because the lists guide requires key types that Bundle can store. Give the headers fixed keys too, so they keep their identity if a section is ever empty.
@Composable
fun FeedScreen(latest: List<Post>) {
val pinned = latest.filter { it.pinned }
LazyColumn {
item(key = "header:pinned") { SectionHeader("Pinned") }
items(pinned, key = { "pinned:${it.id}" }) { post -> PostRow(post) }
item(key = "header:latest") { SectionHeader("Latest") }
items(latest, key = { "latest:${it.id}" }) { post -> PostRow(post) }
}
}
The model’s last line ran these prefixed keys through the same eight rows. It printed OK. The keys are still stable, since each one is built from the post’s ID. They’re unique across the LazyColumn, since no two sections share a prefix. Each row’s remembered state stays with its own section.
The prefix fixes duplicates across sections. A duplicate inside one section is a different bug. It means the data itself is wrong, often because two page loads merged the same rows. Our pagination race condition post covers that case. There, the fix belongs in the repository, not in the key.
How to explain the crash in a bug-squash round
In a live debugging round, the prompt might be the stack trace plus the FeedScreen code. The interviewer adds that it “only crashes for some users since yesterday.” Our Android debugging interview post covers how that round is scored. Walk through the bug in this order.
- Read the message. The key is a post ID, so two rows in this LazyColumn returned the same ID.
- Name the first cause. All
itemanditemscalls share one key namespace. A post in both Pinned and Latest gets one key twice. - Name the second cause. Compose checks for a reused key in
subcompose(), during measure. It only throws when both rows are composed in the same pass. - Connect it to “since yesterday.” A newly pinned post is also near the top of Latest. Both copies are now on the first screen.
- Give the fix. Prefix keys by section, like
"pinned:$id". Keep the keys stable and Bundle-saveable. - Offer the guard. In a debug build, assert that the key list has no duplicates before it reaches the LazyColumn.
Point 3 explains why QA never saw the crash. It also shows you know that a lazy list composes rows on demand.
Quick fixes that stop the crash and lose row state or hide posts
- “Remove the
keyparameter.” The crash stops, because the default key is the row’s index. But the lists guide says state is then tied to position. When a new post arrives, every row shifts by one. A row’srememberSaveablestate moves to the wrong post.animateItem()also needs keys to find a moved row’s new position, per the same guide. - “Use
UUID.randomUUID()as the key.” It’s unique. It just isn’t stable. Every time Compose asks for the keys again, it gets new ones. Compose then sees new rows and discards their state. - “Use
it.hashCode().” Both copies are the samePost, so they hash the same and collide again. A data class hash also changes when the title is edited. That makes the key unstable. - “Drop posts from Latest that are already pinned.” That removes the pinned post from Latest. The product wanted it in both sections, so this changes the feature to hide the bug.
- “Catch the exception.” It’s thrown inside Compose’s measure pass, not in your code. There’s no call site of yours to wrap.
- “It’s a Compose bug.” The
itemsKDoc forbids duplicate keys. The crash enforces a documented contract. It just fires later than candidates expect.