Skip to content

AWS.ECS reference

Source: packages/aws/src/ECS/CapacityProvider.ts

An Amazon ECS capacity provider, backed by an EC2 Auto Scaling Group or by Amazon ECS Managed Instances.

Auto Scaling Group providers are associated with one or more ECS clusters via Cluster#capacityProviders. Managed Instances providers belong to one cluster and are available to it as soon as they exist. Services and tasks select either kind through a capacity provider strategy.

The reserved AWS providers FARGATE and FARGATE_SPOT do not need to be created and can be referenced by name on a Cluster directly.

CapacityProvider: Creating Capacity Providers

Section titled “CapacityProvider: Creating Capacity Providers”
const provider = yield* CapacityProvider("AppCapacityProvider", {
autoScalingGroupArn: asg.autoScalingGroupArn,
managedScaling: {
status: "ENABLED",
targetCapacity: 80,
minimumScalingStepSize: 1,
maximumScalingStepSize: 10,
},
managedTerminationProtection: "ENABLED",
});
yield* Cluster("AppCluster", {
capacityProviders: [provider.name],
defaultCapacityProviderStrategy: [
{ capacityProvider: provider.name, weight: 1 },
],
});

ECS launches and patches the instances of a Managed Instances provider itself, when tasks need them, and drains them when they are empty. The provider creates the infrastructure role ECS assumes, the instance profile the instances run with and their security group, unless you pass your own.

It also creates a security group for the tasks that run on the instances, taskSecurityGroupId, with no inbound rules. Deleting the provider stops the tasks still running on it, then deletes both groups.

Managed Instances Capacity Provider

const cluster = yield* Cluster("AppCluster", {});
const provider = yield* CapacityProvider("AppInstances", {
cluster: cluster.clusterName,
managedInstancesProvider: {
instanceLaunchTemplate: {
networkConfiguration: { subnets: [subnet.subnetId] },
instanceRequirements: {
vCpuCount: { min: 2, max: 8 },
memoryMiB: { min: 4096 },
},
},
},
});

Your own infrastructure role and instance profile

const provider = yield* CapacityProvider("AppInstances", {
cluster: cluster.clusterName,
managedInstancesProvider: {
infrastructureRoleArn: infrastructureRole.roleArn,
instanceLaunchTemplate: {
ec2InstanceProfileArn: instanceProfile.instanceProfileArn,
networkConfiguration: { subnets: [subnet.subnetId] },
instanceRequirements: {
vCpuCount: { min: 2, max: 8 },
memoryMiB: { min: 4096 },
},
},
},
});

Set nitroEnclavesEnabled to launch instances that run each task in its own Nitro Sandbox, a lightweight VM isolated by the Nitro hypervisor. The provider picks instance types that support Nitro Sandboxes. Tasks opt in with isolation: "isolated" on AWS.ECS.Task.

Capacity for isolated tasks

const provider = yield* CapacityProvider("SandboxInstances", {
cluster: cluster.clusterName,
managedInstancesProvider: {
instanceLaunchTemplate: {
networkConfiguration: { subnets: network.privateSubnetIds },
nitroEnclavesEnabled: true,
},
},
});

Choose the instance types

const provider = yield* CapacityProvider("SandboxInstances", {
cluster: cluster.clusterName,
managedInstancesProvider: {
instanceLaunchTemplate: {
networkConfiguration: { subnets: network.privateSubnetIds },
nitroEnclavesEnabled: true,
instanceRequirements: {
vCpuCount: { min: 4, max: 8 },
memoryMiB: { min: 8192 },
allowedInstanceTypes: ["m6i.xlarge", "m7i.xlarge"],
},
},
},
});

CapacityProvider: Adopting Existing Capacity Providers

Section titled “CapacityProvider: Adopting Existing Capacity Providers”

Foreign-tagged capacity providers (i.e. providers that exist in AWS but were not created by this stack/stage/logical-id) are surfaced as Unowned by read, and the engine fails with OwnedBySomeoneElse unless adoption is explicitly opted in via --adopt or adopt.

import { adopt } from "alchemy/AdoptPolicy";
yield* CapacityProvider("AppCapacityProvider", {
name: "existing-provider",
autoScalingGroupArn: asg.autoScalingGroupArn,
}).pipe(adopt());

CapacityProvider: Looking up an existing capacity provider

Section titled “CapacityProvider: Looking up an existing capacity provider”

CapacityProvider.lookup references a capacity provider Alchemy doesn’t manage (created in the console or by another stack), found by name (and cluster, for a Managed Instances provider). It is read during plan/deploy and never created, updated or deleted.

const spot = AWS.ECS.CapacityProvider.lookup({ name: "spot" });

Source: packages/aws/src/ECS/Cluster.ts

An Amazon ECS cluster for running tasks and services.

const cluster = yield* Cluster("AppCluster", {});

Cluster.lookup references a cluster Alchemy doesn’t manage (created in the console or by another stack), found by clusterName. It is read during plan/deploy and never created, updated or deleted.

const cluster = AWS.ECS.Cluster.lookup({ clusterName: "shared" });
const service = yield* AWS.ECS.Service("Web", {
cluster: cluster.clusterArn,
taskDefinition: task.taskDefinitionArn,
});

Source: packages/aws/src/ECS/ContinueServiceDeployment.ts

Runtime binding for ecs:ContinueServiceDeployment.

Bind this operation to a Service inside a function runtime to get a callable that resumes a blue/green deployment paused at a lifecycle-hook stage — the canonical consumer is the deployment lifecycle-hook Lambda that validates the green revision and then approves (or vetoes) the traffic shift. The host is granted ecs:ContinueServiceDeployment on the bound service’s deployments.

ContinueServiceDeployment: Service Deployments

