Automating EC2 Instance Recovery with CloudWatch and Auto Scaling
A web server sitting in an Amazon EC2 subnet in Sydney can fail in ways that never generate a ticket. The instance is reachable one minute and unreachable the next, or AWS flags it for scheduled maintenance and retires it quietly in the background. At 2 a.m. on a Sunday, with the on-call engineer in Perth, waiting for a human to approve a replacement is the difference between a degraded service and a breached SLA. Self-healing infrastructure removes that dependency.
The pattern is well established: CloudWatch watches for the fault, Amazon EC2 Auto Scaling replaces what is broken, and a notification or runbook tells the team what happened. Each piece is simple in isolation. The engineering sits in the details — health check types, grace periods, the gap between an instance that is technically alive and an application that is actually serving traffic, and the IAM permissions that let one service act on another.
This walkthrough covers detection with CloudWatch alarms and metrics, recovery using Auto Scaling groups and load balancer health checks, automated remediation through Lambda and Systems Manager Automation, and the Australian realities that shape deployments — data residency under the Privacy Act 1988, ACSC Essential Eight alignment, and hybrid connectivity over NBN Enterprise links into regional AWS data centres.
The failures that recovery must cover
AWS EC2 status checks report two distinct conditions: system status, which reflects the underlying host hardware, and instance reachability, which reflects the network path. Scheduled maintenance events, deprecated instance types and hardware retirement plans all generate events capable of terminating an instance without warning. Capacity rebalancing handles part of this by moving load ahead of a disruption, though it only applies where the service supports it.
The harder case is an operating system level fault — a full root volume, a hung kernel, a memory leak, or a process that holds the socket open while returning garbage. Status checks stay green because the instance still answers pings. CloudWatch metrics such as CPU utilisation, plus disk and memory utilisation published by the CloudWatch agent for paths like / and /var/lib/docker, catch many of these conditions before they become an outage.
A third failure mode is a network partition. A Sydney instance that loses its Transit Gateway attachment or its tunnel to an on-premises datacentre in Melbourne can look perfectly healthy from AWS's side while being useless to the business.
Detecting faults with CloudWatch alarms
Start with the StatusCheckFailed_System and StatusCheckFailed_Instance metrics. Create an alarm against each with a short evaluation period, then combine them in a CloudWatch composite alarm so a single degraded instance does not trigger unnecessary churn. Composite alarms are also the cleaner place to express logic such as system failure combined with sustained CPU pressure.
For application health, publish custom metrics through the CloudWatch agent, and consider a CloudWatch Synthetics canary or the HealthyHostCount metric from an Application Load Balancer. A Synthetics canary probes from multiple points and gives an external view that matches what a customer in Adelaide or Melbourne actually experiences.
Handle missing data deliberately. Configure alarm actions to treat insufficient data as not breaching, and pair that with a health check grace period on the Auto Scaling group so an agent restart or reboot does not trigger a cascading replacement wave.
Auto Scaling groups as the recovery engine
The Auto Scaling group owns the fleet, the launch template defines the instance, and the health check type determines who judges an instance unhealthy. With EC2 health checks, the group relies on EC2 status; with ELB health checks, it relies on the load balancer's target health, which tracks real service delivery far more closely. Use ELB health checks whenever a load balancer fronts the workload, otherwise a healthy-but-broken instance remains in the rotation.
Keep minimum, desired and maximum capacity distinct, spread the fleet across at least three Availability Zones in ap-southeast-2 (Sydney), and enable capacity rebalancing along with unhealthy instance replacement. Set the grace period generously enough for boot and warm-up — around 300 seconds suits a JVM opening a connection pool. Instances that fail the grace period are terminated and replaced without human involvement.
In practice the friction is capacity rather than logic. AWS infrastructure capacity can be constrained in some Availability Zones, and a replacement launch may fail outright. Mitigate by using on-demand capacity for critical workloads, avoiding single-AZ designs, and letting the group retry with backoff. Instance refresh keeps the fleet on current instance types ahead of retirement deadlines.
Wiring alerts to automated remediation
An alarm action publishing to Amazon SNS is the minimum viable path. Route that topic to a Lambda function or a Systems Manager Automation runbook: the runbook captures diagnostics, copies logs to S3 and tags the incident, while Lambda calls the EC2 API directly to initiate replacement when an instance sits outside a group.
Guardrails matter. Give each integration a dedicated IAM role with least privilege, avoid a loop where a replacement triggers the same alarm, and record every action in CloudTrail. A CloudWatch Logs metric counting replacement events gives the on-call engineer patterns rather than a stream of isolated pages.
For hybrid estates, use EventBridge to react to EC2 state-change events and scheduled maintenance notifications. Those events arrive before the instance stops, giving the runbook time to drain traffic, snapshot volumes and redirect callers.
Australian deployment and compliance realities
Australian government, healthcare and financial workloads often require processing to remain in the country. Keep primary instances in Sydney (ap-southeast-2) or Melbourne (ap-southeast-4), retain snapshots and backups in-region, and treat the Perth region (ap-southeast-5) as a latency decision rather than a default destination.
ACSC Essential Eight guidance favours automated patching and centralised logging, and the Privacy Act 1988 Australian Privacy Principles mean recovery runbooks should never replicate personal information into an overseas region without approval. Audit trail retention belongs in the same design as the replacement logic.
Connectivity shapes timing. Hybrid designs ride on NBN Enterprise and carrier Ethernet from Melbourne and Brisbane offices into the AWS network, where 15 to 30 milliseconds of latency is normal and job timeouts need tuning accordingly. Australian IT teams are frequently lean, so automation carries proportionally more weight here. Schedule infrastructure changes around public holidays such as Australia Day and AnZAC Day, when on-call cover thins.
Recommendations for a self-healing EC2 estate
- Build CloudWatch composite alarms from
StatusCheckFailed_System,StatusCheckFailed_Instanceand application metrics so recovery triggers on real faults rather than a single noisy signal. - Attach every production instance to an Auto Scaling group with ELB health checks when a load balancer fronts the workload.
- Set the health check grace period to match application warm-up time, then enable automatic unhealthy instance replacement.
- Publish disk, memory and CPU metrics with the CloudWatch agent to catch degraded instances that still pass reachability checks.
- Connect alarms to SNS, EventBridge and a Systems Manager Automation runbook, with scoped IAM roles and CloudTrail logging for every remediation action.
- Keep snapshots, backups and audit logs inside an Australian region, and rehearse a restore on a schedule.
- Document the capacity fallback: on-demand instances, multiple Availability Zones, and a tested plan for launching replacement compute in a second region.