CRaC: starting Spring Boot from a saved JVM
CRaC saves a running JVM to disk and starts later copies from that state, skipping class loading, bean creation and JIT warm-up. This page runs the parts of Spring's CRaC integration that work on any JVM, from lifecycle callbacks to connection pool suspension, and explains the commands and traps of a real checkpoint.
Contents
What checkpoint and restore does
A Spring Boot application spends its first seconds on work that is the same every time: loading thousands of classes, creating beans, and running cold code before the JIT compiler has optimised it. CRaC (Coordinated Restore at Checkpoint) skips that work by saving a running JVM to disk and starting later copies from the saved state.
It has two phases:
- Checkpoint: the application starts normally, possibly handles some warm-up traffic, and then the JVM writes its whole state, including the heap, threads and compiled code, to a directory with
. The process then exits.-XX:CRaCCheckpointTo=PATH - Restore:
rebuilds the process from those files and continues where it stopped, with classes loaded, beans created and, if the checkpoint was taken after warm-up, code already compiled.java -XX:CRaCRestoreFrom=PATH
The hard part is the word "coordinated". A saved process cannot keep live operating system resources: an open socket to a database, a file handle or a listening port would point at nothing after restore, possibly on another machine. So before the checkpoint, every component must close such resources, and after restore it must open them again. CRaC's org.crac.ResourceLifecycle
| Technique | Needs | Keeps the JIT | Best for |
|---|---|---|---|
| CRaC checkpoint and restore | A CRaC-enabled JDK on Linux, org.crac:crac | Yes, warmed up if trained | Fast start with peak performance at once |
| GraalVM native image | A native build, closed-world limits | No | Fastest start, smallest memory |
| AOT cache (Java 25) or CDS | A training run, standard JDK | Yes, but starts cold | A moderate gain with no code changes |
| Spring AOT on the JVM | The process-aot | Yes | A smaller gain, often combined with the above |
CRaC needs a JDK built with it, such as Azul Zulu with CRaC or BellSoft Liberica JDK with CRaC, and it runs only on Linux. The build machine for this page has a standard OpenJDK, so no checkpoint was taken or restored here. The programs below run every part of Spring's integration that works on a standard JVM, with Spring Boot 4.1.2 and Spring Framework 7.0.10; the commands for a real checkpoint come from the Spring reference documentation and were not run.
Lifecycle stop and start around a checkpoint
When a checkpoint is requested, Spring stops all running Lifecyclestop()start()
import org.springframework.context.SmartLifecycle;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class LifecycleAroundCheckpoint {
/** Stands for anything holding an OS resource: a socket, a file, a thread pool. */
static class Resource implements SmartLifecycle {
private final String name;
private final int phase;
private boolean running;
Resource(String name, int phase) {
this.name = name;
this.phase = phase;
}
@Override
public void start() {
running = true;
System.out.println(" start " + name + " (phase " + phase + ")");
}
@Override
public void stop() {
running = false;
System.out.println(" stop " + name + " (phase " + phase + ")");
}
@Override
public boolean isRunning() {
return running;
}
@Override
public int getPhase() {
return phase;
}
}
@Configuration
static class Config {
@Bean
Resource connectionPool() {
return new Resource("database connection pool", 0);
}
@Bean
Resource messageListener() {
return new Resource("message listener", 100);
}
@Bean
Resource webServer() {
return new Resource("web server", Integer.MAX_VALUE - 1);
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext()) {
context.register(Config.class);
System.out.println("refresh(): normal startup");
context.refresh();
System.out.println("stop(): what Spring does just before a checkpoint");
context.stop();
System.out.println("start(): what Spring does just after a restore");
context.start();
System.out.println("close(): normal shutdown");
}
}
}
refresh(): normal startup
start database connection pool (phase 0)
start message listener (phase 100)
start web server (phase 2147483646)
stop(): what Spring does just before a checkpoint
stop web server (phase 2147483646)
stop message listener (phase 100)
stop database connection pool (phase 0)
start(): what Spring does just after a restore
start database connection pool (phase 0)
start message listener (phase 100)
start web server (phase 2147483646)
close(): normal shutdown
stop web server (phase 2147483646)
stop message listener (phase 100)
stop database connection pool (phase 0)
- On refresh, beans started in ascending phase order: the connection pool at phase 0 first, the web server at phase 2147483646 last, so the server does not accept requests before its dependencies are ready.
- Before a checkpoint,
ran in the reverse order: the web server stopped taking traffic first, the connection pool closed last.stop() - After a restore,
ran in ascending order again, exactly as at the first startup.start() - Normal shutdown at
uses the same reverse order, which is why a bean that handles shutdown correctly usually handles a checkpoint correctly too.close()
Spring Boot's embedded web server, its messaging listener containers and its scheduled task executors are SmartLifecycleLifecycleSmartLifecycleorg.crac.ResourceCore.getGlobalContext()
The connection pool: allow-pool-suspension
A database connection pool is the resource most likely to break a checkpoint, because it keeps open sockets and refills itself. When org.cracHikariCheckpointRestoreLifecycle
package crac.hikari;
import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.HikariPoolMXBean;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.jdbc.HikariCheckpointRestoreLifecycle;
import org.springframework.jdbc.core.JdbcTemplate;
@SpringBootApplication
public class HikariBeforeCheckpoint {
static void show(String label, HikariDataSource dataSource) {
HikariPoolMXBean pool = dataSource.getHikariPoolMXBean();
System.out.println(" " + label + ": connections open " + pool.getTotalConnections()
+ ", pool running " + dataSource.isRunning());
}
static void run(boolean allowSuspension) throws InterruptedException {
System.out.println("spring.datasource.hikari.allow-pool-suspension=" + allowSuspension);
System.out.flush();
SpringApplication app = new SpringApplication(HikariBeforeCheckpoint.class);
app.setDefaultProperties(Map.of(
"spring.main.banner-mode", "off",
"logging.level.root", "WARN",
"logging.pattern.console", " log: %level %logger{0} - %m%n",
"spring.datasource.url", "jdbc:h2:mem:shop",
"spring.datasource.hikari.maximum-pool-size", "1",
"spring.datasource.hikari.allow-pool-suspension", String.valueOf(allowSuspension)));
try (var context = app.run()) {
HikariDataSource dataSource = context.getBean(HikariDataSource.class);
JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
System.out.println(" query: " + jdbc.queryForObject("SELECT 40 + 2", Integer.class));
show("after startup", dataSource);
System.out.println(" CRaC lifecycle bean in this context: "
+ (context.getBeanNamesForType(HikariCheckpointRestoreLifecycle.class)
.length > 0));
var lifecycle = new HikariCheckpointRestoreLifecycle(dataSource, context);
lifecycle.stop();
Thread.sleep(1000);
show("1 s after stop(), as before a checkpoint", dataSource);
lifecycle.start();
System.out.println(" query: " + jdbc.queryForObject("SELECT 40 + 2", Integer.class));
show("after start(), as after a restore", dataSource);
}
}
public static void main(String[] args) throws InterruptedException {
run(false);
run(true);
}
}
spring.datasource.hikari.allow-pool-suspension=false
query: 42
after startup: connections open 1, pool running true
CRaC lifecycle bean in this context: false
log: WARN HikariCheckpointRestoreLifecycle - HikariDataSource (HikariPool-1) is not configured to allow pool suspension. This will cause problems when the application is checkpointed. Please configure allow-pool-suspension to fix this!
1 s after stop(), as before a checkpoint: connections open 1, pool running true
query: 42
after start(), as after a restore: connections open 1, pool running true
spring.datasource.hikari.allow-pool-suspension=true
query: 42
after startup: connections open 1, pool running true
CRaC lifecycle bean in this context: false
1 s after stop(), as before a checkpoint: connections open 0, pool running false
query: 42
after start(), as after a restore: connections open 1, pool running true
- The auto-configured context had no such bean: it is conditional on
being present, which it is not here. The program builds it with the data source and the context, as the auto-configuration would.org.crac - With the default
,allow-pool-suspension=false logged the warning that this "will cause problems when the application is checkpointed". It closed the connections, but the pool kept running and one second later had reopened a connection: an open socket at checkpoint time.stop() - With
, the pool was suspended and stayed at 0 open connections, ready for a checkpoint.allow-pool-suspension=true - In both cases
resumed the pool, and the next query,start() , returned 42 over a fresh connection.SELECT 40 + 2
Set spring.datasource.hikari.allow-pool-suspension=trueLifecycle
Checkpoint at startup with spring.context.checkpoint
Taking a checkpoint by hand needs a running application and a command. For build pipelines, Spring can take one automatically at the end of startup. This program starts the same application with two system properties and shows what each does on a standard JVM:
package crac.property;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CheckpointProperty {
public static void main(String[] args) throws Exception {
if (args.length > 0) {
SpringApplication app = new SpringApplication(CheckpointProperty.class);
app.setDefaultProperties(Map.of(
"spring.main.banner-mode", "off",
"logging.level.root", "OFF"));
try (var context = app.run()) {
System.out.println(" application ran past refresh, beans: "
+ (context.getBeanDefinitionCount() > 0));
} catch (RuntimeException e) {
Throwable root = e;
while (root.getCause() != null) {
root = root.getCause();
}
System.out.println(" startup failed: " + root.getMessage());
}
return;
}
System.out.println("JVM: " + System.getProperty("java.vm.name") + " "
+ Runtime.version().feature() + ", org.crac on the classpath: "
+ isPresent("org.crac.Core") + ", jdk.crac module: "
+ ModuleLayer.boot().findModule("jdk.crac").isPresent());
for (String flag : new String[] {"-Dspring.context.exit=onRefresh",
"-Dspring.context.checkpoint=onRefresh"}) {
System.out.println(flag + ":");
System.out.flush();
List<String> command = new ArrayList<>(List.of(
ProcessHandle.current().info().command().orElseThrow(), flag,
"-cp", System.getProperty("java.class.path"),
CheckpointProperty.class.getName(), "child"));
ProcessBuilder builder = new ProcessBuilder(command).inheritIO();
builder.environment().remove("JAVA_TOOL_OPTIONS");
System.out.println(" exit code " + builder.start().waitFor());
}
}
static boolean isPresent(String className) {
try {
Class.forName(className);
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
}
JVM: OpenJDK 64-Bit Server VM 21, org.crac on the classpath: false, jdk.crac module: false
-Dspring.context.exit=onRefresh:
exit code 0
-Dspring.context.checkpoint=onRefresh:
startup failed: Checkpoint on refresh requires a CRaC-enabled JVM and 'org.crac:crac' on the classpath
exit code 0
- The JVM here has neither
on the classpath nor theorg.crac module that CRaC-enabled JDKs provide.jdk.crac ended the application at the point where a checkpoint would be taken, so the line after-Dspring.context.exit=onRefresh was never printed and the process exited with 0. This is the test mode: it needs no CRaC at all, and the AOT cache training run on therun()Docker page uses the same property. failed with "Checkpoint on refresh requires a CRaC-enabled JVM and 'org.crac:crac' on the classpath". On a CRaC JDK, the process would instead write the checkpoint and exit.-Dspring.context.checkpoint=onRefresh
The checkpoint is taken during LifecycleProcessor.onRefreshafterPropertiesSetLifecycleContextRefreshedEvent
Taking and restoring a checkpoint
These steps follow the Spring Framework reference documentation and were not run on this page. First add the CRaC API, which works as a no-op on JDKs without CRaC:
<dependency>
<groupId>org.crac</groupId>
<artifactId>crac</artifactId>
</dependency>
Spring Framework supports version 1.4.0 and later. Then, on a CRaC-enabled JDK, either checkpoint automatically at startup or on demand after warm-up:
# checkpoint at the end of startup, then the process exits
java -Dspring.context.checkpoint=onRefresh -XX:CRaCCheckpointTo=./checkpoint -jar app.jar
# or: start normally, send warm-up traffic, then checkpoint the running process
java -XX:CRaCCheckpointTo=./checkpoint -jar app.jar
jcmd app.jar JDK.checkpoint
# restore, as often as needed
java -XX:CRaCRestoreFrom=./checkpoint
- The on-demand checkpoint calls
on running beans first, as the first program showed, and restores a warmed-up JVM, so the first requests after restore run at full speed.stop() - The automatic checkpoint at startup skips startup work but restores a cold JIT.
- Restore usually runs in a container built from the checkpoint files. The checkpoint is taken with CRIU, a Linux tool that needs more privileges than a normal container has; the CRaC JDK vendors document which Linux capabilities to grant for the step that takes the checkpoint.
What can go wrong
- Secrets in the checkpoint: the checkpoint files are a copy of the JVM's memory, including every password, token and key the application had read. Protect them like the secrets themselves, and prefer reading secrets after restore.
- Open resources: a file handle, socket or thread outside Spring's lifecycle makes the checkpoint fail, or breaks after restore. Close it in
or anstop() callback.org.crac.Resource - Fixed-rate schedules:
runs every execution it missed between checkpoint and restore, all at once. Use@Scheduled(fixedRate = 5000) or a cron expression, which are calculated after each run.fixedDelay - Values computed before the checkpoint: the host name, the start time, random seeds and anything read from the environment are restored as they were. Every restored copy shares them unless they are recomputed in
.start() - Configuration that changes per environment: properties bound before the checkpoint keep their build-time values. Pass environment-specific settings that beans read at runtime, or recreate those beans after restore.
Choosing a fast-startup approach
| Situation | Choose |
|---|---|
| Fast start with full JIT performance at once | CRaC with an on-demand checkpoint after warm-up |
| Fast start, simplest pipeline, CRaC JDK available | CRaC with -Dspring.context.checkpoint=onRefresh |
| Testing what a startup checkpoint would capture | -Dspring.context.exit=onRefresh |
| Smallest memory and fastest start, closed world acceptable | A GraalVM native image |
| A standard JDK and no code changes | The Java 25 AOT cache, or CDS on Java 21 |
| Applications that cannot easily close their resources | The AOT cache or a native image rather than CRaC |
CRaC is the only approach here that restores a JIT-compiled JVM, at the cost of a special JDK and careful resource handling. The