Video in progress
How can you control ReadinessState from code in Spring Boot, and when is that useful?
With AvailabilityChangeEvent.publish(ctx, ReadinessState.REFUSING_TRAFFIC) a pod can take itself out of traffic. For example, during heavy internal work or when an important dependency is lost, without restarting the pod.
📖 Answer
Spring Boot tracks two states: LivenessState (CORRECT/BROKEN) and ReadinessState (ACCEPTING_TRAFFIC/REFUSING_TRAFFIC). Readiness becomes ACCEPTING when the app is fully up (after ApplicationReadyEvent) and switches to REFUSING when shutdown begins. These states are reflected directly in /actuator/health/readiness.
You can change them yourself too:
@Component
@RequiredArgsConstructor
class CacheWarmup {
private final ApplicationEventPublisher events;
private final PriceCache cache;
@Scheduled(cron = "0 0 3 * * *")
void rebuild() {
AvailabilityChangeEvent.publish(events, this, ReadinessState.REFUSING_TRAFFIC);
try {
cache.reloadAll(); // a few seconds, and answers would be stale in the meantime
} finally {
AvailabilityChangeEvent.publish(events, this, ReadinessState.ACCEPTING_TRAFFIC);
}
}
}
When readiness fails, Kubernetes removes the pod from the Service endpoints but does not touch the container. Depending on the probe's periodSeconds and failureThreshold, this happens with a delay of a few seconds.
The dangerous part: if all replicas run this cron at the same moment, the service is left with no traffic at all. Run such work with a random delay, or on a single replica (ShedLock).
Set LivenessState.BROKEN only when the app cannot recover on its own, for example if an internal thread pool is completely dead. That leads to a pod restart.
Sign up to mark studied questions and save your progress.