Section titled “ContinueServiceDeployment: Service Deployments”
const continueServiceDeployment =
yield* AWS.ECS.ContinueServiceDeployment(service);
yield* continueServiceDeployment({
serviceDeploymentArn: deploymentArn,
hookId,
});

Source: packages/aws/src/ECS/CreateSandbox.ts

Create and manage sandboxes from a Lambda Function, an ECS Service or any other host in the VPC. Each sandbox is one run of an AWS.ECS.Task on a capacity provider. Set isolation: "isolated" on the Task and every sandbox runs in its own Nitro Sandbox, a VM the Nitro hypervisor isolates from the instance and from every other task.

ECS itself starts, stops and describes a task. This binding is Alchemy’s construct on top: it adds what answers a handle inside the task. To run an isolated Task with ECS alone, bind AWS.ECS.RunTask or run it as an AWS.ECS.Service instead. A Task this binding does not target has nothing of Alchemy’s in it.

The handle runs commands, streams processes, reads and writes files, opens terminals and calls ports inside the sandbox. The Task is either an image with nothing of Alchemy’s in it, or an Effect program, whose methods the handle also has, typed from the Task class.

The host reaches a sandbox at its private address. Sandboxes join the capacity provider’s task security group, which admits nothing by default. The binding creates a security group for the host and a rule that admits it into the sandboxes’ group, and attaches a Lambda Function to the capacity’s subnets. A sandbox cannot reach the host or another sandbox through these groups. Each sandbox also gets a random token that every call carries. connect reads the token back from the task, so a host that may describe the cluster’s tasks may call their sandboxes.

Sandboxes created at run time are tagged with the stack, stage and host (alchemy::stack, alchemy::stage, alchemy::id). They are not resources in the stack: deleting the capacity provider stops them.

One sandbox per request, killed when the request ends

const capacity = yield* Capacity;
const sandboxes = yield* AWS.ECS.CreateSandbox(capacity, MySandbox);
const sandbox = yield* Effect.acquireRelease(sandboxes.create(), (sandbox) =>
Effect.ignore(sandbox.kill()),
);

A long-lived sandbox per user, found by tags

const [existing] = yield* sandboxes.list({ tags: { user } });
const sandbox = existing
? yield* sandboxes.connect(existing.taskArn)
: yield* sandboxes.create({ tags: { user }, idleTimeout: "15 minutes" });

A Task with an image or a context and no main is a sandbox of that image as it is: no Effect program, no server and no Alchemy code of yours inside. The image is pushed to your account unchanged. A small agent that serves the handle is an image of its own: when a sandbox starts, ECS mounts it read-only at /opt/alchemy/sandbox, with its own runtime, so the handle works on any Linux image, with or without Bun or Node.js installed.

The agent starts the image’s own ENTRYPOINT and CMD and keeps serving the handle whether that process runs or exits. The Task’s command replaces the CMD, as it does on any ECS task. Commands given as a string, and terminals, need /bin/sh in the image.

The binding adds three things to the Task’s task definition: a volume, a container named alchemy-sandbox-agent that copies the agent into the volume and exits, and the agent as the entry point of your container. Every run of the Task has them, also one started by a Service or by AWS.ECS.RunTask. Such a run has no token, so the agent does not listen: it runs the image’s ENTRYPOINT and CMD and exits with their exit code. A command override on that run replaces the ENTRYPOINT along with the CMD. To run one image both ways, declare a second Task that no CreateSandbox targets.

A sandbox from a public image

const MyImage = AWS.ECS.Task("MyImage", {
image: "python:3.12-slim",
cpu: 1024,
memory: 2048,
isolation: "isolated",
});
const sandboxes = yield* AWS.ECS.CreateSandbox(Capacity, MyImage);
const sandbox = yield* sandboxes.create();
yield* sandbox.files.write("/work/main.py", `print("hi")`);
const run = yield* sandbox.exec("python3 main.py", { cwd: "/work" });

A sandbox from your own Dockerfile

const MyImage = AWS.ECS.Task("MyImage", {
context: "./sandbox",
cpu: 1024,
memory: 2048,
isolation: "isolated",
});

A command in place of the image’s CMD

const MyImage = AWS.ECS.Task("MyImage", {
image: "python:3.12-slim",
command: ["python3", "-m", "http.server", "8080"],
cpu: 1024,
memory: 2048,
isolation: "isolated",
});
const sandbox = yield* sandboxes.create();
const port = yield* sandbox.getTcpPort(8080);
const response = yield* port.fetch(HttpClientRequest.get("/"));

exec runs to completion and returns { exitCode, stdout, stderr }; a non-zero exit is returned, not failed. A string runs in a shell, an array runs directly.

Write a file and run it

yield* sandbox.files.write("/work/hello.ts", `console.log("hi")`);
const run = yield* sandbox.exec("bun hello.ts", { cwd: "/work" });

Stream a long-running process

const server = yield* sandbox.start(["bun", "run", "dev"], { cwd: "/work" });
yield* server.output.pipe(
Stream.runForEach((chunk) => Effect.log(new TextDecoder().decode(chunk.data))),
);

CreateSandbox: Calling the Task’s methods

Section titled “CreateSandbox: Calling the Task’s methods”

A Task with an Effect program (main) serves the handle itself, and the handle gets the methods the program returns.

// MySandbox extends AWS.ECS.Task<MySandbox, { hello: (name: string) => Effect.Effect<string> }>
const greeting = yield* sandbox.hello("sam");
const request = yield* HttpServerRequest;
const port = yield* sandbox.getTcpPort(8080);
return yield* port.fetch(request);

Source: packages/aws/src/ECS/CreateSandboxHttp.ts Kind: Layer · Provides: AWS.ECS.CreateSandbox

Runs AWS.ECS.CreateSandbox over the ECS API and each sandbox’s private address.

The host is granted ecs:RunTask on the Task’s definition, iam:PassRole on its roles, and stop, describe and list on the cluster’s tasks.

