When Lambda's 15-minute limit, cold starts, database connections or steady-load costs start to hurt, how to move functions to long-running containers on ECS Fargate: wrapping handlers, replacing API Gateway, SQS triggers and EventBridge schedules, and cutting over.

AWS Lambda is the easiest way to run a piece of backend code on AWS: upload a handler, attach a trigger, and pay only while it runs. It starts to hurt in predictable places, such as a report that needs longer than the 15-minute maximum, cold starts on an endpoint users wait for, two hundred concurrent invocations each opening a Postgres connection, or a bill for functions that are effectively running all day.
ECS on Fargate keeps the "no servers" part and swaps invocations for long-running containers. This guide covers when the move pays off, how to restructure handlers, what replaces API Gateway, SQS triggers and EventBridge schedules, and a cutover that keeps both running until you are sure.
If two or more rows land on the right, a container service is usually simpler and cheaper to run.
A Lambda handler mixes event parsing with business logic. Move the logic into plain functions that take typed input, and leave the handler as a thin adapter, so the same logic can be called from an HTTP route, a queue consumer and a test. This step can ship while everything still runs on Lambda.
ReceiveMessage, process, DeleteMessage on success. Keep the queue's redrive policy and set the visibility timeout above the slowest message.Package the HTTP server and consumers in one image, or one image per service if they scale differently, and push it to ECR. Create a task definition with CPU and memory, an ECS service on Fargate with a minimum task count, a target group with a health check, and autoscaling on CPU or queue depth.
The Lambda execution role becomes two roles: an execution role that lets ECS pull the image and read secrets, and a task role with the permissions your code uses, such as reading from the queue and writing to the bucket. Environment variables move to the task definition, and secrets move to Secrets Manager references in the same definition. Database connections can now come from a pool in each task, which usually lets you drop RDS Proxy.
Run both side by side. For APIs, add the ALB as a second origin and shift traffic with weighted DNS or a CloudFront origin group, then retire the API Gateway stage. For queue workers, start the ECS consumer, then disable the Lambda event source mapping, so a message is never left without a consumer. Keep the functions deployed but untriggered for a week as a rollback path.
Encore brings infrastructure from code to Go and TypeScript, which turns steps two to four into code: each API Gateway route becomes an endpoint, each SQS trigger becomes a subscription, and each EventBridge schedule becomes a cron job, all declared in the service, and a push deploys them to ECS on Fargate with RDS and SNS with SQS in your own AWS account. There are no task definitions, target groups or task roles to write, as the AWS infrastructure docs describe.
Install the Encore CLI with the command for your system, then create the app:
Run in your terminal to get started locally.
The migration creates a notifications table with id BIGSERIAL, recipient, message, sent_at and failed_at. Three Lambda functions, an API handler, an SQS-triggered sender and a scheduled retry, become one Go service:
// notifications/notifications.go
package notifications
import (
"context"
"errors"
"encore.dev/beta/errs"
"encore.dev/cron"
"encore.dev/pubsub"
"encore.dev/storage/sqldb"
)
var db = sqldb.NewDatabase("notifications", sqldb.DatabaseConfig{Migrations: "./migrations"})
// Set with `encore secret set`; was a Lambda environment variable.
var secrets struct {
SMSProviderKey string
}
type Queued struct{ ID int64 }
// Was the SQS queue that triggered the sender function.
var Outbox = pubsub.NewTopic[*Queued]("notification-outbox", pubsub.TopicConfig{
DeliveryGuarantee: pubsub.AtLeastOnce,
})
type SendParams struct {
Recipient string `json:"recipient"`
Message string `json:"message"`
}
// Was the API Gateway route and its Lambda handler.
//encore:api public method=POST path=/notifications
func Send(ctx context.Context, p *SendParams) error {
if p.Recipient == "" || p.Message == "" {
return &errs.Error{Code: errs.InvalidArgument, Message: "recipient and message are required"}
}
var id int64
if err := db.QueryRow(ctx, `
INSERT INTO notifications (recipient, message) VALUES ($1, $2) RETURNING id`,
p.Recipient, p.Message).Scan(&id); err != nil {
return err
}
_, err := Outbox.Publish(ctx, &Queued{ID: id})
return err
}
// Was the SQS-triggered sender function; no 15-minute ceiling here.
var _ = pubsub.NewSubscription(Outbox, "deliver", pubsub.SubscriptionConfig[*Queued]{
Handler: func(ctx context.Context, q *Queued) error {
var recipient, message string
err := db.QueryRow(ctx, `
SELECT recipient, message FROM notifications
WHERE id = $1 AND sent_at IS NULL`, q.ID).Scan(&recipient, &message)
if errors.Is(err, sqldb.ErrNoRows) {
return nil // already sent
} else if err != nil {
return err
}
// The provider call uses the notification ID as its idempotency key.
if err := sendSMS(ctx, secrets.SMSProviderKey, recipient, message, q.ID); err != nil {
_, _ = db.Exec(ctx, `UPDATE notifications SET failed_at = now() WHERE id = $1`, q.ID)
return err
}
_, err = db.Exec(ctx, `UPDATE notifications SET sent_at = now() WHERE id = $1`, q.ID)
return err
},
})
// Was the EventBridge schedule and its retry function.
var _ = cron.NewJob("retry-failed", cron.JobConfig{
Title: "Re-queue failed notifications",
Every: 1 * cron.Hour,
Endpoint: RetryFailed,
})
//encore:api private
func RetryFailed(ctx context.Context) error {
rows, err := db.Query(ctx, `
SELECT id FROM notifications
WHERE sent_at IS NULL AND failed_at IS NOT NULL LIMIT 200`)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
return err
}
if _, err := Outbox.Publish(ctx, &Queued{ID: id}); err != nil {
return err
}
}
return rows.Err()
}
func sendSMS(ctx context.Context, apiKey, to, body string, idempotencyKey int64) error {
// Call your SMS provider with apiKey and the idempotency key.
return nil
}
encore run starts Postgres and Pub/Sub locally and runs all three former functions in one process, which SAM could only approximate per function. Cron jobs are managed by the Encore platform and do not run locally or in preview environments, so RetryFailed is called from the local development dashboard while testing. On push, Encore provisions the service on ECS Fargate behind a load balancer, the RDS database, an SNS topic with an SQS queue and dead-letter queue for the subscription, and the secret in Secrets Manager, and Encore provisions an IAM role for the service. The service holds a connection pool per task, so there is no RDS Proxy to add. A coding agent porting the next function adds an endpoint or a subscription to this service and runs it locally before the pull request, instead of writing a new task definition.
The database, Pub/Sub, cron job and secrets docs cover each declaration used here in more detail.
Best fit: teams moving a set of Lambda functions that share a database to long-running services in their own AWS account, without writing the ECS infrastructure by hand.
Common triggers are jobs that need longer than Lambda's 15-minute maximum, cold starts on latency-sensitive endpoints, too many database connections from concurrent invocations, and steady traffic where per-invocation billing costs more than a container that is always running. Spiky, low-volume or event-glue workloads usually stay cheaper on Lambda.
Move the business logic out of the handler into ordinary functions, then call them from an HTTP server for API routes and from a queue consumer for SQS-triggered functions. Package that as one container image, run it as an ECS service behind an Application Load Balancer, and give the task a role with the permissions the Lambda execution role had.
The Lambda event source mapping polled SQS for you. On ECS, a consumer in the service long-polls ReceiveMessage, processes each message, deletes it on success, and lets the redrive policy move repeated failures to a dead-letter queue. The visibility timeout must be longer than the slowest message.
With Encore, API endpoints, queue subscribers and cron jobs are declared in Go or TypeScript. encore run starts them locally with Postgres and Pub/Sub, and a git push deploys them as services on ECS Fargate with RDS and SNS with SQS in your own AWS account.
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.