Scrivio Interview library
DebuggingIntermediate9 min read · updated 12 November 2026

A Spring Boot service on Google Cloud Run has slow first requests after idle periods, scheduled @Scheduled jobs that sometimes do not run, and lost messages during deployments. Explain the platform behaviours behind each problem and the fixes.

All three problems come from how Cloud Run manages instances. It scales to zero, so the first request after idle waits for a JVM and Spring to start; with request-based billing it throttles CPU outside requests, so @Scheduled jobs may not run; and it stops instances with SIGTERM and a short grace period, so work held only in memory is lost. The fixes are minimum instances, startup CPU boost and faster start-up (CDS, AOT cache or a native image), moving scheduled work to Cloud Scheduler or Cloud Run jobs, graceful shutdown, and acknowledging messages only after they are processed.

Why this question is asked

This question is a good test of whether we treat a serverless platform as a server. Each symptom looks like a bug in our code, but each one is the platform doing exactly what it promises. Interviewers ask it at senior level because the fixes involve trade-offs between cost, latency and design rather than a single setting. In this answer, we will recap Cloud Run's instance model, then take the three symptoms one by one, explain the behaviour behind each and the fixes, and finish with the limits we must match, such as timeouts, concurrency and memory.

1A Quick Recap of Cloud Run's Instance Model

Cloud Run runs our container image and charges for resources while instances run. By default it scales on traffic: no requests means it can scale down to zero instances, and a burst of requests makes it start new ones. Each instance can handle several requests at once, up to a concurrency limit we set (80 by default at the time of writing).

There are two CPU allocation modes. With request-based billing, the default, an instance gets full CPU only while it is handling a request; between requests its CPU is throttled to almost nothing. With instance-based billing, often called CPU always allocated, the instance keeps its CPU for as long as it exists, and we pay for that time. Finally, when Cloud Run removes an instance, during scale-in or a new deployment, it sends SIGTERM and kills the container after a grace period of about 10 seconds; check the current documentation, because platform limits change.

Step throughWhere each symptom comes from
ClientCloud RunInstance (JVM)
first request after idle
start container: JVM + Spring startup, several seconds
slow first response
between requests: CPU throttled, @Scheduled stalls
new revision deployed: SIGTERM
about 10 s later: killed, in-memory work lost

6 messages in order. Play them, or step through them one at a time.

Each symptom is the platform working as designed.

2Slow First Requests: Cold Starts

When traffic arrives and no instance is running, Cloud Run must start one. That means pulling the image, starting the JVM, loading thousands of classes, building the Spring context, opening the connection pool and warming the JIT compiler. For a typical Spring Boot service this takes several seconds, and the request that triggered it waits all that time. This is called a cold start.

We attack it from two sides. The first is avoiding cold starts: setting minimum instances to 1 or more keeps that many warm instances even with no traffic, at the cost of paying for them. The second is making start-up faster. Startup CPU boost gives an instance extra CPU while it starts, which helps the JVM a lot. Class Data Sharing (CDS) stores already-parsed classes in an archive the JVM maps at start-up, and Spring Boot 3.3 and later can extract the jar in a layout that supports it. On Java 24 and later, the JDK's AOT cache goes further by also storing loaded and linked classes and, on Java 25, method profiles. A GraalVM native image, built with Spring Boot's AOT support, starts in well under a second but takes longer to build and has restrictions on reflection.

Text
# Keep one instance warm and boost CPU during start-up
gcloud run services update orders --min-instances=1 --cpu-boost
# Training run for CDS with Boot 3.3+ (check your version for the exact steps)
java -Djarmode=tools -jar orders.jar extract --destination app
java -XX:ArchiveClassesAtExit=app/app.jsa -Dspring.context.exit=onRefresh -jar app/orders.jar
# At runtime:
java -XX:SharedArchiveFile=app/app.jsa -jar app/orders.jar
# Typical effect: start-up drops by roughly a third to a half

Notice that the training run starts the context and exits at refresh, so the archive records the classes Spring needs without serving any traffic.

3@Scheduled Jobs That Sometimes Do Not Run

A @Scheduled method runs on a background thread inside our instance. With request-based billing, that thread gets CPU only while some request happens to be in flight. Between requests, the timer may fire but the work barely progresses, or the instance may have been scaled to zero and not exist at all. So a job set for every five minutes runs when there happens to be traffic, and silently does not run when there is none.

There are two fixes, and the second is usually better. We can switch the service to CPU always allocated and keep minimum instances above zero, so the thread always has CPU; but every instance then runs the job, so with three instances the job runs three times unless we add a lock such as ShedLock. Or we move the trigger outside the service. Cloud Scheduler can call an HTTP endpoint on a cron schedule; the call is a real request, so the instance has CPU while it runs, and it runs exactly once per tick. For long batch work, Cloud Run jobs run a container to completion without serving HTTP at all.

Java
// Before: depends on CPU between requests and runs on every instance
@Scheduled(cron = "0 */5 * * * *")
void expireReservations() { reservations.expireOlderThan(Duration.ofMinutes(15)); }
// After: Cloud Scheduler calls POST /internal/jobs/expire-reservations every 5 minutes
@PostMapping("/internal/jobs/expire-reservations")
ResponseEntity<Void> expire() {
int n = reservations.expireOlderThan(Duration.ofMinutes(15)); // runs inside a request: full CPU
log.info("expired {} reservations", n); // expired 42 reservations
return ResponseEntity.noContent().build(); // 204
}

The endpoint should accept only authenticated calls from the scheduler's service account, and the job must finish within the request timeout.

4Lost Messages During Deployments