Sandboxes join the capacity provider’s task security group, which admits nothing by default. The binding creates a security group for the host and a rule that admits it into the sandboxes’ group, so the host reaches every port of a sandbox, and a sandbox reaches neither the host nor another sandbox. A Lambda Function host joins its group and the capacity’s subnets for you. An ECS Service or Task host does not: pass securityGroups that admit it.

export default class Api extends AWS.Lambda.Function<Api>()(
"Api",
{ main: import.meta.filename, functionUrl: true, timeout: Duration.minutes(5) },
Effect.gen(function* () {
const capacity = yield* Capacity;
const sandboxes = yield* AWS.ECS.CreateSandbox(capacity, MySandbox);
return {
fetch: Effect.gen(function* () {
const sandbox = yield* sandboxes.create({ idleTimeout: "15 minutes" });
const run = yield* sandbox.exec("uname -a");
return HttpServerResponse.text(run.stdout);
}).pipe(Effect.orDie),
};
}).pipe(Effect.provide(AWS.ECS.CreateSandboxHttp)),
) {}

Source: packages/aws/src/ECS/DescribeContainerInstances.ts

Runtime binding for ecs:DescribeContainerInstances.

Bind this operation to a Cluster inside a function runtime to get a callable that describes container instances registered to the bound cluster — remaining resources, running-task counts, agent status. The cluster ARN is injected automatically and the host is granted ecs:DescribeContainerInstances on the cluster’s container instances.

DescribeContainerInstances: Container Instances

Section titled “DescribeContainerInstances: Container Instances”
const describeContainerInstances =
yield* AWS.ECS.DescribeContainerInstances(cluster);
const response = yield* describeContainerInstances({
containerInstances: [containerInstanceArn],
});
const remaining = response.containerInstances?.[0]?.remainingResources;

Source: packages/aws/src/ECS/DescribeServiceDeployments.ts

Runtime binding for ecs:DescribeServiceDeployments.

Bind this operation to a Service inside a function runtime to get a callable that describes the bound service’s deployments — rollout state, circuit-breaker status, target service revision. The host is granted ecs:DescribeServiceDeployments on the service’s deployments (deployment ARNs are only known at runtime, e.g. from ListServiceDeployments).

DescribeServiceDeployments: Service Deployments

Section titled “DescribeServiceDeployments: Service Deployments”
const describeServiceDeployments =
yield* AWS.ECS.DescribeServiceDeployments(service);
const response = yield* describeServiceDeployments({
serviceDeploymentArns: [deploymentArn],
});
const status = response.serviceDeployments?.[0]?.status;

Source: packages/aws/src/ECS/DescribeServiceRevisions.ts

Runtime binding for ecs:DescribeServiceRevisions.

Bind this operation to a Service inside a function runtime to get a callable that describes the bound service’s revisions — the immutable task-definition + configuration snapshots that deployments roll between. The host is granted ecs:DescribeServiceRevisions on the service’s revisions (revision ARNs come from deployment describe/list responses).

DescribeServiceRevisions: Service Deployments

Section titled “DescribeServiceRevisions: Service Deployments”
const describeServiceRevisions =
yield* AWS.ECS.DescribeServiceRevisions(service);
const response = yield* describeServiceRevisions({
serviceRevisionArns: [revisionArn],
});
const taskDefinition = response.serviceRevisions?.[0]?.taskDefinition;

Source: packages/aws/src/ECS/DescribeServices.ts

Runtime binding for ecs:DescribeServices.

Bind this operation to a Cluster inside a function runtime to get a callable that describes services in the bound cluster. The cluster ARN is injected automatically and the host is granted ecs:DescribeServices on the cluster’s services.

const describeServices = yield* AWS.ECS.DescribeServices(cluster);
const response = yield* describeServices({ services: [serviceName] });
const runningCount = response.services?.[0]?.runningCount;

Source: packages/aws/src/ECS/DescribeTasks.ts

Runtime binding for ecs:DescribeTasks.

Bind this operation to a Cluster inside a function runtime to get a callable that describes tasks in the bound cluster. The cluster ARN is injected automatically and the host is granted ecs:DescribeTasks on the cluster’s tasks.

const describeTasks = yield* AWS.ECS.DescribeTasks(cluster);
const response = yield* describeTasks({ tasks: [taskArn] });
const status = response.tasks?.[0]?.lastStatus;
const exitCode = response.tasks?.[0]?.containers?.[0]?.exitCode;

Source: packages/aws/src/ECS/ExecuteCommand.ts

Runtime binding for ecs:ExecuteCommand (ECS Exec).

Bind this operation to a Cluster inside a function runtime to get a callable that starts a command against a running container in the bound cluster. The cluster ARN is injected automatically and the host is granted ecs:ExecuteCommand on the cluster and its tasks.

The target task must have been launched with enableExecuteCommand and the task role must allow the SSM messages channel. The response’s session.tokenValue is a Redacted bearer token for the SSM WebSocket stream (session.streamUrl).

const executeCommand = yield* AWS.ECS.ExecuteCommand(cluster);
const response = yield* executeCommand({
task: taskArn,
command: "ls -al /",
interactive: true,
});
const streamUrl = response.session?.streamUrl;

Source: packages/aws/src/ECS/GetTaskProtection.ts

Runtime binding for ecs:GetTaskProtection.

Bind this operation to a Cluster inside a function runtime to get a callable that reads the scale-in protection status of service-managed tasks in the bound cluster. The cluster ARN is injected automatically and the host is granted ecs:GetTaskProtection on the cluster’s tasks.

const getTaskProtection = yield* AWS.ECS.GetTaskProtection(cluster);
const response = yield* getTaskProtection({ tasks: [taskArn] });
const protected_ = response.protectedTasks?.[0]?.protectionEnabled;

Source: packages/aws/src/ECS/ListContainerInstances.ts

