Scrivio Interview library
ScenarioAdvanced7 min read · updated 12 November 2026

Services in your platform use CountDownLatches to block startup until caches are warm and connections are ready, and some hang forever in Kubernetes when a dependency is down. What standard for startup coordination would you set?

An unbounded latch.await() at startup turns a dependency outage into a pod that neither starts nor fails, so Kubernetes can do nothing useful with it. The standard I would set is: every startup wait has a timeout, each dependency is classified as required (fail startup with a clear message) or optional (start degraded), readiness is reported through the readiness probe instead of blocking the main thread, coordination uses Spring lifecycle hooks rather than ad hoc latches, and startup is tested with each dependency down.

Why this question is asked

A CountDownLatch that waits for a cache to warm looks harmless on a laptop where the cache always warms. In a cluster, the day the cache's backing store is down, every new pod blocks forever, rolling deploys stall, and autoscaling adds pods that never serve traffic. Interviewers ask this to see whether we think about how a process behaves inside its platform, not only in isolation. In this answer, we will recap what the latch does, see exactly why it hangs in Kubernetes, then build the standard step by step: timeouts, required versus optional dependencies, readiness probes, lifecycle hooks, and tests.

1A Quick Recap of CountDownLatch at Startup

A CountDownLatch is a counter that threads can wait on. We create it with a count, other threads call countDown() as they finish their part, and any thread that calls await() blocks until the count reaches zero. It is one-shot: once it reaches zero it stays open.

The pattern in the question looks like this. The main thread starts some background work, such as warming a cache and opening connections, and then waits on a latch until both are done before it lets the application finish starting.

Java
CountDownLatch ready = new CountDownLatch(2);
executor.submit(() -> { cache.warm(); ready.countDown(); });
executor.submit(() -> { pool.connectAll(); ready.countDown(); });
ready.await(); // blocks forever if warm() throws or hangs
log.info("started"); // never printed when the cache store is down

Notice two problems in four lines. If warm() throws, countDown() is never called, so the count never reaches zero. And await() has no limit, so even a warm() that simply hangs on a network call keeps the main thread blocked forever.

2Why the Pod Hangs Instead of Failing

Kubernetes decides what to do with a pod from two signals: whether the process is alive, and what the probes say. A process blocked in await() is alive. It does not exit, so the container is never restarted for a crash, and it never becomes ready, so it never receives traffic. If there is a liveness probe pointed at an HTTP endpoint that is not yet served, the pod may be killed and restarted in a loop, which looks like a crash loop with no error message. If there is no such probe, the pod just sits there.

Step throughA pod blocked on a latch during an outage
KubeletPod main threadWarm-up taskCache store
submit warm()
load entries
connection refused, warm() throws
ready.await(), no timeout
readiness probe
no answer: web server not started
pod stays not ready, rollout stalls

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

The process is alive but never ready, so Kubernetes can neither route to it nor treat it as failed.

3Rule 1: Every Startup Wait Has a Timeout

The first rule is mechanical and easy to review: no await() without a timeout, and every countDown() goes in a finally block or is replaced by a future that completes exceptionally. await(timeout, unit) returns false when the time runs out, which gives us a place to make a decision.

Java
CompletableFuture<Void> cache = CompletableFuture.runAsync(cache::warm, executor);
CompletableFuture<Void> pool = CompletableFuture.runAsync(pool::connectAll, executor);
try {
CompletableFuture.allOf(cache, pool).get(30, TimeUnit.SECONDS);
} catch (TimeoutException e) {
throw new IllegalStateException("startup: dependencies not ready after 30s", e); // the process exits with a clear message
} catch (ExecutionException e) {
throw new IllegalStateException("startup: " + e.getCause().getMessage(), e.getCause());
}

The reason futures read better than a latch here is that a future carries the failure with it. A latch only knows that a count did or did not reach zero; it cannot tell us that warm() failed and why. The timeout value should come from configuration and be shorter than the Kubernetes startup probe's total budget, so that our own message appears in the log before the kubelet kills the container.

4Rule 2: Decide Per Dependency Whether to Fail or Start Degraded

A timeout forces the question of what to do next, and the answer depends on the dependency. A required dependency is one without which the service cannot do anything correct, such as its own database. For those, failing startup fast is right: the pod exits, Kubernetes restarts it with back-off, and the event is visible as a crash with a clear reason.

An optional dependency is one the service can live without for a while, such as a cache it can fall back from, or a recommendations service whose absence only removes a panel from a page. For those, the service should start, report itself as degraded through health details and metrics, and keep retrying in the background. Starting degraded is often better for the whole system, because a cache outage that also prevents every pod from starting turns a slowdown into a full outage.

I would make this decision explicit in each service's configuration or code review, not leave it to whoever writes the warm-up code. The table below is the kind of classification I would ask teams to write down.

