# When the Auto Scaling Schedule Took Production Down

*Two pieces of automation, both doing their job perfectly, and production still went down*

Let me tell you about two coworkers who never talk to each other.

The first one is **the schedule**. Every morning it shows up and adds an extra server so we're ready for the busy hours. Every evening it removes that server so we don't pay for something nobody is using. Very reliable. Never late. Never asks questions.

The second one is **the health alarm**. It watches the load balancer, and the moment a server goes unhealthy, it calls for backup and adds a new one. When everything is healthy again, it sends the backup home.

Both of them are great at their jobs. The problem is, they have no idea the other one exists. And one day that cost us production.

## Our setup

We run one primary server all the time, plus an auto scaling group behind the same load balancer. Both the schedule and the alarm control that group.

On paper this is safe. Busy hours get extra capacity, and if something breaks, the alarm brings help. What could go wrong? :)

## The day it went wrong

Production went down. The first thing I opened was the auto scaling group's activity history, and when I put the events in order, it read like a bad comedy:

```plaintext
morning   the schedule adds a server       2 running, 2 healthy
later     both servers become unhealthy    2 running, 0 healthy
          the alarm calls for backup       3 running, 1 healthy
evening   the schedule clocks out          1 running, 0 healthy
```

The alarm did exactly what it should. It saw unhealthy servers and brought a fresh one, and that fresh server was the only healthy one we had. It was literally holding production up by itself.

Then the evening came, and the schedule did exactly what it should too. It looked at the clock, saw it was time, and scaled the group down. It didn't ask why there were more servers than usual. It didn't check if anyone was sick. It just sent everyone home, including the only healthy server we had.

We were left with the unhealthy primary, all alone. And that means production down.

The funny part (funny now, not that day) is that nothing was misconfigured. Every piece worked exactly as designed. They were just working against each other.

## Can't AWS handle this on its own?

That was my first question too. Surely AWS thought about this, right? I went through the docs, and the short answer is: not really.

A scheduled action doesn't care how the servers got there. From the [scheduled scaling docs](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-scheduled-scaling.html):

> If current capacity is greater than the specified desired capacity, Amazon EC2 Auto Scaling scales in, or removes instances, to the specified desired capacity.

In other words, the schedule knows two things, the time and a number. That's it.

You **can** pause it. The same page says you can "temporarily turn off scheduled scaling for an Auto Scaling group by suspending the `ScheduledActions` process". But nothing built in will flip that switch for you when an alarm fires. Something has to do it, and it really shouldn't be a human waiting for an alert.

And there's one more catch, which turned out to matter a lot. From the [docs on suspending processes](https://docs.aws.amazon.com/autoscaling/ec2/userguide/understand-how-suspending-processes-affects-other-processes.html):

> Amazon EC2 Auto Scaling does not run scheduled actions that are scheduled to run during the suspension period.

So if the schedule is paused when the morning scale-up was supposed to happen, that scale-up just doesn't happen. It doesn't wait for you, it's gone.

If your setup allows it, the cleanest built-in answer is to put every server inside the auto scaling group with load balancer health checks, so AWS replaces unhealthy servers by itself. That wasn't an option for us at the time, so we needed some glue.

## Two options

I wrote down two options in the incident report:

1. **Make the schedule wait.** A Lambda that pauses the scheduled actions while the alarm is firing, and lets the schedule continue once the alarm clears.
2. **Fire the schedule.** Remove the scheduled actions completely and let a Lambda handle all the scaling, based on the time and the health of the servers.

We went with option 1. It was simpler, and it kept the schedules. On a normal day the schedule was doing a great job, it just needed to learn to wait when there's an emergency.

## Proving it first

I didn't want to try this idea directly on production (production had been through enough already). So I built a small copy of the setup in a sandbox: a simple web server behind a load balancer, an auto scaling group, a CloudWatch alarm on `UnHealthyHostCount`, and the Lambda. I used it to test the whole flow before going near the real thing, and recorded a walkthrough of it.

The first version of the Lambda was tiny. On `ALARM`, pause the scheduled actions. On `OK`, resume them. Plus one extra step that is easy to miss: if the alarm clears during business hours, put the business-hours server back, because the morning scale-up might have been skipped while the schedule was paused.

## The version we run now

A year later, during a bigger infrastructure review, the Lambda grew up a bit. Here's a simplified version of what it does today:

