Kotlin daemon "OutOfMemoryError: Metaspace" in CI
Metaspace holds class metadata, separate from the Java heap. A large Kotlin build (many modules, kapt/ksp generating classes) can exhaust the default Metaspace on the compile daemon, producing OutOfMemoryError: Metaspace even when heap is fine.
What this error means
The Kotlin compile daemon or Gradle daemon fails with "java.lang.OutOfMemoryError: Metaspace" and the compile task aborts, sometimes taking the daemon down with it.
> Task :app:compileKotlin FAILED
java.lang.OutOfMemoryError: Metaspace
at java.base/java.lang.ClassLoader.defineClass1(Native Method)Common causes
Default Metaspace too small for the build
A multi-module Kotlin build loads many classes; the daemon default Metaspace cap is exceeded, especially with annotation processors generating extra classes.
Metaspace accumulates across a long-lived daemon
A reused daemon that compiled many builds retains class metadata until Metaspace is full.
How to fix it
Raise MaxMetaspaceSize for daemon and Gradle
Set a larger Metaspace cap in gradle.properties for both the Gradle and Kotlin daemons.
# gradle.properties
org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=1536m
kotlin.daemon.jvmargs=-Xmx2g -XX:MaxMetaspaceSize=1gRestart daemons on OOM
- Stop lingering daemons so Metaspace resets.
- Re-run the build with the raised Metaspace cap.
- On self-hosted runners, avoid indefinitely reusing one daemon.
./gradlew --stop
./gradlew buildHow to prevent it
- Set an explicit
MaxMetaspaceSizesized for your module count. - Restart the Gradle/Kotlin daemons periodically on long-lived runners.
- Reduce kapt usage (prefer ksp) to cut generated-class churn.