
Improving AWS ECS Fargate Auto Scaling for PHP Applications During Sudden Traffic Spikes
Our goal is to identify and address scaling bottlenecks by optimizing CloudWatch metrics, scaling policies, container startup time, PHP-FPM configuration, and health checks. We are also exploring request-based and scheduled scaling to ensure sufficient capacity is available during peak traffic periods, particularly when handling up to 5,000 concurrent users.
Introduction
We recently deployed a PHP + Apache-based application on Amazon ECS Fargate, with a minimum of two running tasks. The application was expected to handle sudden traffic spikes of up to 5,000 concurrent users.
During our initial performance testing, we noticed an interesting issue: ECS was not scaling out quickly enough when sudden traffic spikes occurred.
Although we had configured ECS Service Auto Scaling based on CPU and memory utilization, the existing configuration wasn't responding quickly enough to sudden increases in traffic. As a result, the running containers were experiencing high resource utilization before additional tasks became available.
We started troubleshooting the issue step by step, looking at the scaling policies, CloudWatch metrics, container startup time, application configuration, and health checks.
In this blog, I'm sharing the changes we made and the approaches we're using to improve ECS Fargate auto scaling.
1. Enable High-Resolution CloudWatch Metrics
By default, Amazon ECS publishes CPU and memory utilization metrics to CloudWatch at 60-second intervals.
This can introduce a delay when your application experiences a sudden traffic spike. By the time CloudWatch detects the increased utilization and triggers the scaling policy, the existing containers might already be under significant pressure.
We enabled high-resolution ECS service metrics with a 20-second resolution.
This allows ECS Service Auto Scaling to detect changes in CPU and memory utilization much faster and respond accordingly.
There is an additional CloudWatch cost associated with high-resolution metrics, so consider this when planning your monitoring configuration.
2. Adjust the Scale-Out Cooldown Period
Another area we investigated was the scaling cooldown configuration.
The cooldown period determines how long Application Auto Scaling waits after a scaling activity before initiating another scaling action.
We reduced the scale-out cooldown period to around 60 seconds and tested different values based on application behaviour.
A shorter cooldown can help ECS initiate additional scaling activities without waiting too long for the previous scaling action to complete.
However, setting it too low without understanding the application's startup time can result in unnecessary scaling activities.
Our recommendation: Tune the scale-out and scale-in cooldown periods independently. Scale-out should be more responsive, while scale-in should be conservative to avoid removing capacity too early.
3. Optimize Container Image Size
When ECS Fargate launches a new task, it needs to retrieve the required container image from Amazon ECR (unless an applicable image-pull optimization or cache is available).
Larger container images can increase image-pull time, which adds to the overall task startup time.
We started looking at ways to reduce our Docker image size.
Some of the improvements include:
- Using multi-stage Docker builds.
- Choosing minimal base images, such as Alpine, where application compatibility allows.
- Removing unnecessary packages and dependencies.
- Cleaning up temporary files and build artifacts.
- Avoiding unnecessary files in the final image.
The objective is simple: reduce the time required to download the image and get the application ready to serve traffic.
Every second saved during task initialization can make a difference during sudden traffic spikes.
4. Tune PHP-FPM and Apache Configuration
This was one of the important areas we investigated on the application side.
In our case, we were using PHP-FPM to handle PHP requests.
Even when ECS launches additional tasks, poorly configured PHP-FPM workers can become a bottleneck. If the number of available workers is insufficient, incoming requests start waiting in the queue, eventually resulting in request timeouts.
We reviewed and adjusted PHP-FPM settings based on the CPU and memory allocated to each Fargate task.
Some of the important parameters include:
-
pm: Process management mode.
-
pm.max_children: Maximum number of child processes.
-
pm.start_servers: Number of child processes created during startup.
-
pm.min_spare_servers: Minimum number of idle processes.
-
pm.max_spare_servers: Maximum number of idle processes.
-
pm.max_requests: Number of requests a child process handles before restarting.
These values should be determined based on the application's actual memory consumption and request-processing behaviour.
For example, setting
pm.max_children too high can cause memory pressure, while setting it too low can limit the number of concurrent requests each task can handle.We also reviewed Apache's worker configuration to ensure it wasn't introducing another bottleneck.
The key takeaway: Scaling the number of containers alone doesn't solve application-level bottlenecks. PHP-FPM and Apache must also be configured to handle the expected workload.
5. Tune ECS and Load Balancer Health Checks
Task startup time is another important factor during scaling.
When ECS launches a new task, the application needs some time to initialize before it can start accepting requests.
We reviewed the health check configuration in both the ECS task definition and the Application Load Balancer.
The parameters we focused on included:
- Container health check
startPeriod.
- Health check interval.
- Health check timeout.
- Healthy threshold count.
- ECS service health check grace period.
- ALB target group health check configuration.
Our objective was to make newly launched tasks healthy and available to receive traffic as soon as the application was genuinely ready.
One important consideration: reducing health check intervals and startup periods too aggressively can cause healthy applications to be marked unhealthy during initialization.
The configuration should reflect the application's actual startup time rather than simply using the lowest possible values.
6. Explore Request-Based Auto Scaling
Initially, we tested CPU- and memory-based scaling policies.
However, resource utilization metrics alone don't always provide an early indication of incoming traffic. During sudden spikes, application response times and request queues can increase before CPU or memory utilization reaches the configured scaling threshold.
We therefore started exploring application-level and request-based scaling metrics.
Some useful metrics include:
- ALB RequestCountPerTarget: Average number of requests received per target. ECS supports this as a predefined target tracking metric.
- ALB ActiveConnectionCount: Useful for monitoring the number of active connections, although additional metric configuration may be required to use it effectively for per-task scaling.
- Amazon SQS ApproximateNumberOfMessagesVisible: Useful for applications that process asynchronous workloads through SQS queues.
For our application, request-based scaling is particularly interesting because it allows us to consider incoming workload rather than relying entirely on resource utilization.
The goal is to add capacity before the existing tasks become overloaded.
7. Pre-Provision Tasks Using Scheduled Scaling
We already have a reasonable understanding of our application's traffic patterns.
For example, we know there are certain periods during the day when traffic is consistently higher.
Instead of waiting for a traffic spike and then scaling from two tasks, we are planning to use scheduled scaling.
Our approach is to maintain:
- Normal hours: Minimum of 2 running tasks.
- Expected peak hours: Minimum of 4 running tasks.
- Special events or promotions: Increase the minimum capacity based on expected demand.
This approach helps reduce the initial scaling delay because additional tasks are already running before the traffic arrives.
It also gives the application some additional headroom during predictable traffic spikes.
Results and What's Next
After implementing and testing these changes, we observed approximately a 60% improvement in the scaling-related issues compared with our initial configuration.
However, this is still ongoing work. We are continuing to investigate additional improvements, particularly around application-level metrics, PHP-FPM tuning, and faster scaling responses.
One important lesson from this exercise is that ECS auto scaling is not just about configuring CPU and memory thresholds.
Container startup time, image size, application worker configuration, health checks, scaling cooldowns, and traffic patterns all contribute to how quickly an application can respond to increased demand.
We are still exploring ways to improve the overall scaling behaviour and make the application more resilient during sudden traffic spikes.
**
I'd be interested to hear from others who have handled similar workloads on ECS Fargate.**
What scaling strategies have worked well for your applications, particularly when dealing with sudden increases in concurrent users?
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article