```python
import json
import os
from datetime import datetime
from zoneinfo import ZoneInfo

import boto3

autoscaling = boto3.client("autoscaling")
cloudwatch = boto3.client("cloudwatch")

ASG_NAME = "app-asg"
WATCHED_ALARMS = ["CPUHigh", "MemoryHigh", "UnhealthyHosts"]
TIME_ZONE = ZoneInfo(os.environ["TIME_ZONE"])  # your users' time zone
BUSINESS_START, BUSINESS_END = 8, 18            # your business hours
MAX_SIZE = 3                                    # your max group size


def lambda_handler(event, context):
    alarm = json.loads(event["Records"][0]["Sns"]["Message"])
    group = autoscaling.describe_auto_scaling_groups(
        AutoScalingGroupNames=[ASG_NAME]
    )["AutoScalingGroups"][0]
    min_size, desired = group["MinSize"], group["DesiredCapacity"]

    if alarm["NewStateValue"] == "ALARM":
        pause_schedule()
        # Base it on min, not desired. Desired might be stale here.
        set_capacity(desired=min_size + 1, min_size=min_size + 1)

    elif alarm["NewStateValue"] == "OK":
        if not any_alarm_firing():
            resume_schedule()
        set_capacity(desired=desired, min_size=max(min_size - 1, 0))

        # A scheduled scale-up may have been skipped while we were paused.
        if in_business_hours() and desired == 0 and min_size == 0:
            set_capacity(desired=1, min_size=1)


def any_alarm_firing():
    try:
        alarms = cloudwatch.describe_alarms(AlarmNames=WATCHED_ALARMS)["MetricAlarms"]
        return any(a["StateValue"] == "ALARM" for a in alarms)
    except Exception:
        return False  # if we can't check, don't leave the schedule paused forever


def in_business_hours():
    now = datetime.now(TIME_ZONE)
    return BUSINESS_START <= now.hour < BUSINESS_END


def pause_schedule():
    autoscaling.suspend_processes(AutoScalingGroupName=ASG_NAME, ScalingProcesses=["ScheduledActions"])


def resume_schedule():
    autoscaling.resume_processes(AutoScalingGroupName=ASG_NAME, ScalingProcesses=["ScheduledActions"])


def set_capacity(desired, min_size):
    autoscaling.update_auto_scaling_group(
        AutoScalingGroupName=ASG_NAME, DesiredCapacity=desired, MinSize=min_size, MaxSize=MAX_SIZE
    )
```

What changed from the first version, and why:

- **Three alarms instead of one.** Unhealthy hosts, high CPU and high memory all trigger it now. A server can be alive but drowning long before the load balancer calls it unhealthy.
- **Only resume when every alarm is clear.** With three alarms, one can go back to `OK` while another is still firing. If the first `OK` resumed the schedule, we'd be right back where we started.
- **Raise the minimum, not just desired.** Raising `MinSize` together with `DesiredCapacity` means nothing else can quietly scale the group back down while the alarm is active.
- **Local time zone.** The business-hours check uses the users' time zone, not UTC.
- **Don't get stuck.** If checking the alarms fails, it resumes the schedule anyway, so a bug can't leave the schedule paused forever.
- **A dry run mode.** A flag that only logs what it would do, which makes it much easier to test changes without touching the real group.

## What it doesn't solve

The Lambda only helps while an alarm is firing. If something fails after the evening scale-down has already happened, a new server has to start from zero, and that takes a few minutes. So it's not a replacement for having enough servers running while your users are actually there. Make sure the schedule matches when people really use the system, not just a guess of "business hours".

## What I took from this

- **Automation doesn't talk to other automation unless you make it.** Two things that are each correct can still take you down together.
- **Scheduled actions are blunt.** They set numbers at a time. They don't know about incidents, alarms or anything else that happened that day.
- **Check the activity history first.** It showed the whole pattern across all the servers, which you'd never see from one server's logs.
- **Paused schedules skip, they don't catch up.** If you pause scheduled actions, you need to handle what was missed.
- **Prove it somewhere safe first.** A small sandbox copy of the setup was enough to see the problem and test the fix without risking production.

In the end it's a small Lambda, basically a note on the schedule's desk that says "not now, there's an emergency". But it closed a gap that took production down, and it's a gap AWS doesn't close for you.

That's all for now. If you're interested in more advanced content about WSGI, Apache, or other DevOps topics, there are many articles in the DevOps series that you might find interesting.

Mostafa-DE Fayyad

Software Engineer