Runtime binding for ecs:ListContainerInstances.

Bind this operation to a Cluster inside a function runtime to get a callable that lists container-instance ARNs registered to the bound cluster (EC2/EXTERNAL launch types). The cluster ARN is injected automatically and the host is granted ecs:ListContainerInstances on the cluster.

ListContainerInstances: Container Instances

Section titled “ListContainerInstances: Container Instances”
const listContainerInstances = yield* AWS.ECS.ListContainerInstances(cluster);
const response = yield* listContainerInstances({ status: "ACTIVE" });
const instanceArns = response.containerInstanceArns ?? [];

Source: packages/aws/src/ECS/ListServiceDeployments.ts

Runtime binding for ecs:ListServiceDeployments.

Bind this operation to a Service inside a function runtime to get a callable that lists the bound service’s deployments (newest first). The service and cluster ARNs are injected automatically and the host is granted ecs:ListServiceDeployments on the service.

ListServiceDeployments: Service Deployments

Section titled “ListServiceDeployments: Service Deployments”
const listServiceDeployments = yield* AWS.ECS.ListServiceDeployments(service);
const response = yield* listServiceDeployments({
status: ["IN_PROGRESS"],
});
const deploymentArn = response.serviceDeployments?.[0]?.serviceDeploymentArn;

Source: packages/aws/src/ECS/ListServices.ts

Runtime binding for ecs:ListServices.

Bind this operation to a Cluster inside a function runtime to get a callable that lists service ARNs in the bound cluster. The cluster ARN is injected automatically and the grant is conditioned on the bound cluster.

const listServices = yield* AWS.ECS.ListServices(cluster);
const response = yield* listServices({ launchType: "FARGATE" });
const serviceArns = response.serviceArns ?? [];

Source: packages/aws/src/ECS/ListTasks.ts

Runtime binding for ecs:ListTasks.

Bind this operation to a Cluster inside a function runtime to get a callable that lists task ARNs in the bound cluster. The cluster ARN is injected automatically and the grant is conditioned on the bound cluster.

const listTasks = yield* AWS.ECS.ListTasks(cluster);
const response = yield* listTasks({
desiredStatus: "STOPPED",
});
const taskArns = response.taskArns ?? [];

Source: packages/aws/src/ECS/RunTask.ts

Runtime binding for ecs:RunTask.

Bind this operation to a Cluster and Task inside a function runtime to get a callable that starts a task from the bound task definition, on Fargate or on a capacity provider. The cluster and task definition are injected automatically; the host is granted ecs:RunTask on the task definition plus iam:PassRole on the task and execution roles. The rest of the request is ECS’s own RunTask request.

Launch a Fargate Task from a handler

const api = yield* AWS.Lambda.Function(
"Api",
{ main: import.meta.url, functionUrl: true },
Effect.gen(function* () {
// init: bind the launch (IAM grants happen here)
const runTask = yield* AWS.ECS.RunTask(cluster, task);
return {
fetch: Effect.gen(function* () {
// runtime: launch a task per request
const response = yield* runTask({
launchType: "FARGATE",
networkConfiguration: {
awsvpcConfiguration: {
subnets: [subnetId],
assignPublicIp: "ENABLED",
},
},
});
return yield* HttpServerResponse.json({
taskArn: response.tasks?.[0]?.taskArn,
});
}),
};
}),
);

Run an isolated Task on a capacity provider

A Task with isolation: "isolated" runs in its own Nitro Sandbox on a Managed Instances capacity provider. Name the provider and the subnets; the task joins the VPC’s default security group unless you pass securityGroups.

const capacity = yield* Capacity;
const runTask = yield* AWS.ECS.RunTask(Cluster, MyJob);
const CapacityName = yield* capacity.name;
const Subnets = yield* capacity.subnets;
return {
fetch: Effect.gen(function* () {
const { tasks } = yield* runTask({
capacityProviderStrategy: [{ capacityProvider: yield* CapacityName, weight: 1 }],
networkConfiguration: { awsvpcConfiguration: { subnets: yield* Subnets } },
});
return HttpServerResponse.text(tasks?.[0]?.taskArn ?? "no task started");
}).pipe(Effect.orDie),
};

Source: packages/aws/src/ECS/Schedule.ts

Creates a scheduled EventBridge rule that runs an ECS Fargate task.

every is the high-level ECS scheduling helper for phase 1. It provisions the EventBridge rule plus the invoke role required to call ecs:RunTask and iam:PassRole for the target task’s execution roles.

Plain English durations like "1 hour" are normalized to rate(...) expressions automatically. Full rate(...) and cron(...) expressions are also accepted as-is.

Run a task every hour

yield* AWS.ECS.every("HourlyJob", "1 hour", {
cluster,
task: jobTask,
subnets: [privateSubnet1.subnetId, privateSubnet2.subnetId],
securityGroups: [jobSecurityGroup.groupId],
});

Use an explicit cron expression

yield* AWS.ECS.every("NightlyJob", "cron(0 3 * * ? *)", {
cluster,
task: nightlyTask,
subnets: [privateSubnet1.subnetId, privateSubnet2.subnetId],
securityGroups: [jobSecurityGroup.groupId],
});

Run multiple copies with static input

yield* AWS.ECS.every("BatchJob", "30 minutes", {
cluster,
task: batchTask,
subnets: [privateSubnet1.subnetId, privateSubnet2.subnetId],
securityGroups: [jobSecurityGroup.groupId],
taskCount: 3,
input: JSON.stringify({ source: "scheduler" }),
});

Source: packages/aws/src/ECS/Service.ts

An ECS service: N copies of a container kept alive, optionally behind a load balancer.

The service’s image comes from one of four sources:

  • image — run a pre-built registry image, mirrored into ECR.
  • context — build your own Dockerfile.
  • main — bundle an inline Effect program (servers return { fetch }).
  • task: — deploy an existing AWS.ECS.Task’s definition; the Service adds desiredCount / load balancing / deployment configuration.