During a deployment, Cloud Run starts instances of the new revision and stops the old ones with SIGTERM. If an old instance had pulled messages into an in-memory queue, or acknowledged a message as soon as it arrived and planned to process it later, that work dies with the instance after the grace period. The message broker thinks the message was handled, so it is never redelivered.

The fix has three parts. Enable graceful shutdown, which is the default for Boot's web servers since 3.4, and keep spring.lifecycle.timeout-per-shutdown-phase below the platform's grace period, so in-flight requests finish. Keep each unit of work short enough to finish in that window. And acknowledge a message only after it has been processed and its result stored, so a killed instance simply means redelivery. With Pub/Sub, a push subscription fits Cloud Run well: Pub/Sub sends each message as an HTTP request, and a 2xx response is the acknowledgement, so the message is acknowledged exactly when our handler finishes. Because redelivery means a message can arrive twice, the handler must be idempotent, for example by recording processed message ids.

Java
@PostMapping("/pubsub/orders")
ResponseEntity<Void> onMessage(@RequestBody PushEnvelope env) {
if (processed.exists(env.message().messageId())) return ResponseEntity.ok().build(); // duplicate: 200
orders.handle(env.message().decode()); // do the work first
processed.record(env.message().messageId());
return ResponseEntity.ok().build(); // 200 = ack; an error or a killed instance = redelivery
}

5Matching the Platform's Limits

Three more limits shape a healthy service. The request timeout, five minutes by default and configurable up to an hour, caps how long any request, including a scheduler call, can run. Concurrency per instance decides how many requests share one JVM; set it too high and requests queue for threads or connections, set it too low and Cloud Run starts more instances than needed. Memory is the hard limit of the container, and the JVM must fit inside it with heap, metaspace, thread stacks and native buffers, so we size the heap with -XX:MaxRAMPercentage, for example 75, rather than a fixed -Xmx.

So the overall picture is: decide what must be warm, move background work into requests or jobs, make shutdown and message handling safe, and size the JVM for the instance.

Symptom, cause and fix on Cloud Run
SymptomPlatform behaviourFix
Slow first requestscale to zero, cold JVM startmin instances, CPU boost, CDS/AOT cache, native
@Scheduled skippedCPU throttled outside requestsCloud Scheduler calls an endpoint, or Cloud Run jobs
Lost messagesSIGTERM, then kill after the grace periodgraceful shutdown, ack after processing
OOM killshard container memory limitMaxRAMPercentage sized to the instance

6Follow-up questions

How do you choose the concurrency per instance for a Spring MVC app?

Spring MVC uses one thread per request, and Tomcat allows 200 by default, but threads are rarely the real limit. The real limits are CPU and the connection pool: if HikariCP has 10 connections and each request needs one for most of its time, more than about 10 concurrent requests just queue inside the instance. I start from Little's law, where concurrent requests equal throughput times latency, measure with a load test at increasing concurrency, and pick the point where latency starts to climb. For CPU-heavy work that may be 10 to 20; for I/O-bound work with virtual threads enabled through spring.threads.virtual.enabled it can be much higher, as long as the database pool and downstream services can take it.

Is minimum instances enough to fix @Scheduled jobs?

Not by itself. A warm instance with request-based billing still has its CPU throttled between requests, so the job can still stall. We need CPU always allocated as well, and then every instance runs the job, so we need a distributed lock or a single scheduler. That is why an external trigger is usually simpler.

Why not just use a native image for everything?

A native image starts fastest and uses less memory, but builds take minutes, reflection and dynamic proxies need hints, some libraries are not supported, and peak throughput can be lower than a warmed-up JIT. It is a strong choice for services that scale to zero often; for steady traffic, min instances with CDS or an AOT cache is often enough.

7Conclusion

In this answer, we saw that each symptom is Cloud Run behaving as designed. Scale to zero causes cold starts, which we avoid with minimum instances and shorten with CPU boost, CDS, an AOT cache or a native image. Request-based billing throttles CPU outside requests, so scheduled work moves to Cloud Scheduler calling an endpoint or to Cloud Run jobs. SIGTERM with a short grace period ends instances during deployments, so we use graceful shutdown, short work and acknowledgement after processing with idempotent handlers. Request timeout, concurrency and memory limits complete the list of things the service must match.

What to say in the interviewAbout 90 seconds aloud

Open with

All three come from Cloud Run's instance model rather than bugs in our code. The slow first request is a cold start: Cloud Run scales to zero, so after idle it has to start a container, the JVM and the Spring context while the request waits.

Then, if they want more

I fix that with min instances for the latency-sensitive services, startup CPU boost, and faster start-up through CDS, which Boot 3.3 supports, or the AOT cache on recent JDKs, or a native image if it scales to zero a lot.

The skipped @Scheduled jobs come from request-based billing: CPU is throttled when no request is in flight, and the instance may not exist at all. I move the trigger out, so Cloud Scheduler calls an authenticated endpoint, or I use a Cloud Run job for batch work; that also avoids every instance running the job.

The lost messages come from SIGTERM during deploys: the instance gets about ten seconds, check the current docs, and then it is killed.

So graceful shutdown with a timeout below that window, short units of work, nothing held only in memory, and acknowledge only after processing, ideally with a Pub/Sub push subscription where the 200 response is the ack, plus idempotent handling for redeliveries. Finally I check the request timeout, tune concurrency with a load test and size the heap with MaxRAMPercentage.

About this answer

Last updated
12 November 2026
Versions it names
Java 24, Java 25, Spring Boot 3.3
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Boot reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A Spring Boot service on Google Cloud Run has slow first requests after idle periods...": https://scrivio-interview-library.netlify.app/spring-boot/packaging-and-deployment/d21348fb63/