AWS Builder Center

Achieving Zero-Downtime Releases for Spring Boot Applications on Amazon ECS

The simply adopting a rolling update or blue/green deployment is not enough. You need to make sure that unlucky users do not encounter a 5xx error. This article explores the concrete measures needed to do that.

Software Engineer/AWS Community Builder(Devtools)
Note: This is an English translation of my original Japanese post
Modern web services are commonly designed to run 24/7, so deployment approaches that avoid taking the service offline are essential. This is usually called a zero-downtime release.
However, zero-downtime releases are not always straightforward, depending on how the application is implemented. For example:
  • In a stateful application, in-progress work cannot simply be terminated, which makes it difficult to decide when to shut down the old version.
  • When the application switches from the old version to the new version, even a brief interruption can cause requests received at that moment to return 5xx errors.
In these situations, simply adopting a rolling update or blue/green deployment is not enough. You need to make sure that unlucky users do not encounter a 5xx error. This article explores the concrete measures needed to do that.
This article considers a Java application running on Amazon ECS, like the architecture below. Specifically, it assumes multiple ECS tasks behind a single Application Load Balancer (ALB).
AWS architecture


Challenges That Prevent Zero-Downtime Releases

As mentioned above, zero-downtime releases have two main challenges:
  • The old version must not shut down until all in-progress work has completed.
  • A brief application outage can occur while the old version shuts down and the new version starts.
We will address the first challenge with graceful shutdown and the second with rolling updates.

Graceful Shutdown

Graceful shutdown means shutting down without interrupting work already in progress.
For example, when you shut down a Windows or macOS computer, the operating system safely closes open applications one at a time before it shuts down. Graceful shutdown follows the same idea.
The process consists of the following steps:
  • Stop accepting new requests.
  • Wait for all in-progress work to complete.
  • Shut down the application.
To implement graceful shutdown for a Spring Boot application running on Amazon ECS, several settings are required.

Spring Boot Behavior

Since Spring Boot 3.4, graceful shutdown is enabled by default unless explicitly disabled. Earlier Spring Boot versions have different defaults, so it is safer to specify the following settings explicitly when you want behavior that is clear regardless of the version:
server:
shutdown: graceful # Enable graceful shutdown

spring:
lifecycle:
timeout-per-shutdown-phase: 30s # Maximum wait time for each shutdown phase
In Spring Boot 3.4 and later, the defaults for these properties are  graceful  and  30s , respectively.
 timeout-per-shutdown-phase  does not protect arbitrary background work for 30 seconds. It is the timeout for waiting for  SmartLifecycle  beans in the same phase to stop. During graceful shutdown of the web server, the server waits for in-progress requests to finish within the timeout and stops accepting new requests. When the timeout expires, it proceeds to immediate shutdown.
At this point, you might think, “If I use Spring Boot 3.4 or later, graceful shutdown works without any extra work.” In practice, there are several important caveats:
  1. Asynchronous processing, such as work started with  @Async , is not guaranteed to complete through web-server graceful shutdown alone.
  • Long-running asynchronous work requires ECS task scale-in protection, described later.
  1. Set  timeout-per-shutdown-phase  to a value that is neither too short nor too long.
  • If it is too short, work may not finish. If it is too long, deployments take longer than necessary.
  • You need to understand the application characteristics and estimate an appropriate wait time.
  1. Graceful shutdown runs when the process receives  SIGTERM .
  • Graceful shutdown does not apply when the process receives  SIGKILL .
The next section covers how to protect asynchronous work with ECS task scale-in protection.
When ECS stops a task, it first sends  SIGTERM , then forcibly stops the container with  SIGKILL  after the stop timeout. The default stop timeout is also 30 seconds. If both the Spring Boot timeout and the ECS timeout are 30 seconds, ECS may send  SIGKILL  before Spring Boot completes shutdown. For example, when Spring Boot uses 30 seconds, set  stopTimeout  to 60 seconds in the container definition of the ECS task definition.
{
"stopTimeout": 60
}