With any of the first three the Service synthesizes its own task definition (task + execution roles, log group, ECR repository). loadBalancer: true wires a public ALB + target group + listener and populates the url attribute. When vpcId/subnets are omitted the account’s default VPC (and its per-AZ subnets) is used.

Most configuration is updated in place via updateService (desiredCount, task definition, network, deployment config, placement, exec, load balancers, tags). Only truly-immutable aspects — serviceName, cluster, launchType↔capacityProviderStrategy switch, deploymentController type, schedulingStrategy, enableECSManagedTags, role — replace the service.

Remote Image Behind a Load Balancer

const nginx = yield* Service("Edge", {
cluster,
image: "public.ecr.aws/nginx/nginx:1.27",
port: 80,
desiredCount: 2,
loadBalancer: true, // ALB + target group + listener wiring
});
nginx.url; // http://<alb-dns-name>

Run an Existing Task’s Definition

const api = yield* Service("Api", {
cluster,
task: apiTask, // shared image/roles/config; Service adds
desiredCount: 2, // desiredCount / LB / deployment config
loadBalancer: true,
});

Inline Effect Server

const api = yield* Service(
"Api",
{ cluster, main: import.meta.url, port: 3000, desiredCount: 2, cpu: 256, memory: 512 },
Effect.gen(function* () {
const putItem = yield* AWS.DynamoDB.PutItem(table);
return {
fetch: Effect.gen(function* () {
return yield* HttpServerResponse.json({ ok: true });
}),
};
}).pipe(Effect.provide(AWS.DynamoDB.PutItemHttp)),
);

Builds reuse the local BuildKit cache of the machine they run on, and nothing but the image is pushed. A builder that has never built the image, such as a fresh CI runner, reruns every step. Set build.cache: true to keep every stage’s layers at the image repository’s :buildcache tag, so fresh builders skip unchanged steps. For another backend, pass BuildKit’s own --cache-from / --cache-to values as from and to.

Cache layers in the image repository

const api = yield* AWS.ECS.Service("Api", {
cluster,
context: "./api",
port: 8080,
build: { cache: true },
});

Cache layers in GitHub Actions

const api = yield* AWS.ECS.Service("Api", {
cluster,
context: "./api",
port: 8080,
build: {
cache: {
from: ["type=gha,scope=api"],
to: ["type=gha,scope=api,mode=max"],
},
},
});

main is bundled with rolldown at deploy time. Unused code is tree-shaken. effect, alchemy, and @distilled.cloud are marked pure so unused parts prune more aggressively. Your app is not marked pure.

Mark additional packages as pure

Only list packages with no top-level side effects.

{
main: import.meta.url,
build: {
pure: { packages: ["my-lib", "@my-scope/*"] },
},
}

Turn it off

{
main: import.meta.url,
build: { pure: false },
}

Two Services Sharing One Listener

// The ALB + listener are stack-level resources owned by neither service.
const lb = yield* AWS.ELBv2.LoadBalancer("Alb", {
subnets: [subnetA.subnetId, subnetB.subnetId],
securityGroups: [sg.groupId],
});
const listener = yield* AWS.ELBv2.Listener("Http", {
loadBalancerArn: lb.loadBalancerArn,
port: 80,
defaultActions: [
{ type: "fixedResponse", statusCode: "404", messageBody: "no route" },
],
});
// Each service composes only its own TargetGroup + ListenerRule on the
// shared listener. Destroying one service removes its rule + target
// group; the ALB, listener, and the other service are untouched.
const api = yield* Service("Api", {
cluster,
image: "my-org/api:latest",
port: 3000,
loadBalancer: { listener, rules: [{ path: "/api/*" }] },
});
const web = yield* Service("Web", {
cluster,
image: "my-org/web:latest",
port: 8080,
loadBalancer: { listener, rules: [{ path: "/*" }] },
});

Catch-All on a Shared Listener

// A bare listener reference adds a single `path: "/*"` rule.
const svc = yield* Service("Svc", {
cluster,
image: "my-org/web:latest",
port: 8080,
loadBalancer: listener,
});

Owned ALB with Routing Rules and an HTTP → HTTPS Redirect

// `"80/http"`-style `listen` strings mean the service OWNS the ALB and
// these listeners (mixing them with shared listener references is a
// typed error).
const svc = yield* Service("Svc", {
cluster,
image: "my-org/web:latest",
port: 8080,
certificateArn,
loadBalancer: {
rules: [
{ listen: "80/http", redirect: "443/https" },
{ listen: "443/https", forward: "8080/http" },
],
},
});

Domain with a Composed Certificate

// Looks up the matching Route 53 hosted zone, composes a DNS-validated
// ACM certificate in the service's region, wires it to the HTTPS
// listener, and creates alias A/AAAA records. `url` becomes
// https://api.example.com.
const svc = yield* Service("Api", {
cluster,
image: "my-org/api:latest",
port: 3000,
loadBalancer: { domain: "api.example.com" },
});

Domain with an Existing Certificate

const svc = yield* Service("Api", {
cluster,
image: "my-org/api:latest",
port: 3000,
loadBalancer: {
domain: { name: "api.example.com", aliases: ["www.api.example.com"], cert: certificateArn },
},
});

Domain on Cloudflare DNS

// The certificate is validated through the Cloudflare zone and each
// name gets a CNAME to the load balancer. Requires
// `Cloudflare.providers()` in the stack.
const svc = yield* Service("Api", {
cluster,
image: "my-org/api:latest",
port: 3000,
loadBalancer: {
domain: { name: "api.example.com", dns: Cloudflare.DNS.Adapter() },
},
});
// tcp/udp/tls/tcp_udp listen protocols compose a Network Load Balancer;
// each rule's action becomes its listener's default forward (NLB
// listeners route by port alone).
const svc = yield* Service("Tcp", {
cluster,
image: "my-org/tcp-echo:latest",
port: 9000,
loadBalancer: { rules: [{ listen: "80/tcp" }] },
});