Classifying startup dependencies
DependencyClassOn timeoutReadiness
Primary databaserequiredfail startup with a clear errornot ready until connected
Kafka producerrequired for writesfail startupnot ready until metadata loads
Local cache warm-upoptionalstart cold, warm in backgroundready, health shows degraded
Recommendations APIoptionalstart, use fallbackready, metric shows fallback rate
Writing the class down turns a hidden latch into a reviewed decision.

5Rule 3: Report Readiness Instead of Blocking the Main Thread

The main thread should finish starting the application quickly, so the web server and the health endpoints come up, and readiness should be reported through the readiness probe. Spring Boot supports this directly. Its availability support tracks a liveness state and a readiness state, and with Actuator they are exposed at /actuator/health/liveness and /actuator/health/readiness, which Kubernetes probes can call. Any bean can change the readiness state by publishing an AvailabilityChangeEvent.

Java
@Component
class CacheWarmer implements SmartLifecycle {
private final ApplicationContext ctx;
private volatile boolean running;
public void start() {
running = true;
AvailabilityChangeEvent.publish(ctx, ReadinessState.REFUSING_TRAFFIC); // probe returns 503
CompletableFuture.runAsync(cache::warm)
.orTimeout(30, TimeUnit.SECONDS)
.whenComplete((ok, err) -> {
if (err != null) log.warn("cache warm-up failed, serving cold", err);
AvailabilityChangeEvent.publish(ctx, ReadinessState.ACCEPTING_TRAFFIC); // probe returns 200
});
}
public void stop() { running = false; }
public boolean isRunning() { return running; }
}

Notice that the main thread is never blocked. The liveness probe answers at once, so Kubernetes knows the process is healthy, and the readiness probe stays at 503 until warm-up ends or times out. For a required dependency, the whenComplete branch would instead mark the application broken (LivenessState.BROKEN) or exit, so the platform restarts it. Kubernetes also has a startupProbe, which gives slow-starting containers a separate, longer budget before liveness checks begin; it is the right place to express how long startup may take.

6Rule 4: Use Framework Lifecycle Hooks, Not Ad Hoc Latches

Most of the coordination these latches do is already provided by Spring. SmartLifecycle beans are started in order of their phase, after all singletons are created, and stopped in reverse order on shutdown, so the cache warmer above starts after the beans it depends on. ApplicationReadyEvent is published once the application has started, which is the right moment to begin background warm-up that should not delay startup. Health indicators let each dependency report its own state, and readiness groups decide which indicators count for the readiness probe.

7Rule 5: Test Startup With Each Dependency Down

The last rule is the one that proves the others. For every service, the test suite should start the application once with each dependency unavailable and assert the expected behaviour: for a required one, startup fails within the timeout with the expected message; for an optional one, the application starts, readiness turns ACCEPTING_TRAFFIC and health shows the degraded state. Testcontainers makes this practical, because we can start the application against a database container that is stopped, or point a client at an unused port. A simple assertion that startup finishes or fails in under 40 seconds catches an unbounded wait the moment someone adds one.

8Follow-up questions

Is a CountDownLatch ever acceptable at startup?

Yes, inside a component, as long as the wait has a timeout, countDown() is in a finally block, and the timeout leads to an explicit decision. The standard bans unbounded, undocumented waits on the main thread, not the class.

What should the liveness probe check?

Only that the process itself is healthy and making progress, never the state of dependencies. If liveness checked the database, a database outage would make Kubernetes restart every pod at once, which adds load and fixes nothing. Dependencies belong in readiness, or in health details that people and alerts read.

9Conclusion

In this answer, we saw why a latch that waits forever at startup leaves a pod alive but never ready, which hides a dependency outage from both Kubernetes and the people on call. The standard has five parts: put timeouts on every startup wait, classify each dependency as required or optional and either fail fast or start degraded, report readiness through probes instead of blocking the main thread, use Spring's SmartLifecycle, ApplicationReadyEvent and availability states instead of hand-rolled latches, and test startup with each dependency down.

What to say in the interviewAbout 80 seconds aloud

Open with

The core problem is that an unbounded await at startup turns an outage into a pod that is alive but never ready, so Kubernetes can't restart it for a crash and can't send it traffic, and rollouts just stall.

Then, if they want more

So the standard I'd set starts with no unbounded waits: every startup wait has a timeout from configuration, shorter than the startup probe's budget, and a countDown always sits in a finally block, or better, we use futures so the failure reason travels with the result. Then each service writes down, per dependency, whether it is required or optional.

For a required one like the primary database, we fail startup with a clear message and let Kubernetes restart us with back-off. For an optional one like a cache, we start degraded and say so in health and metrics.

Third, the main thread shouldn't block at all: in Spring Boot, a SmartLifecycle bean or an ApplicationReadyEvent listener does the warm-up and publishes readiness changes, and the readiness probe reports them, while liveness only checks the process itself.

Finally, every service has a startup test per dependency with that dependency down, asserting it either fails within the timeout or starts degraded.

About this answer

Last updated
12 November 2026
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.
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 "Services in your platform use CountDownLatches to block startup until caches are warm...": https://scrivio-interview-library.netlify.app/java/synchronizers/7f33e5dcea/