ECS Task Scale-In Protection

To protect asynchronous work as described in the previous section, use ECS task scale-in protection.
This feature prevents a task from being shut down during scale-in or deployment. You can defer shutdown for a specified period.
The ECS task role needs these two permissions:
"ecs:GetTaskProtection",
"ecs:UpdateTaskProtection"
Task protection does not automatically protect every asynchronous operation. The application must explicitly specify the work to protect. The overall flow is as follows:

Here is a sample implementation based on that flow:
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;

/**
* Executes an asynchronous process while protecting the ECS task
* from scale-in termination.
*/
@Service
public final class AsyncJobService {
private final RestClient restClient;
private final String taskProtectionEndpoint;
private final Object taskProtectionLock = new Object();
private int activeJobCount;

/**
* Creates the service.
*
* @param restClientBuilder the REST client builder
* @param ecsAgentUri the ECS container agent URI
*/
public AsyncJobService(
final RestClient.Builder restClientBuilder,
@Value("${ECS_AGENT_URI}") final String ecsAgentUri
) {
this.restClient = restClientBuilder.build();
this.taskProtectionEndpoint =
ecsAgentUri + "/task-protection/v1/state";
}

/**
* Executes an asynchronous process with ECS task protection enabled.
*
* @return a future completed when the process finishes
*/
@Async
public CompletableFuture<Void> executeAsync() {
startProtectedJob();
try {
// Execute the asynchronous process here.
return CompletableFuture.completedFuture(null);
} finally {
finishProtectedJob();
}
}

/**
* Starts a job and enables protection before the first active job.
*/
private void startProtectedJob() {
synchronized (taskProtectionLock) {
if (activeJobCount == 0) {
updateTaskProtection(true);
}
activeJobCount++;
}
}

/**
* Finishes a job and disables protection after the last active job.
*/
private void finishProtectedJob() {
synchronized (taskProtectionLock) {
activeJobCount--;
if (activeJobCount == 0) {
updateTaskProtection(false);
}
}
}

/**
* Updates the scale-in protection status of the current ECS task.
*
* @param enabled whether task protection should be enabled
*/
private void updateTaskProtection(final boolean enabled) {
final Map<String, Object> requestBody = enabled
? Map.of(
"ProtectionEnabled", true,
"ExpiresInMinutes", 60
)
: Map.of("ProtectionEnabled", false);
restClient.put()
.uri(taskProtectionEndpoint)
.contentType(MediaType.APPLICATION_JSON)
.body(requestBody)
.retrieve()
.toBodilessEntity();
}
}
ECS automatically injects the URI in the  ECS_AGENT_URI  environment variable. Before starting asynchronous work that needs protection, send a request to this URI to enable task protection.
An important limitation is that task protection cannot be applied per process. It protects the task as a whole.
The sample tracks the number of active jobs in the same task. It enables protection before the first job starts and disables it after the last job completes. If each job simply disabled protection in its own  finally  block, a job that finishes first could remove protection while other jobs are still running.
 ExpiresInMinutes  is not a substitute for disabling protection after work completes; it is an upper bound in case protection is not removed. If the work may exceed the expiry period, configure a duration that matches the expected processing time or renew protection periodically.
An old task with task protection enabled will not be stopped during deployment until protection is removed or expires. In an architecture that continues accepting requests that start asynchronous work, an old task could continue receiving new work and prevent the deployment from completing. You need a mechanism to stop accepting new asynchronous work after deployment begins.

Rolling Updates

Enable rolling updates on the ECS side.
A rolling update gradually replaces containers running the old version with containers running the new version. The number of old and new tasks that can run at the same time is determined by  minimumHealthyPercent ,  maximumPercent , and  desiredCount  for the ECS service. Therefore, ECS does not necessarily start and stop tasks one at a time.
The default deployment strategy for an ECS service is  ROLLING . When configuring it explicitly, also set the availability percentages. In the following example, ECS keeps at least  desiredCount  healthy tasks running and can temporarily run up to twice that number of tasks.
aws ecs update-service \
--cluster my-cluster \
--service my-service \
--deployment-configuration \
'{"strategy":"ROLLING","minimumHealthyPercent":100,"maximumPercent":200}'
For example, even when  desiredCount  is 1, setting  maximumPercent  to 200 lets ECS start one new task and wait until it is healthy before stopping the old task.

Health Checks

When configuring rolling updates, pay close attention to container health checks.
The health-check result determines whether a new container has started successfully. For a Spring Boot application on ECS, the container should be considered healthy only after the Spring Boot JAR has started and the application can accept requests on port 8080.

Without an application-aware health check, a container can be treated as ready before the Spring Boot application has actually finished starting. Requests could then reach the container too early and return HTTP 5xx errors to clients. Implement and configure a health check that waits until the application is ready.

Implement a Health Check in the Application

Spring Boot Actuator makes it easy to implement health checks.
dependencies {
implementation("org.springframework.boot:spring-boot-starter-actuator")
}
After adding this dependency to  build.gradle , you can check the application status at  GET http://localhost:8080/actuator/health .

Update the ALB or ECS Health-Check Configuration

When the ALB communicates with ECS, configure the Actuator health-check endpoint in the ALB target group.
aws elbv2 modify-target-group \
--target-group-arn <target-group-arn> \
--health-check-protocol HTTP \
--health-check-port traffic-port \
--health-check-path /actuator/health \
--health-check-interval-seconds 30 \
--health-check-timeout-seconds 5 \
--healthy-threshold-count 2 \
--unhealthy-threshold-count 2 \
--matcher 'HttpCode=200'
  •  health-check-port : Use  traffic-port  to use the port forwarded to the ECS container.
  •  health-check-path : The application health-check path.
  •  matcher : The HTTP status code regarded as healthy. Usually, use 200.
  •  healthy-threshold-count : The number of consecutive successful checks required before the target becomes healthy.
  •  unhealthy-threshold-count : The number of consecutive failed checks required before the target becomes unhealthy.
If ECS tasks communicate through ECS Service Discovery, configure the health-check endpoint in the ECS task definition instead.
"healthCheck": {
"command": [
"CMD-SHELL",
"curl -f http://localhost:8080/actuator/health || exit 1"
],
"interval": 30,
"timeout": 5,
"retries": 3,
"startPeriod": 60
}
  •  command 
  • The health-check command run inside the container.
  •  CMD-SHELL  runs the command through a shell, allowing shell syntax such as  || .
  •  curl -f  exits with failure for HTTP status 400 or above.
  • Exit code 0 is healthy; any other exit code is unhealthy.
  •  interval 
  • Runs the health check every 30 seconds.
  •  timeout 
  • Marks a health check as failed if the command does not complete within 5 seconds.
  •  retries 
  • Marks the container as  UNHEALTHY  after three consecutive failures.
  • For tasks managed by an ECS service, unhealthy tasks are normally stopped and replaced.
  •  startPeriod 
  • Provides a 60-second startup grace period after the container starts.
  • Failures during this period do not count toward  retries .

Aside: ECS Service Discovery

While researching this topic, ECS Service Discovery was a service I encountered for the first time. It lets you discover the changing IP addresses of ECS tasks by using a stable service name. In other words, it lets you address containers through DNS. AWS Cloud Map manages the mapping between IP addresses and service names.
ECS Service
├─ Task: 10.0.1.10
├─ Task: 10.0.2.20
└─ Task: 10.0.3.30
│ Automatically register and deregister
▼
AWS Cloud Map
Namespace: internal.local
Service: payment
│
▼
payment.internal.local
→ 10.0.1.10
→ 10.0.2.20
→ 10.0.3.30
Cloud Map is not specific to ECS; it is a general-purpose service that can also be used with EC2 and other AWS resources.

Summary

Depending on how the application and infrastructure are implemented, achieving zero-downtime releases can be challenging. But once achieved, they substantially reduce operational burden, so they are well worth the effort.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article