Skip to content
Latchkey

sbt "OutOfMemoryError" in CI

The JVM that runs sbt exhausted its heap or metaspace while compiling. Scala compilation is memory-hungry, and CI runners often default to a small heap, so large builds hit the ceiling.

What this error means

The build fails with "java.lang.OutOfMemoryError: Java heap space" or "Metaspace", sometimes after a long compile. It may pass on a larger runner or with more heap, confirming it is a resource limit, not a code error.

sbt output
[error] java.lang.OutOfMemoryError: Java heap space
[error] Use 'last' for the full log.
# or
java.lang.OutOfMemoryError: Metaspace

Common causes

sbt JVM heap/metaspace too small

sbt launches a JVM with a default heap that is too small for a large Scala compile, so it exhausts heap or metaspace mid-build.

Runner has too little memory

On a small runner, even a tuned heap can be starved by the OS and other processes, leading to OOM under load.

How to fix it

Raise the sbt JVM memory

Give sbt a larger heap and metaspace via JVM options.

Terminal
export SBT_OPTS="-Xmx4g -XX:MaxMetaspaceSize=1g -XX:+UseG1GC"
sbt compile
# or per-invocation:
sbt -J-Xmx4g compile

Pin memory in .jvmopts

Commit a .jvmopts so every runner uses the same memory settings.

.jvmopts
# .jvmopts
-Xmx4g
-XX:MaxMetaspaceSize=1g

Use a larger runner if heap tuning is not enough

  1. Confirm the runner has more RAM than your configured -Xmx.
  2. Move large compiles to a higher-memory runner.
  3. Split very large modules so each compile needs less heap.

How to prevent it

  • Set SBT_OPTS/.jvmopts heap and metaspace for your build size.
  • Run memory-heavy Scala builds on adequately sized runners.
  • Cache compilation output to avoid recompiling the whole project.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →