What the ECS OutOfMemoryError and exit code 137 mean, how task and container memory limits interact on Fargate, how to confirm the cause with Container Insights, and how to fix the limit or the code that outgrew it.

An ECS task that stops with OutOfMemoryError: Container killed due to memory usage and exit code 137 was killed by the kernel for crossing its memory limit, and ECS will keep replacing it, so the service often looks healthy between crashes while requests and messages in flight are lost.
The fix is either more memory or less usage, and choosing correctly starts with confirming the stop was a memory kill.
Exit code 137 means the process received SIGKILL, and an OOM kill is only one way to get there. A container that ignores SIGTERM during a deployment is also killed with SIGKILL after the stop timeout, and adding memory does nothing for that. Read the container reason on a recently stopped task:
aws ecs describe-tasks --cluster prod --tasks "$TASK_ARN" \
--query 'tasks[].{stopCode:stopCode,stoppedReason:stoppedReason,
containers:containers[].{name:name,exitCode:exitCode,reason:reason}}'
OutOfMemoryError: Container killed due to memory usage in a container's reason settles it. Stopped tasks stay visible for a limited time, so check soon after an incident or have an EventBridge rule capture task state changes.
The task definition parameters define memory at two levels. On Fargate, the task-level memory is required, must match a valid CPU and memory combination, and is the hard ceiling for all containers in the task; memoryReservation does not size a Fargate task. Each container can also set memory, a hard limit that kills that container when crossed. On EC2, memoryReservation is a soft limit that ECS uses for placement, and the container may use more up to its hard limit or the memory left on the instance.
A common trap is a sidecar such as a log router or an OpenTelemetry collector, which shares the task's memory with the app container, or a container hard limit set lower than the task size, so the app dies with free memory left in the task. The Fargate task size table lists the valid combinations.
With Container Insights enabled, MemoryUtilized per container shows whether usage climbs steadily (a leak or an unbounded cache), spikes with traffic (concurrency), or jumps on specific jobs (a large file or query result loaded at once). AWS's OutOfMemory troubleshooting guide includes a Logs Insights query over the Container Insights performance logs that charts MemoryUtilized against MemoryReserved per task.
GOMEMLIMIT slightly below the container limit, such as 900MiB for 1 GiB, so the garbage collector works harder before the kernel steps in. The Go GC guide explains the soft limit.--max-old-space-size larger than the container limit lets the heap grow past it, and Buffer data lives outside the V8 heap, so leave room for both.-XX:MaxRAMPercentage so the heap follows the container size.Most OOM kills in backend services come from doing too much at once rather than from leaks: a worker that pulls ten messages and loads a 200 MB file for each, an export that builds the whole CSV in memory, or an endpoint that reads an unbounded query result into a slice. Bounding concurrency and streaming large data keeps peak memory flat regardless of input size.
Best fit: confirm the OOM in the container reason, size the task from MemoryUtilized at peak plus headroom, and fix unbounded concurrency or buffering in code.
Encore brings infrastructure from code, so the queue a worker reads from and the limit on how many messages it handles at once are declared together in the service, and on AWS Encore provisions them as SNS and SQS in your account with the service running on Fargate or EKS, as the AWS infrastructure docs describe. This import worker processes at most two files per instance and streams each one from the bucket line by line:
Run in your terminal to get started locally.
// imports/worker.go
package imports
import (
"context"
"encoding/csv"
"errors"
"io"
"encore.dev/pubsub"
"encore.dev/storage/objects"
"encore.dev/storage/sqldb"
)
// migrations/1_create_rows.up.sql:
// CREATE TABLE imported_rows (import_id text NOT NULL, line bigint NOT NULL,
// sku text NOT NULL, quantity int NOT NULL, PRIMARY KEY (import_id, line));
var db = sqldb.NewDatabase("imports", sqldb.DatabaseConfig{Migrations: "./migrations"})
var uploads = objects.NewBucket("import-uploads", objects.BucketConfig{})
type ImportRequested struct {
ImportID string `json:"import_id"`
ObjectKey string `json:"object_key"`
}
var ImportTopic = pubsub.NewTopic[*ImportRequested]("import-requested", pubsub.TopicConfig{
DeliveryGuarantee: pubsub.AtLeastOnce,
})
var _ = pubsub.NewSubscription(ImportTopic, "process-import", pubsub.SubscriptionConfig[*ImportRequested]{
Handler: processImport,
MaxConcurrency: 2, // at most two files at once per instance
})
func processImport(ctx context.Context, msg *ImportRequested) error {
r := uploads.Download(ctx, msg.ObjectKey)
defer r.Close()
cr := csv.NewReader(r)
cr.FieldsPerRecord = 2
var line int64
for {
rec, err := cr.Read()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return err
}
line++
// Idempotent on redelivery: the primary key skips rows already written.
_, err = db.Exec(ctx, `
INSERT INTO imported_rows (import_id, line, sku, quantity)
VALUES ($1, $2, $3, $4::int)
ON CONFLICT DO NOTHING
`, msg.ImportID, line, rec[0], rec[1])
if err != nil {
return err
}
}
return r.Err()
}
MaxConcurrency caps simultaneous messages per instance of the service, so memory stays proportional to two files' working sets however long the queue gets, and the Pub/Sub docs cover delivery guarantees and retries. The bucket reader streams the object, which the object storage docs describe, so a 2 GB upload uses the same memory as a 2 KB one. On AWS, Encore provisions an IAM role for the service.
encore run runs the topic, subscription and bucket locally, so you can publish a large test file and watch the handler in the trace before deploying. An AI coding agent that adds a second worker copies the subscription config with its concurrency limit, which keeps the next import type from reintroducing the unbounded pattern, and if one service needs more memory than the others, the infrastructure configuration docs explain how process allocation can run it in its own process.
Best fit: queue workers and import jobs that handle files or batches of unpredictable size on Fargate.
The container used more memory than its hard limit in the task definition, so the kernel killed it with SIGKILL and ECS stopped the task with exit code 137. Either raise the container or task memory, or reduce the memory the application uses at peak.
No. 137 means the process received SIGKILL, which also happens when a container ignores SIGTERM during a deployment and ECS kills it after the stop timeout. Check the container's reason field for the OutOfMemoryError text before raising memory.
On Fargate, the task-level memory is the hard ceiling for every container in the task, and memoryReservation does not size the task. Container-level memory is an optional hard limit that kills that container if it is crossed. On EC2, memoryReservation is a soft limit that ECS uses for placement, and the container may use more up to its hard limit or the memory left on the instance.
Set MaxConcurrency on the pubsub.SubscriptionConfig so each instance handles a bounded number of messages at once, and stream large objects from the bucket instead of reading them into memory. Each running subscriber shows up in the local trace from encore run.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.