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.

Share

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 -XX:CRaCCheckpointTo=PATH. The process then exits.
  • Restore: java -XX:CRaCRestoreFrom=PATH 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.

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.Resource interface carries those two callbacks, and Spring maps them onto its own Lifecycle contract.

Ways to start a Spring Boot application faster
TechniqueNeedsKeeps the JITBest for
CRaC checkpoint and restoreA CRaC-enabled JDK on Linux, org.crac:cracYes, warmed up if trainedFast start with peak performance at once
GraalVM native imageA native build, closed-world limitsNoFastest start, smallest memory
AOT cache (Java 25) or CDSA training run, standard JDKYes, but starts coldA moderate gain with no code changes
Spring AOT on the JVMThe process-aot build stepYesA 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 Lifecycle beans; after restore, it starts them again. The same calls are available as stop() and start() on any application context, so three beans with different phases show the exact order Spring uses:

Java
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");
        }
    }
}
Output
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, stop() ran in the reverse order: the web server stopped taking traffic first, the connection pool closed last.
  • After a restore, start() ran in ascending order again, exactly as at the first startup.
  • Normal shutdown at close() uses the same reverse order, which is why a bean that handles shutdown correctly usually handles a checkpoint correctly too.

Spring Boot's embedded web server, its messaging listener containers and its scheduled task executors are SmartLifecycle beans already, so they stop and start around a checkpoint with no code. Your own beans that hold sockets, files or threads should implement Lifecycle or SmartLifecycle the same way. Code that does not depend on Spring can implement org.crac.Resource and register itself with Core.getGlobalContext() instead.

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.crac is on the classpath, Spring Boot registers a HikariCheckpointRestoreLifecycle bean for the pool. This program creates that same class by hand on a standard JVM and calls it, once with Hikari's default settings and once with pool suspension allowed:

Java
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);
    }
}
Output
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 org.crac being present, which it is not here. The program builds it with the data source and the context, as the auto-configuration would.
  • With the default allow-pool-suspension=false, stop() 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.
  • With allow-pool-suspension=true, the pool was suspended and stayed at 0 open connections, ready for a checkpoint.
  • In both cases start() resumed the pool, and the next query, SELECT 40 + 2, returned 42 over a fresh connection.

Set spring.datasource.hikari.allow-pool-suspension=true in any application that uses CRaC. Other clients that hold connections, such as a Redis client, a message broker connection or an HTTP connection pool, need the same treatment: check that the library supports CRaC, or wrap it in a Lifecycle bean that closes it on stop.

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:

Java
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;
        }
    }
}
Output
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 org.crac on the classpath nor the jdk.crac module that CRaC-enabled JDKs provide.
  • -Dspring.context.exit=onRefresh ended the application at the point where a checkpoint would be taken, so the line after run() 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 the Docker page uses the same property.
  • -Dspring.context.checkpoint=onRefresh 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.

The checkpoint is taken during LifecycleProcessor.onRefresh: all non-lazy singletons exist and their afterPropertiesSet callbacks have run, but no Lifecycle bean has started yet and ContextRefreshedEvent has not been published. Nothing needs stopping at that moment, which makes this the safest kind of checkpoint, but it also means the JIT has not been warmed up by any traffic.

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:

XML
<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:

Shell
# 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 stop() 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.
  • 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 stop() or an org.crac.Resource callback.
  • Fixed-rate schedules: @Scheduled(fixedRate = 5000) runs every execution it missed between checkpoint and restore, all at once. Use fixedDelay or a cron expression, which are calculated after each run.
  • 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

Situations and the approach that fits them
SituationChoose
Fast start with full JIT performance at onceCRaC with an on-demand checkpoint after warm-up
Fast start, simplest pipeline, CRaC JDK availableCRaC with -Dspring.context.checkpoint=onRefresh
Testing what a startup checkpoint would capture-Dspring.context.exit=onRefresh on any JVM
Smallest memory and fastest start, closed world acceptableA GraalVM native image
A standard JDK and no code changesThe Java 25 AOT cache, or CDS on Java 21
Applications that cannot easily close their resourcesThe 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 native image page covers GraalVM, the Docker page covers the AOT cache, and the bean lifecycle page explains the callbacks CRaC builds on.