Prepare the app
Build one app for Lambda delivery, maintenance, migrations, and a Fargate worker.
Create this app before choosing a deploy tool. All three tools use the same files and bundles.
Lambda runs a function when an event arrives. Fargate runs containers without servers for you to manage. This app sends greetings to Lambda and reports to a Fargate worker. Reports wait in memory to stand in for slow work. They have no external side effects.
This app always uses Postgres and Amazon Simple Queue Service (SQS). SQS holds messages that wake workers. For a local lane first, start runlane dev to own the in-memory runs. App triggers connect to dev or fail with storage_unavailable; tests can use createTestLane() without dev. Follow Run locally, then use Postgres and SQS.
The finished app has this layout:
my-app/
├── package.json
├── package-lock.json
├── tsconfig.json
├── runlane.config.ts
├── Dockerfile
├── .dockerignore
├── certificates/rds-global-bundle.pem
├── scripts/build.mjs
└── src/
├── env.ts
├── queues.ts
├── runlane.ts
├── tasks/greet.ts
├── tasks/build-report.ts
├── lambda/delivery.ts
├── lambda/maintenance.ts
└── worker.tsCreate the project
Use Node.js 24, npm, and an empty directory. Run all commands from this directory:
mkdir my-app
cd my-app
npm init -ySet the module type and scripts in package.json. Keep the dependency fields that npm adds in the next step.
{
"name": "runlane-tutorial",
"private": true,
"type": "module",
"scripts": {
"build": "node scripts/build.mjs",
"typecheck": "tsc --noEmit"
}
}Install the app packages:
npm install @aws-sdk/client-sqs @runlane/core @runlane/lane-postgres-sqs @runlane/postgres-storage @runlane/transport-sqs dotenv zodInstall the CLI and build tools:
npm install --save-dev @runlane/cli typescript@^6 @types/node@^24 esbuildKeep package-lock.json with the app to lock package versions.
{
"compilerOptions": {
"target": "ES2024",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"types": ["node"]
},
"include": ["src/**/*.ts", "runlane.config.ts"]
}Read the environment
Create src/env.ts. Values from the process take priority over .env.local, then .env. Quiet loading keeps CLI JSON output clean.
import { config as loadDotenv } from 'dotenv'
import * as z from 'zod'
loadDotenv({ path: ['.env.local', '.env'], quiet: true })
export const env = z
.object({
DATABASE_URL: z.url(),
RUNLANE_ENVIRONMENT: z.string().min(1),
RUNLANE_DEFAULT_QUEUE_URL: z.url(),
RUNLANE_LONG_RUNNING_QUEUE_URL: z.url(),
AWS_REGION: z.string().min(1),
})
.parse(process.env)After deployment, your tool page supplies these values for a local .env:
DATABASE_URL=postgresql://runlane:<password>@<rds-host>:5432/runlane?sslmode=verify-full
RUNLANE_ENVIRONMENT=tutorial
RUNLANE_DEFAULT_QUEUE_URL=<default-queue-url>
RUNLANE_LONG_RUNNING_QUEUE_URL=<long-running-queue-url>
AWS_REGION=us-east-1Use your chosen region. Keep .env and .env.local out of source control. Deployed processes get these values from the platform. Lambda supplies AWS_REGION; the container needs it set explicitly.
Define the tasks
Keep both queues in a shared module. The tasks and runtime import these definitions.
import { queue } from '@runlane/core'
export const defaultQueue = queue({ name: 'default', default: true })
export const longRunningQueue = queue({ name: 'long-running' })The greeting uses the default queue. Its return value becomes the stored output.
import { task } from '@runlane/core'
import * as z from 'zod'
export const greet = task({
id: 'greeting.create',
schema: z.object({ name: z.string().min(1) }),
output: z.object({ message: z.string() }),
run({ name }) {
return { message: `Hello, ${name}!` }
},
})The report uses the long-running queue and can take up to ten minutes. The abort signal lets shutdown or a lost lease stop its timer. Runlane saves console output from a task to the run's logs by default, and the output still prints normally.
import { setTimeout } from 'node:timers/promises'
import { task } from '@runlane/core'
import * as z from 'zod'
import { longRunningQueue } from '../queues.js'
export const buildReport = task({
id: 'report.build',
queue: longRunningQueue,
schema: z.object({ seconds: z.number().int().min(1).max(600) }),
output: z.object({ seconds: z.number().int() }),
async run({ seconds }, context) {
console.log(`Building a ${seconds}-second report`)
await setTimeout(seconds * 1000, undefined, { signal: context.signal })
return { seconds }
},
})Bind the runtime to both queues
One runtime owns task routing and both SQS bindings. runHints: false avoids a dedicated Postgres connection for run hints. Workers still get their wakeups through SQS.
With `runHints: false`, realtime readers fall back to `streams.pollInterval`, whose default is `contractDefaults.streams.pollInterval` (`1s`). Updates can arrive in one-second bursts; lower the interval if needed.
import { SQSClient } from '@aws-sdk/client-sqs'
import { createRunlane } from '@runlane/core'
import { postgresSqsLane } from '@runlane/lane-postgres-sqs'
import { sqsQueue } from '@runlane/transport-sqs'
import { env } from './env.js'
import { defaultQueue, longRunningQueue } from './queues.js'
import { buildReport } from './tasks/build-report.js'
import { greet } from './tasks/greet.js'
export const runlane = createRunlane({
environment: { name: env.RUNLANE_ENVIRONMENT },
lane: postgresSqsLane({
runHints: false,
postgres: { connectionString: env.DATABASE_URL, schema: 'runlane' },
sqs: {
client: new SQSClient({}),
queues: [
sqsQueue(defaultQueue, { queueUrl: env.RUNLANE_DEFAULT_QUEUE_URL }),
sqsQueue(longRunningQueue, { queueUrl: env.RUNLANE_LONG_RUNNING_QUEUE_URL }),
],
},
}),
queues: [defaultQueue, longRunningQueue],
tasks: { greet, buildReport },
})The report's task definition sets its queue. The queue names default and long-running are Runlane names, each bound to one AWS queue URL.
Add the Lambda handlers
Each handler has its own file. The delivery handler uses the concrete SQS lane type from the runtime.
import { runlane } from '../runlane.js'
export const handler = runlane.createDeliveryHandler()The maintenance function runs one bounded pass. It reuses the runtime when Lambda keeps the process warm. Each pass also arms scheduled task fires that are due before the next pass and sends each one a delayed wakeup. The run is created when its fire time arrives. The default scheduleLookahead of 1m matches the one-minute timer each tool sets up. A standard SQS queue holds each future wakeup using a whole-second delay rounded up. The fire time marks eligibility; delivery and worker capacity determine the later handler start. See SQS timing limits. If you change the timer's rate, pass the same interval as scheduleLookahead to createMaintenanceHandler().
import { runlane } from '../runlane.js'
export const handler = runlane.createMaintenanceHandler()Add the worker
The worker receives only the long-running queue. It handles SIGTERM, the stop signal sent by the container platform, by draining accepted work.
import { longRunningQueue } from './queues.js'
import { runlane } from './runlane.js'
const worker = await runlane.createDeliveryWorker({
concurrency: 1,
queues: [longRunningQueue.name],
})
const close = () => {
console.log('Worker draining')
void worker.close()
}
process.once('SIGTERM', close)
process.once('SIGINT', close)
console.log('Worker listening')
try {
await worker.waitUntilClosed()
} finally {
process.off('SIGTERM', close)
process.off('SIGINT', close)
await runlane.close()
}
console.log('Worker stopped')The log lines show in the worker's log group, so you can see a clean drain. Worker stopped prints only after every attempt settles and the database pool closes.
A forced stop can interrupt work before it drains. Runlane uses leases to track ownership. Maintenance can recover interrupted work.
Each tool page gives the worker container 60 seconds to stop. That covers the worker's default shutdownGrace (contractDefaults.worker.shutdownGrace, 25 seconds today), an SQS long poll of up to 20 seconds, and 15 seconds to save results and exit. The poll and the grace can overlap, but the budget counts both to stay safe. Raise it if you raise shutdownGrace. Fargate allows at most 120 seconds. To shorten the idle wait, set waitTimeSeconds in the lane's sqs options. Shorter polls make more empty receives, which raises SQS request costs. See allow time for worker shutdown.
Trust the database certificate
Amazon RDS hosts the Postgres database. Download its certificate authority (CA) bundle. A CA signs the certificate that proves the server's identity.
mkdir -p certificates
curl --fail --location \
https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem \
--output certificates/rds-global-bundle.pemKeep the bundle with your app. sslmode=verify-full checks both the certificate chain and the database hostname. Use the RDS hostname in the URL.
Node.js 20 and later Lambda runtimes need explicit RDS CA loading. Each deployed Lambda uses NODE_EXTRA_CA_CERTS=/var/task/certificates/rds-global-bundle.pem.
On your laptop, export the path before starting Node:
export NODE_EXTRA_CA_CERTS="$PWD/certificates/rds-global-bundle.pem"Node reads this variable at process start. Loading it later through dotenv is too late.
Build the bundles
Create scripts/build.mjs. It bundles JavaScript and copies the CA bundle into the Lambda asset.
import { cp, mkdir, rm } from 'node:fs/promises'
import { build } from 'esbuild'
await rm('dist', { recursive: true, force: true })
await mkdir('dist/lambda/certificates', { recursive: true })
const options = {
bundle: true,
platform: 'node',
format: 'esm',
target: 'node24',
sourcemap: true,
external: ['pg-native'],
banner: {
js: "import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);",
},
}
await build({
...options,
entryPoints: ['src/lambda/delivery.ts', 'src/lambda/maintenance.ts'],
outdir: 'dist/lambda',
outExtension: { '.js': '.mjs' },
})
await build({
...options,
entryPoints: ['src/worker.ts'],
outfile: 'dist/worker/index.mjs',
})
await cp('certificates/rds-global-bundle.pem', 'dist/lambda/certificates/rds-global-bundle.pem')The esbuild options create ES module bundles for Node.js 24. The createRequire banner supports CommonJS dependencies inside them. pg-native is an optional Postgres driver; this app uses the JavaScript driver.
All tools use dist/lambda for delivery.handler and maintenance.handler. Both functions use the nodejs24.x runtime and x86_64 architecture.
Build the container image
The image uses the worker bundle from the last npm run build. Run the build before every deploy. Docker copies only that bundle and the certificates. The process runs as the non-root node user. CMD starts Node directly, so Node receives SIGTERM when ECS stops the task.
FROM node:24-slim
WORKDIR /app
ENV NODE_ENV=production
ENV NODE_EXTRA_CA_CERTS=/app/certificates/rds-global-bundle.pem
COPY dist/worker ./dist/worker
COPY certificates ./certificates
USER node
CMD ["node", "dist/worker/index.mjs"]Exclude local files and secrets from the image build:
node_modules
.git
.env*
dist/lambdaRun npm run build, then build the image from the app root. The worker uses x86_64 in AWS. Set the platform so builds from Apple silicon use the same architecture:
docker build --platform linux/amd64 --tag runlane-tutorial-worker .Configure the laptop CLI
The CLI imports the same runtime, so it sees both tasks and both queue bindings.
import { type RunlaneCliConfig } from '@runlane/cli'
import { runlane } from './src/runlane.js'
export default { runtime: runlane } satisfies RunlaneCliConfigRun migrations from the deploying machine
Each tool page runs this command from the app root before workloads are created or updated:
npm exec -- runlane adapter postgres migrateThe CLI loads runlane.config.ts and uses the installed storage package and its SQL files. It checks migration history and applies pending migrations. Repeating the command is safe. A failure must stop the deploy.
Loading the runtime needs DATABASE_URL with ?sslmode=verify-full, RUNLANE_ENVIRONMENT=tutorial, both queue URLs, and AWS_REGION. Supply them through the process environment or .env. Export NODE_EXTRA_CA_CERTS with the absolute CA path before starting the command, as shown above. Each tool page supplies these values once the database and queues exist.
Check the build locally
These checks need no database connection or environment values:
npm run typecheck
npm run buildExpect dist/lambda/delivery.mjs, dist/lambda/maintenance.mjs, and dist/worker/index.mjs. Each JavaScript bundle has a source map. The Lambda asset also has certificates/rds-global-bundle.pem.