Per-Target-Group Health Overrides

const svc = yield* Service("Api", {
cluster,
image: "my-org/api:latest",
port: 3000,
loadBalancer: {
rules: [{ listen: "80/http" }],
health: {
"3000/http": {
path: "/healthz",
interval: "15 seconds",
healthyThreshold: 3,
successCodes: "200-299",
},
},
},
});

Container Health Check

const svc = yield* Service("Api", {
cluster,
image: "my-org/api:latest",
port: 3000,
healthCheck: {
command: ["CMD-SHELL", "curl -f http://localhost:3000/ || exit 1"],
interval: "30 seconds",
retries: 3,
},
});
// Composes a ScalableTarget (min/max) plus one target-tracking policy
// per metric. Redeploys stop pinning desiredCount while scaling is set.
const svc = yield* Service("Api", {
cluster,
image: "my-org/api:latest",
port: 3000,
loadBalancer: true,
scaling: {
min: 1,
max: 4,
cpuUtilization: 70,
requestCount: 200,
scaleInCooldown: "5 minutes",
},
});
// Values are ARNs; the container gets them as env vars via `valueFrom`
// and the execution role is granted read on exactly these ARNs.
const svc = yield* Service("Api", {
cluster,
image: "my-org/api:latest",
port: 3000,
secrets: {
DB_PASSWORD: dbPasswordSecret.secretArn,
API_KEY: apiKeyParameter.parameterArn,
},
logging: { retention: "2 weeks" },
});
const namespace = yield* AWS.CloudMap.PrivateDnsNamespace("AppNs", {
name: "internal.example.com",
vpc: vpc.vpcId,
});
const svc = yield* Service("Api", {
cluster,
image: "my-org/api:latest",
port: 3000,
serviceRegistry: { namespace },
});
const svc = yield* Service("Api", {
cluster,
image: "my-org/api:latest",
port: 3000,
volumes: [{ efs: fileSystem, path: "/mnt/data" }],
});
// The cluster must have the Fargate capacity providers associated:
// Cluster("C", { capacityProviders: ["FARGATE", "FARGATE_SPOT"] }).
const svc = yield* Service("Worker", {
cluster,
image: "my-org/worker:latest",
capacity: { fargate: { weight: 1, base: 1 }, spot: { weight: 4 } },
});
const service = yield* Service("ApiService", {
cluster,
task: apiTask,
vpcId: vpc.vpcId,
subnets: [subnet1.subnetId, subnet2.subnetId],
loadBalancers: [
{
targetGroupArn,
containerName: apiTask.containerName,
containerPort: apiTask.port,
},
],
});
const service = yield* Service("WorkerService", {
cluster,
task: workerTask,
vpcId: vpc.vpcId,
subnets: [subnet.subnetId],
capacityProviderStrategy: [
{ capacityProvider: "FARGATE_SPOT", weight: 4 },
{ capacityProvider: "FARGATE", weight: 1, base: 1 },
],
placementStrategy: [{ type: "spread", field: "attribute:ecs.availability-zone" }],
});
const service = yield* Service("ApiService", {
cluster,
task: apiTask,
vpcId: vpc.vpcId,
subnets: [subnet1.subnetId, subnet2.subnetId],
desiredCount: 3,
enableExecuteCommand: true,
deploymentConfiguration: {
minimumHealthyPercent: 100,
maximumPercent: 200,
deploymentCircuitBreaker: { enable: true, rollback: true },
},
healthCheckGracePeriod: "30 seconds",
});

Service.lookup references a service Alchemy doesn’t manage (created in the console or by another stack), found by cluster and serviceName. It is read during plan/deploy and never created, updated or deleted.

const web = AWS.ECS.Service.lookup({ cluster: "shared", serviceName: "web" });
const serviceArn = web.serviceArn;

Source: packages/aws/src/ECS/StartTask.ts

Runtime binding for ecs:StartTask.

Bind this operation to a Cluster and Task inside a function runtime to get a callable that places the bound task definition on specific container instances (EC2/EXTERNAL launch types — unlike RunTask, which lets ECS pick placement). The cluster and task definition ARNs are injected automatically; the host is granted ecs:StartTask on the task definition plus iam:PassRole on the task and execution roles.

const controller = yield* AWS.Lambda.Function(
"PlacementController",
{ main: import.meta.url },
Effect.gen(function* () {
// init: bind the launch (IAM grants happen here)
const startTask = yield* AWS.ECS.StartTask(cluster, task);
return {
fetch: Effect.gen(function* () {
// runtime: place the task on a chosen instance
const response = yield* startTask({
containerInstances: [containerInstanceArn],
startedBy: "placement-controller",
});
return yield* HttpServerResponse.json({
taskArn: response.tasks?.[0]?.taskArn,
});
}),
};
}),
);

Source: packages/aws/src/ECS/StopServiceDeployment.ts

Runtime binding for ecs:StopServiceDeployment.

Bind this operation to a Service inside a function runtime to get a callable that stops an in-progress deployment of the bound service — either abandoning it or rolling back to the last completed revision. The host is granted ecs:StopServiceDeployment on the service’s deployments.

StopServiceDeployment: Service Deployments

Section titled “StopServiceDeployment: Service Deployments”
const stopServiceDeployment = yield* AWS.ECS.StopServiceDeployment(service);
yield* stopServiceDeployment({
serviceDeploymentArn: deploymentArn,
stopType: "ROLLBACK",
});

Source: packages/aws/src/ECS/StopTask.ts

Runtime binding for ecs:StopTask.

Bind this operation to a Cluster inside a function runtime to get a callable that stops a running task in the bound cluster. The cluster ARN is injected automatically and the host is granted ecs:StopTask on the cluster’s tasks.

