An ECS service at 1/1 running that restarted every 80 seconds
Our ECS console showed 1/1 running while the task was OOM-killed about every 80 seconds for weeks. How to see stopped tasks, why a full-refresh replication job ate 512 MB, and an EventBridge alarm on restarts.
Desired 1, running 1. For weeks that is what the ECS console showed for our background jobs service, and for weeks the task inside it was being killed for running out of memory roughly every 80 seconds. Exit code 137, a fresh task, 80 seconds of work, exit code 137 again.
I found it on 3 September, that too by accident. We had just resized the main RDS instance and I was walking through every service to check it came back properly. The jobs service looked fine at first glance. It wasn't.
In this blog we will look at why the console lied (well, it didn't lie, it answered a different question), how to see the stopped tasks, what was eating the memory, and the alarm I'd put on every service so this can't hide for weeks again.
Why 1/1 looks healthy
An ECS service has one promise: keep desiredCount tasks running. When a task dies, the scheduler starts a replacement within seconds. So if you look at the service at a random moment, the replacement is almost always already there and the count says 1/1.
The number that tells you something is how many tasks it has started, and the console doesn't put that on the front page.
Other things that also didn't help here:
- The deployment circuit breaker only watches a deployment while it is rolling out. Once a deployment is marked complete, later crashes are none of its business.
- There was no load balancer health check, as this is a worker with no HTTP port.
- CPU and memory graphs looked noisy but normal, because every new task starts at near zero.
One sign was there if you knew to look. The service never reached a steady state, so the events never had that line in them.
Seeing the stopped tasks
ECS keeps stopped tasks visible for a short time only (the docs promise at least an hour), so look soon after you suspect something. List them and pull the stop reason:
CLUSTER=my-cluster
SERVICE=worker
aws ecs list-tasks --cluster "$CLUSTER" --service-name "$SERVICE" \
--desired-status STOPPED --query 'taskArns' --output text \
| tr '\t' '\n' | head -20 > stopped.txt
aws ecs describe-tasks --cluster "$CLUSTER" --tasks $(cat stopped.txt) \
--query 'tasks[].{started:startedAt,stopped:stoppedAt,code:stopCode,reason:stoppedReason,exit:containers[0].exitCode}' \
--output table
describe-tasks takes at most 100 tasks per call, which is why I cut the list at 20. What came back was the same row again and again:
code: EssentialContainerExited
exit: 137
reason: OutOfMemoryError: container killed due to memory usage
The gap between startedAt and stoppedAt were around 80 seconds. Then the service events, newest first:
aws ecs describe-services --cluster "$CLUSTER" --services "$SERVICE" \
--query 'services[0].events[:10].[createdAt,message]' --output text
In a loop like this, expect a wall of "has started 1 tasks" lines and nothing else.
To get a feel for how long it had been going on I counted log streams, since the awslogs driver makes one stream per task. On 3 September alone there were about 255, and the listing I pulled was capped, so the true number was higher. The oldest streams I looked at went back to 2 September. It had very likely been running like this since a long time before that.
What was eating 512 MB
The task was small itself: 0.25 vCPU and 512 MB. The service runs a few scheduled routines, and one of them copies tables from the main Postgres database into a separate analytics database. Its logs just before each death had the same line:
source table has no primary key, refreshing in full
The copy code had two paths. For a table with a primary key it does keyset paging: fetch 1,000 rows after the last id, write them, repeat. Memory stays flat. For a table without a primary key it can't page, because there is nothing stable to order by, so it fell back to a "full refresh": read the whole table into a slice, then write it all. Several source tables had no primary key. The first big one blew through 512 MB, the kernel killed the container, and the next task started the routine from the beginning. Forever.
Two side effects made this quite worse than a noisy log. The analytics copy was never actually completing, so that data was quietly stale. And every 80 seconds the main database got a full table scan of the same tables. At that time it was on a tiny burstable instance with 1 GB of memory, and I think (I can't prove it) this loop was part of the memory pressure that made us resize it in the first place.
Fixing the copy
Giving the task 2 GB would have hidden it for some time. Tables grow, so that's a delay only. There are two real fixes.
First, give the tables a key. A table without a primary key is a problem for replication of every kind, logical replication included, so this is worth doing anyway:
ALTER TABLE audit_events ADD COLUMN id bigint GENERATED ALWAYS AS IDENTITY;
ALTER TABLE audit_events ADD PRIMARY KEY (id);
On a big table, adding the identity column rewrites the table and holds a lock, so do it in a quiet window. Once there is a key, the paging query is the boring one:
SELECT * FROM audit_events WHERE id > $1 ORDER BY id LIMIT 1000;
Second, for any table you can't change, stream instead of loading. A database/sql cursor already hands rows over one at a time; the bug was collecting them all before writing. This keeps one batch in memory at most:
const batchSize = 1000
// Batch receives at most batchSize rows. It must not keep the slice.
type Batch func(ctx context.Context, rows [][]any) error
// streamTable reads a table without a primary key one row at a time and hands
// it on in batches, so memory stays at one batch however big the table is.
func streamTable(ctx context.Context, db *sql.DB, table string, ncols int, sink Batch) error {
rows, err := db.QueryContext(ctx, fmt.Sprintf("SELECT * FROM %s", table))
if err != nil {
return err
}
defer rows.Close()
batch := make([][]any, 0, batchSize)
for rows.Next() {
vals := make([]any, ncols)
ptrs := make([]any, ncols)
for i := range vals {
ptrs[i] = &vals[i]
}
if err := rows.Scan(ptrs...); err != nil {
return err
}
batch = append(batch, vals)
if len(batch) == batchSize {
if err := sink(ctx, batch); err != nil {
return err
}
batch = batch[:0]
}
}
if err := rows.Err(); err != nil {
return err
}
if len(batch) > 0 {
return sink(ctx, batch)
}
return nil
}
The table name here comes from our own list of tables, never from user input; quote it with your driver's identifier quoting anyway. I checked this compiles and passes go vet on Go 1.27. On the write side, truncate and refill the target table inside one transaction, so readers of the analytics database never see it half empty.
An alarm on restarts
This is the part I'd do for every service today, whatever it runs. EventBridge sees every task state change. A rule that matches STOPPED tasks for one service gives you two things: a log group with the full stop history (much longer than the hour ECS keeps it), and a MatchedEvents metric you can alarm on.
resource "aws_cloudwatch_log_group" "stopped_tasks" {
name = "/aws/events/ecs-stopped-${var.service_name}"
retention_in_days = 30
}
resource "aws_cloudwatch_event_rule" "task_stopped" {
name = "ecs-${var.service_name}-task-stopped"
event_pattern = jsonencode({
source = ["aws.ecs"]
"detail-type" = ["ECS Task State Change"]
detail = {
clusterArn = [{ wildcard = "*:cluster/${var.cluster_name}" }]
group = ["service:${var.service_name}"]
lastStatus = ["STOPPED"]
}
})
}
resource "aws_cloudwatch_event_target" "to_logs" {
rule = aws_cloudwatch_event_rule.task_stopped.name
arn = aws_cloudwatch_log_group.stopped_tasks.arn
}
data "aws_iam_policy_document" "events_to_logs" {
statement {
actions = ["logs:CreateLogStream", "logs:PutLogEvents"]
resources = ["${aws_cloudwatch_log_group.stopped_tasks.arn}:*"]
principals {
type = "Service"
identifiers = ["events.amazonaws.com", "delivery.logs.amazonaws.com"]
}
}
}
resource "aws_cloudwatch_log_resource_policy" "events_to_logs" {
policy_name = "events-to-ecs-stopped-${var.service_name}"
policy_document = data.aws_iam_policy_document.events_to_logs.json
}
# A healthy service stops a task only on deploys and scale-in.
# More than 3 stops in 15 minutes means something is killing it.
resource "aws_cloudwatch_metric_alarm" "restarts" {
alarm_name = "ecs-${var.service_name}-restarting"
namespace = "AWS/Events"
metric_name = "MatchedEvents"
dimensions = { RuleName = aws_cloudwatch_event_rule.task_stopped.name }
statistic = "Sum"
period = 900
evaluation_periods = 1
threshold = 3
comparison_operator = "GreaterThanThreshold"
treat_missing_data = "notBreaching"
alarm_actions = [var.alarm_topic_arn]
}
I validated this with Terraform 1.17.1 and AWS provider 6.74.0 (terraform validate only, not applied for this post). Missing data is notBreaching on purpose: no stopped tasks means no data points, and that's the good case. A normal rolling deploy of a one-task service stops one task, so a threshold of 3 in 15 minutes stays quiet during deploys and fires within one period of a crash loop like ours, which would have done more than 10 stops in that window.
Why not send each event straight to SNS? Because at one event every 80 seconds you'd get over a thousand mails a day and filter them out by lunch. One alarm that goes red and stays red is easier to act on.
If you are new to how services, tasks and deployments fit together, ECS explained covers the basics. And if you run a proxy box somewhere that can also die silently, the same "alarm on the thing users need, not the instance" idea is in the nginx proxy that died after unattended-upgrades.
Since then I don't read 1/1 as healthy. I read the stop reasons.