Deploy with SST
Deploy the tutorial app with SST, then save its outputs for the Runlane CLI.
Finish Prepare the app first. This page adds SST to that app. It creates a Postgres database, three SQS queues, two Lambda functions, a maintenance timer, and one container worker.
The shared maintenance entry point uses runlane.createMaintenanceHandler() and starts lazily. Export the handler directly; it ignores event and context arguments.
Before you start
Use Node.js 24, npm, the AWS CLI, and Docker with its daemon running. Run commands from the app root. This page pins sst@4.17.2, the Pulumi-based SST line. It does not use SST v2's CDK constructs.
Choose a region and load AWS deploy credentials. The deploy identity needs access to create these resources.
export AWS_REGION=us-east-1
aws sts get-caller-identity
docker infoCheck that the identity is in your test account. Keep using this region and the named tutorial stage throughout the page. The queue names are fixed, so use only one copy of this tutorial per account and region.
This setup exposes database port 5432 to the internet. It uses a generated password and verified TLS. Use test data, then remove it or follow Prepare for production.
Add SST to the app
Install the CLI and initialize SST:
npm install --save-dev --save-exact sst@4.17.2
npm exec -- sst init --yesChoose aws when prompted. Keep package.json, package-lock.json, and the root sst.config.ts. Keep sst-env.d.ts if SST generates it later. Keep your existing app tsconfig.json; use the separate config below for infrastructure checks.
Add these lines to your ignore files. .sst contains generated platform code, state, and local outputs.
node_modules/
dist/
.sst/
.env*.sstKeep the existing .dockerignore entries from Prepare the app. Adding .sst keeps deploy state out of Docker's build context.
{
"compilerOptions": {
"target": "ES2024",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"types": ["node"]
},
"include": ["sst.config.ts"]
}This checks the root config against SST's generated platform types after sst install.
Define the infrastructure
Replace sst.config.ts with the following blocks, in order. Each block continues the same file. The last block closes it.
Stage and network
A virtual private cloud (VPC) is your AWS network. A subnet is an address range within it. Here, each subnet has a route to the internet through an internet gateway. A security group holds network access rules.
/// <reference path="./.sst/platform/config.d.ts" />
export default $config({
app(input) {
return {
name: 'runlane-tutorial',
home: 'aws',
removal: input.stage === 'tutorial' ? 'remove' : 'retain-all',
protect: input.stage !== 'tutorial',
providers: {
aws: { version: '7.52.1' },
random: '4.21.4',
command: { package: '@pulumi/command', version: '1.2.1' },
'docker-build': '0.0.22',
},
}
},
async run() {
const region = aws.getRegionOutput().region
const zones = await aws.getAvailabilityZones({
state: 'available',
filters: [{ name: 'zone-type', values: ['availability-zone'] }],
})
const vpc = new aws.ec2.Vpc('Vpc', {
cidrBlock: '10.0.0.0/16',
enableDnsHostnames: true,
enableDnsSupport: true,
})
const gateway = new aws.ec2.InternetGateway('Gateway', { vpcId: vpc.id })
const routes = new aws.ec2.RouteTable('PublicRoutes', {
vpcId: vpc.id,
routes: [{ cidrBlock: '0.0.0.0/0', gatewayId: gateway.id }],
})
const subnets = [0, 1].map((index) => {
const subnet = new aws.ec2.Subnet(`PublicSubnet${index}`, {
vpcId: vpc.id,
availabilityZone: zones.names[index],
cidrBlock: `10.0.${index}.0/24`,
mapPublicIpOnLaunch: true,
})
new aws.ec2.RouteTableAssociation(`PublicRoute${index}`, {
subnetId: subnet.id,
routeTableId: routes.id,
})
return subnet.id
})
const workerNetwork = new aws.ec2.SecurityGroup('WorkerNetwork', {
vpcId: vpc.id,
ingress: [],
egress: [{ protocol: '-1', fromPort: 0, toPort: 0, cidrBlocks: ['0.0.0.0/0'] }],
})
const databaseNetwork = new aws.ec2.SecurityGroup('DatabaseNetwork', {
vpcId: vpc.id,
ingress: [{ protocol: 'tcp', fromPort: 5432, toPort: 5432, cidrBlocks: ['0.0.0.0/0'] }],
})This uses Pulumi's network resources within SST. It creates only two public subnets in separate Availability Zones. Each zone is a separate location within the region. SST's Vpc component also creates private subnets, which this tutorial does not need. There is no NAT gateway, which would give private resources outbound internet access.
Lambda runs outside this VPC and has no fixed source IP. That is why the database allows public connections here. A private database needs an in-VPC path for Lambda, migrations, and CLI checks. It also needs NAT or service endpoints for outbound AWS calls. The production checklist covers that path.
Database
const password = new random.RandomPassword('DatabasePassword', {
length: 32,
special: false,
})
const databaseSubnets = new aws.rds.SubnetGroup('DatabaseSubnets', {
subnetIds: subnets,
})
const database = new aws.rds.Instance('Database', {
identifier: 'runlane-tutorial',
engine: 'postgres',
engineVersion: '17',
instanceClass: 'db.t4g.micro',
allocatedStorage: 20,
storageType: 'gp3',
dbName: 'runlane',
username: 'runlane',
password: password.result,
dbSubnetGroupName: databaseSubnets.name,
vpcSecurityGroupIds: [databaseNetwork.id],
publiclyAccessible: true,
deletionProtection: false,
skipFinalSnapshot: true,
backupRetentionPeriod: 0,
deleteAutomatedBackups: true,
})
const databaseUrl = $util.secret(
$interpolate`postgresql://${database.username}:${password.result}@${database.address}:${database.port}/${database.dbName}?sslmode=verify-full`,
)RDS settings select PostgreSQL 17 with 20 GB of gp3 storage. The generated password has 32 letters and digits. The URL verifies the server's certificate and hostname. Backups and the final snapshot are off for teardown; use test data only.
Queues and shared environment
A dead-letter queue (DLQ) holds messages after repeated delivery failures.
const deadLetter = new sst.aws.Queue('DeadLetter', {
transform: {
queue: { name: 'runlane-tutorial-dead-letter', messageRetentionSeconds: 1209600 },
},
})
const defaultQueue = new sst.aws.Queue('DefaultQueue', {
visibilityTimeout: '6 minutes',
dlq: { queue: deadLetter.arn, retry: 5 },
transform: { queue: { name: 'runlane-tutorial-default' } },
})
const longRunningQueue = new sst.aws.Queue('LongRunningQueue', {
visibilityTimeout: '6 minutes',
dlq: { queue: deadLetter.arn, retry: 5 },
transform: { queue: { name: 'runlane-tutorial-long-running' } },
})
const sendPermission = {
actions: ['sqs:SendMessage'],
resources: [defaultQueue.arn, longRunningQueue.arn],
}
const environment = {
DATABASE_URL: databaseUrl,
RUNLANE_ENVIRONMENT: 'tutorial',
RUNLANE_DEFAULT_QUEUE_URL: defaultQueue.url,
RUNLANE_LONG_RUNNING_QUEUE_URL: longRunningQueue.url,
}
const lambdaSettings = {
runtime: 'nodejs24.x',
architecture: 'x86_64',
memory: '512 MB',
logging: { retention: '1 week' },
} satisfies Pick<sst.aws.FunctionArgs, 'runtime' | 'architecture' | 'memory' | 'logging'>
const lambdaCa = '/var/task/certificates/rds-global-bundle.pem'
const lambdaRole = { managedPolicyArns: [], inlinePolicies: undefined }Both work queues send messages to the DLQ after five failed receives. The DLQ keeps messages for 14 days. Six minutes of visibility gives delivery Lambda six times its one-minute timeout. Queue URLs go through env values. The role policies below grant only the listed SQS actions.
Migrations before workloads
const migrations = new command.local.Command(
'DatabaseMigrations',
{
create: 'npm exec -- runlane adapter postgres migrate',
update: 'npm exec -- runlane adapter postgres migrate',
dir: process.cwd(),
environment: {
...environment,
AWS_REGION: region,
NODE_EXTRA_CA_CERTS: `${process.cwd()}/certificates/rds-global-bundle.pem`,
},
triggers: [Date.now().toString()],
},
{ dependsOn: [database, defaultQueue, longRunningQueue] },
)
const afterMigrations = (_args: object, options: $util.CustomResourceOptions): undefined => {
options.dependsOn = [migrations]
}The local command runs on the deploying machine, from the app root. It uses the installed CLI and app config. The timestamp changes on each deploy, so it runs every time. Its environment includes both queue URLs and an absolute CA path set before Node starts.
The tutorial database is public, so this machine can reach it. Production needs a release step with private database access.
A non-zero exit code fails the command resource. This fails the deploy and blocks dependent workload changes. Existing workloads can still run during an update. Use compatible schema changes.
The transform callback adds the migration dependency to the actual workload resources inside SST components. An IAM role is an AWS identity whose policies grant permissions. Delivery and maintenance keep their own roles.
Delivery Lambda and its queue connection
An event source mapping polls SQS and calls Lambda with message batches.
const delivery = new sst.aws.Function('Delivery', {
...lambdaSettings,
bundle: 'dist/lambda',
handler: 'delivery.handler',
timeout: '1 minute',
environment: { ...environment, NODE_EXTRA_CA_CERTS: lambdaCa },
transform: { function: afterMigrations, role: lambdaRole },
})SST's Function API supports nodejs24.x. Its bundle option uploads a prebuilt directory without rebundling it. The asset includes the RDS CA bundle.
The mapping enables partial batch responses and caps concurrent calls at two. The role includes the receive, delete, and queue-attribute actions that Lambda's SQS poller needs. It can also send outbox messages to either work queue.
This uses an explicit mapping because SST's queue subscriber adds extra SQS actions. No reserved concurrency is set; some new accounts lack the quota to reserve it. The function and mapping both depend on migrations.
Maintenance timer
EventBridge Scheduler is AWS's timer service.
const maintenance = new sst.aws.Function('Maintenance', {
...lambdaSettings,
bundle: 'dist/lambda',
handler: 'maintenance.handler',
timeout: '2 minutes',
environment: { ...environment, NODE_EXTRA_CA_CERTS: lambdaCa },
transform: { function: afterMigrations, role: lambdaRole },
})
const lambdaPolicies = [
{
name: 'Delivery',
fn: delivery,
permissions: [
sendPermission,
{
actions: ['sqs:ReceiveMessage', 'sqs:DeleteMessage', 'sqs:GetQueueAttributes'],
resources: [defaultQueue.arn],
},
],
},
{ name: 'Maintenance', fn: maintenance, permissions: [sendPermission] },
].map(
({ name, fn, permissions }) =>
new aws.iam.RolePolicy(`${name}Policy`, {
role: fn.nodes.role.name,
policy: fn.nodes.logGroup.apply((group) => {
if (!group) throw new Error('Lambda logging must be enabled')
return aws.iam.getPolicyDocumentOutput({
statements: [
...permissions,
{
actions: ['logs:CreateLogStream', 'logs:PutLogEvents'],
resources: [$interpolate`${group.arn}:*`],
},
],
}).json
}),
}),
)
new aws.lambda.EventSourceMapping(
'DeliveryQueue',
{
eventSourceArn: defaultQueue.arn,
functionName: delivery.arn,
batchSize: 10,
maximumBatchingWindowInSeconds: 0,
functionResponseTypes: ['ReportBatchItemFailures'],
scalingConfig: { maximumConcurrency: 2 },
},
{ dependsOn: [migrations, delivery, ...lambdaPolicies] },
)
new sst.aws.CronV2('MaintenanceTimer', {
schedule: 'rate(1 minute)',
function: maintenance.arn,
transform: {
schedule(_args, options) {
options.dependsOn = [migrations, ...lambdaPolicies]
},
},
})CronV2 uses Scheduler to call maintenance every minute. SST creates a separate role with lambda:InvokeFunction on only maintenance. The function can publish to both work queues and write to only its own log group. Both the function and schedule wait for migrations.
The role transform removes SST's default policies. Each inline role policy then owns that function's SQS and log grants. Leaving inlinePolicies unset lets these resources own the policies without drift. The mapping and timer wait for the policies too.
Container image and worker
An image holds the files the worker needs to run. Store it in Amazon Elastic Container Registry (ECR) on AWS. Fargate runs containers without servers for you to manage. Use Amazon Elastic Container Service (ECS) to manage this app's worker and keep it running. A task definition describes its image, resources, roles, and env values.
const repository = new aws.ecr.Repository('WorkerRepository', {
name: 'runlane-tutorial-worker',
forceDelete: true,
})
const registry = aws.ecr.getAuthorizationTokenOutput({ registryId: repository.registryId })
const image = new dockerbuild.Image('WorkerImage', {
context: { location: '.' },
dockerfile: { location: 'Dockerfile' },
platforms: ['linux/amd64'],
tags: [$interpolate`${repository.repositoryUrl}:worker`],
push: true,
registries: [
{
address: registry.proxyEndpoint,
username: registry.userName,
password: $util.secret(registry.password),
},
],
})
const cluster = new sst.aws.Cluster('Cluster', {
vpc: {
id: vpc.id,
containerSubnets: subnets,
loadBalancerSubnets: subnets,
securityGroups: [workerNetwork.id],
},
transform: { cluster: { name: 'runlane-tutorial' } },
})
const workerPermissions = [
sendPermission,
{
actions: ['sqs:ReceiveMessage', 'sqs:DeleteMessage', 'sqs:ChangeMessageVisibility'],
resources: [longRunningQueue.arn],
},
]
const workerLogGroup = '/runlane-tutorial/worker'
const workerLogArn = $interpolate`arn:${aws.getPartitionOutput().partition}:logs:${region}:${aws.getCallerIdentityOutput().accountId}:log-group:${workerLogGroup}`
const worker = new sst.aws.Service('Worker', {
cluster,
image: image.ref,
architecture: 'x86_64',
cpu: '0.25 vCPU',
memory: '0.5 GB',
scaling: { min: 1, max: 1 },
logging: { name: workerLogGroup, retention: '1 week' },
environment: {
...environment,
AWS_REGION: region,
NODE_EXTRA_CA_CERTS: '/app/certificates/rds-global-bundle.pem',
},
permissions: workerPermissions,
wait: true,
transform: {
taskDefinition(args, options) {
afterMigrations(args, options)
args.containerDefinitions = $output(args.containerDefinitions).apply((definitions) =>
JSON.stringify(JSON.parse(definitions).map((container: object) => ({ ...container, stopTimeout: 60 }))),
)
},
service(args, options) {
args.networkConfiguration = {
subnets,
securityGroups: [workerNetwork.id],
assignPublicIp: true,
}
args.enableExecuteCommand = false
options.dependsOn = [migrations, routes]
},
taskRole(args) {
args.inlinePolicies = [
{
name: 'sqs',
policy: aws.iam.getPolicyDocumentOutput({
statements: workerPermissions.map((permission) => ({ ...permission, effect: 'Allow' })),
}).json,
},
]
},
executionRole(args) {
args.managedPolicyArns = []
args.inlinePolicies = [
{
name: 'image-and-logs',
policy: aws.iam.getPolicyDocumentOutput({
statements: [
{ actions: ['ecr:GetAuthorizationToken'], resources: ['*'] },
{
actions: ['ecr:BatchCheckLayerAvailability', 'ecr:GetDownloadUrlForLayer', 'ecr:BatchGetImage'],
resources: [repository.arn],
},
{
actions: ['logs:CreateLogStream', 'logs:PutLogEvents'],
resources: [$interpolate`${workerLogArn}:*`],
},
],
}).json,
},
]
},
},
})The image resource builds the app-root Dockerfile for linux/amd64. It pushes to a dedicated ECR repository. Passing its digest reference to Service ties each task revision to that image. This avoids leaving old worker images in SST's shared asset repository after teardown.
The worker has one x86_64 Linux task with a public IP in a public subnet. It can pull its image and reach SQS without NAT. Its log group keeps logs for one week. wait: true makes deploy wait for a healthy service. SST has no stop-timeout option, so the task definition transform sets the container's stopTimeout to 60 seconds.
The log ARN uses the AWS partition, account id, region, and group name. The :* suffix covers that group's log streams. See CloudWatch log ARNs.
SST normally adds session access to the task role and secret-read access to the execution role. These transforms remove those extras. The task role keeps only the listed SQS actions. The execution role transform grants image pulls from only the worker repository and log writes to only the worker log group. It uses no managed policies. ECR requires ecr:GetAuthorizationToken on *. ECS Exec, which opens a session in the container, is off.
Service scaling uses AWS's ECS auto-scaling service-linked role. AWS owns its policy; it manages ECS scaling and CloudWatch alarms. ECS also uses its own service-linked role for network and service tasks. This config creates no VPC or log-retention helper roles. SST's bootstrap step creates shared storage, not app execution roles.
Outputs
return {
databaseUrl,
defaultQueueUrl: defaultQueue.url,
longRunningQueueUrl: longRunningQueue.url,
deadLetterQueueUrl: deadLetter.url,
region,
deliveryFunctionName: delivery.name,
maintenanceFunctionName: maintenance.name,
workerLogGroup,
clusterName: cluster.nodes.cluster.name,
serviceName: worker.nodes.service.name,
}
},
})These keys match Check the deployment. databaseUrl is marked secret in Pulumi state. SST writes plain output values to local files; protect those files and deploy logs as secrets.
Deploy
Install the pinned providers and check the config. sst install installs @pulumi/command@1.2.1 with the other pinned providers. Then build and deploy:
npm exec -- sst install
npm exec -- tsc --project tsconfig.sst.json
npm run build
umask 077
npm exec -- sst deploy --stage tutorialRun npm run build before every deploy. SST uploads the prebuilt Lambda directory. Docker copies the host-built worker bundle. RDS creation takes several minutes. Migrations run first. Then the delivery and maintenance functions, mapping, timer, task definition, and service can change.
Expect a successful deploy with the output keys above. Keep any terminal capture private: it may contain the database URL. Do not run two deploys for this stage at once.
Save the outputs for the CLI
SST writes returned values to .sst/outputs.json. Create this script to write .env without printing the database URL:
import { chmod, readFile, writeFile } from 'node:fs/promises'
const outputs = JSON.parse(await readFile('.sst/outputs.json', 'utf8'))
const values = {
DATABASE_URL: outputs.databaseUrl,
RUNLANE_ENVIRONMENT: 'tutorial',
RUNLANE_DEFAULT_QUEUE_URL: outputs.defaultQueueUrl,
RUNLANE_LONG_RUNNING_QUEUE_URL: outputs.longRunningQueueUrl,
AWS_REGION: outputs.region,
}
await writeFile(
'.env',
Object.entries(values)
.map(([key, value]) => `${key}=${value}`)
.join('\n') + '\n',
{ mode: 0o600 },
)
await chmod('.env', 0o600)Run it after a successful deploy. It replaces the tutorial .env. Remove old tutorial values from .env.local, which takes priority over .env.
node scripts/save-sst-env.mjs
export AWS_REGION=us-east-1
export NODE_EXTRA_CA_CERTS="$PWD/certificates/rds-global-bundle.pem"Use the region you deployed into. Node must read the CA setting before it starts. Keep .env and .sst out of source control. Re-run the script after a later deploy changes outputs.
Check it works
Follow Check the deployment to prove Lambda delivery, the worker, and scheduled maintenance. Read the other output names from .sst/outputs.json without sharing its database URL.
Remove everything
This deletes task history and the database without a final snapshot. Use it only when finished with this test deployment:
npm exec -- sst remove --stage tutorialThe stage's removal: 'remove' deletes its resources. skipFinalSnapshot permits database deletion. forceDelete removes the worker repository even when it holds images. Other stages are protected and retain their resources.
In the same region, check the AWS console: the RDS instance runlane-tutorial, ECR repository runlane-tutorial-worker, and ECS cluster runlane-tutorial should be gone. Check that /runlane-tutorial/worker and the two /aws/lambda/<function-name> log groups are gone too. The queues, timer, roles, and VPC should also be removed.
SST's account-level bootstrap storage can remain for other SST apps. Keep it while those apps use it. See SST state storage. Delete your local .env and .sst/outputs.json when you no longer need the credentials.
Troubleshoot SST
- Missing platform types: run
npm exec -- sst installafter changing provider versions. Keep the triple-slash reference at the top ofsst.config.ts. - Docker build or push fails: start Docker and check
docker info. Keep the rootDockerfile, worker bundle, and CA bundle in the build context. Build the app before retrying the deploy. - A bundle or handler is missing: run
npm run build. Keepbundle: 'dist/lambda'withdelivery.handlerandmaintenance.handler. - Migration command fails: read the deploy command output, fix the cause, and deploy again. Do not remove its dependencies to get past the error.
- A name already exists: check the account, region, and stage. The fixed tutorial names cannot be shared by two deployments in one region.
For database, permissions, and task failures, use the shared deployment checks.