const stopTask = yield* AWS.ECS.StopTask(cluster);
const response = yield* stopTask({
task: taskArn,
reason: "drained by worker",
});

Source: packages/aws/src/ECS/Task.ts

A Fargate task definition with a container image from one of three sources, declared flat on the props:

  • main — bundle an inline Effect program into a generated image (compose with image or an inline dockerfile to pick the environment; defaults to oven/bun:1).
  • context — build your own Dockerfile (dockerfile is a path relative to the cwd, defaulting to ${context}/Dockerfile).
  • image — run a pre-built registry image, mirrored into ECR.

Task provisions task + execution IAM roles, a CloudWatch log group, and an ECR repository holding the built (or mirrored) image, then registers a Fargate task definition. Each reconcile registers a new immutable revision. A launched task runs until its process exits — it is the target of AWS.ECS.RunTask / StopTask bindings and AWS.ECS.Schedule; effectful impls return { run }, executed to completion when the container starts.

Beyond the primary container you can declare task-level configuration (volumes, runtime platform, ephemeral storage, IPC/PID mode, placement constraints) and append additional sidecars for multi-container tasks.

Remote Image

const migrate = yield* Task("DbMigrate", {
image: "public.ecr.aws/docker/library/busybox:stable",
command: ["sh", "-c", "echo done"],
cpu: 256,
memory: 512,
});

Build Your Own Dockerfile

const render = yield* Task("RenderJob", {
context: "./render", // dockerfile defaults to ./render/Dockerfile
dockerfile: "./render/Dockerfile.gpu", // always a PATH
cpu: 1024,
memory: 4096,
});

Build args and secrets

// Dockerfile:
// ARG NODE_ENV
// RUN --mount=type=secret,id=NPM_TOKEN,env=NPM_TOKEN npm ci
const api = yield* Task("Api", {
context: "./api",
build: {
args: { NODE_ENV: "production" },
// Mounted only into the RUN step that asks for it; never in the image.
secrets: { NPM_TOKEN: Config.Redacted("NPM_TOKEN") },
},
cpu: 256,
memory: 512,
});

Inline Effect Program

const drainer = yield* Task(
"QueueDrainer",
{ main: import.meta.url, image: "oven/bun:1", cpu: 256, memory: 512 },
Effect.gen(function* () {
const receive = yield* AWS.SQS.ReceiveMessage(queue);
return {
run: Effect.gen(function* () {
// runs to completion, then the container exits
const batch = yield* receive({ MaxNumberOfMessages: 10 });
}),
};
}),
);
const task = yield* Task("ApiTask", {
main: import.meta.url,
port: 3000,
sidecars: [
{
name: "otel-collector",
image: "public.ecr.aws/aws-observability/aws-otel-collector:latest",
essential: false,
portMappings: [{ containerPort: 4317, protocol: "tcp" }],
},
],
});

Builds reuse the local BuildKit cache of the machine they run on, and nothing but the image is pushed. A builder that has never built the image, such as a fresh CI runner, reruns every step. Set build.cache: true to keep every stage’s layers at the image repository’s :buildcache tag, so fresh builders skip unchanged steps. For another backend, pass BuildKit’s own --cache-from / --cache-to values as from and to.

Cache layers in the image repository

const worker = yield* AWS.ECS.Task("Worker", {
context: "./worker",
build: { cache: true },
});

Cache layers in GitHub Actions

const worker = yield* AWS.ECS.Task("Worker", {
context: "./worker",
build: {
cache: {
from: ["type=gha,scope=worker"],
to: ["type=gha,scope=worker,mode=max"],
},
},
});

main is bundled with rolldown at deploy time. Unused code is tree-shaken. effect, alchemy, and @distilled.cloud are marked pure so unused parts prune more aggressively. Your app is not marked pure.

Mark additional packages as pure

Only list packages with no top-level side effects.

{
main: import.meta.url,
build: {
pure: { packages: ["my-lib", "@my-scope/*"] },
},
}

Turn it off

{
main: import.meta.url,
build: { pure: false },
}

ARM64 with EFS Volume and Ephemeral Storage

const task = yield* Task("WorkerTask", {
main: import.meta.url,
runtimePlatform: { cpuArchitecture: "ARM64", operatingSystemFamily: "LINUX" },
ephemeralStorage: { sizeInGiB: 40 },
volumes: [
{
name: "data",
efsVolumeConfiguration: { fileSystemId: fileSystem.fileSystemId },
},
],
container: {
mountPoints: [{ sourceVolume: "data", containerPath: "/data" }],
},
});

Environment Files from S3

const task = yield* Task("ApiTask", {
main: import.meta.url,
environmentFiles: [
{ value: "arn:aws:s3:::my-config-bucket/app.env", type: "s3" },
],
});

isolation: "isolated" runs every task in its own Nitro Sandbox: a VM the Nitro hypervisor isolates from the instance and from every other task. Use it for code you do not trust. The task needs a Managed Instances capacity provider with nitroEnclavesEnabled, and does not run on Fargate. A sandbox has 20 GiB of storage.

Isolation alone adds nothing to the task: its task definition holds the container you declare. Run it as an AWS.ECS.Service or start it with AWS.ECS.RunTask. AWS.ECS.CreateSandbox is the layer on top that drives a task through a handle.

An image that runs in a Nitro Sandbox

const job = yield* AWS.ECS.Task("MyJob", {
image: "python:3.12-slim",
command: ["python3", "-c", "print('hello from a sandbox')"],
cpu: 1024,
memory: 2048,
isolation: "isolated",
});

A Task that runs in a Nitro Sandbox

const sandbox = yield* AWS.ECS.Task("MySandbox", {
main: import.meta.url,
port: 3000,
cpu: 1024,
memory: 2048,
isolation: "isolated",
});

A sandbox class with typed methods

AWS.ECS.CreateSandbox(capacity, MySandbox) starts one per call and hands back a handle with exec, files and the methods below.

export default class MySandbox extends AWS.ECS.Task<
MySandbox,
{ hello: (name: string) => Effect.Effect<string> }
>()(
"MySandbox",
{ main: import.meta.url, port: 3000, cpu: 1024, memory: 2048, isolation: "isolated" },
Effect.gen(function* () {
return {
fetch: Effect.succeed(HttpServerResponse.text("ok")),
hello: Effect.fn(function* (name: string) {
return `hello ${name}`;
}),
};
}),
) {}

Source: packages/aws/src/ECS/TaskDefinition.ts

A standalone ECS task definition for bring-your-own-container workloads.

Unlike the Effect-native AWS.ECS.Task (which bundles an inline program and builds/pushes a Docker image), TaskDefinition registers user-supplied containerDefinitions — any image URI from ECR, public.ecr.aws, or an external registry — with full control over Fargate/EC2 compatibility, volumes, runtime platform, and IAM roles.

Task definitions are immutable revisions under a family:

  • reconcile registers a new revision only when the definition content changed (compared against the observed latest ACTIVE revision), so a no-op redeploy keeps the same revision;
  • changing the family replaces the resource;
  • destroy deregisters and hard-deletes every revision of the family. ECS may retain referenced revisions in DELETE_IN_PROGRESS until their tasks and services terminate; that is a successful terminal state.

Layering — why TaskDefinition is deliberately not a Platform. ECS splits “what runs” from “how it runs”: a task definition is the immutable container spec, while Task (runs to completion) and Service (long-running) are the execution vehicles. The effectful Platform abstraction requires Alchemy to own the container image and entrypoint so it can bundle the inline Effect program — that is exactly what AWS.ECS.Task does (bundle → Docker build/push → register definition → serve the program). Making TaskDefinition also a Platform would duplicate Task while contradicting this resource’s purpose: user-supplied images whose entrypoint Alchemy must not rewrite. So the effectful path is AWS.ECS.Task; the bring-your-own-container path is TaskDefinition. Both surface taskDefinitionArn / containerName / port, so either plugs into AWS.ECS.Service’s task prop unchanged.

TaskDefinition: Creating a Task Definition

Section titled “TaskDefinition: Creating a Task Definition”

Public Image on Fargate

const taskDef = yield* TaskDefinition("Nginx", {
containerDefinitions: [
{
name: "nginx",
image: "public.ecr.aws/nginx/nginx:stable",
essential: true,
portMappings: [{ containerPort: 80, protocol: "tcp" }],
},
],
});

With IAM Roles and CloudWatch Logs

const taskDef = yield* TaskDefinition("Api", {
cpu: 512,
memory: 1024,
taskRoleArn: taskRole, // AWS.IAM.Role resource or raw ARN
executionRoleArn: executionRole, // needed for awslogs / private images
awslogs: true, // creates /ecs/{family} and injects awslogs config
containerDefinitions: [
{
name: "api",
image: image.imageUri,
essential: true,
portMappings: [{ containerPort: 8080 }],
environment: [{ name: "STAGE", value: "prod" }],
},
],
});
const service = yield* Service("ApiService", {
cluster,
task: taskDef, // exposes taskDefinitionArn / containerName / port
vpcId: vpc.vpcId,
subnets: [subnet.subnetId],
assignPublicIp: true,
});
const taskDef = yield* TaskDefinition("Agent", {
requiresCompatibilities: ["EC2"],
networkMode: "bridge",
volumes: [{ name: "docker-sock", host: { sourcePath: "/var/run/docker.sock" } }],
containerDefinitions: [
{
name: "agent",
image: "public.ecr.aws/docker/library/busybox:stable",
memory: 128,
essential: true,
mountPoints: [{ sourceVolume: "docker-sock", containerPath: "/var/run/docker.sock" }],
},
],
});

TaskDefinition: Looking up an existing task definition

Section titled “TaskDefinition: Looking up an existing task definition”

TaskDefinition.lookup references a task definition Alchemy doesn’t manage (created in the console or by another stack), found by family. It is read during plan/deploy and never created, updated or deleted.

const migrate = AWS.ECS.TaskDefinition.lookup({ family: "migrate" });
const taskDefinitionArn = migrate.taskDefinitionArn;

Source: packages/aws/src/ECS/UpdateContainerInstancesState.ts

Runtime binding for ecs:UpdateContainerInstancesState.

Bind this operation to a Cluster inside a function runtime to get a callable that transitions container instances between ACTIVE and DRAINING — the canonical building block of an Auto Scaling lifecycle-hook drain function that gracefully migrates tasks off an instance before it terminates. The cluster ARN is injected automatically and the host is granted ecs:UpdateContainerInstancesState on the cluster’s container instances.

UpdateContainerInstancesState: Container Instances

Section titled “UpdateContainerInstancesState: Container Instances”
const updateContainerInstancesState =
yield* AWS.ECS.UpdateContainerInstancesState(cluster);
yield* updateContainerInstancesState({
containerInstances: [containerInstanceArn],
status: "DRAINING",
});

Source: packages/aws/src/ECS/UpdateTaskProtection.ts

Runtime binding for ecs:UpdateTaskProtection.

Bind this operation to a Cluster inside a function runtime to get a callable that toggles scale-in protection on service-managed tasks in the bound cluster — the canonical pattern is a task protecting itself while it processes long-running work so deployments and scale-in don’t terminate it. The cluster ARN is injected automatically and the host is granted ecs:UpdateTaskProtection on the cluster’s tasks.

const updateTaskProtection = yield* AWS.ECS.UpdateTaskProtection(cluster);
yield* updateTaskProtection({
tasks: [taskArn],
protectionEnabled: true,
expiresIn: "30 minutes",
});