Deploy with Postgres and SQS
Keep run state in Postgres and use SQS to wake workers.
Choose this lane for SQS-triggered Lambda functions or long-running SQS consumers. Postgres remains the source of truth. Each SQS message only tells a worker which run to check.
Deployment shape
producer
|
v
Postgres (run + outbox)
|
v
publisher --> SQS --> worker
|
v
Postgres
maintenance --> due and recovery workRunlane stores the run and its pending wakeup together in Postgres. A publisher sends the wakeup to SQS. The consumer then reads Postgres before it claims or executes the run.
Follow Upgrade Runlane when changing handlers, packages, or stored formats.
To create this infrastructure step by step with SST, AWS CDK, or Terraform, follow Deploy to AWS.
Install the packages and bind queues
npm install @aws-sdk/client-sqs @runlane/core @runlane/lane-postgres-sqs @runlane/postgres-storage @runlane/transport-sqs zodThe files below use one practical layout:
src/
├── tasks/send-email.ts
├── runlane.ts
├── worker.ts # long-running consumer
└── handlers/
├── runlane-sqs.ts # Lambda consumer
└── runlane-maintenance.ts # scheduled Lambda
scripts/
└── migrate-runlane.tsUse either the Lambda consumer or the long-running consumer. Both are shown so you can match the deployment you already run.
Put task code in its own module
Create src/tasks/send-email.ts. Producers import the task definition for its schema and id. Only workers execute run() and therefore need EMAIL_API_URL.
import { task } from '@runlane/core'
import * as z from 'zod'
const envSchema = z.object({ EMAIL_API_URL: z.url() })
export const sendEmail = task({
id: 'email.send',
schema: z.object({ to: z.email() }),
async run({ to }, context) {
const { EMAIL_API_URL } = envSchema.parse(process.env)
const response = await fetch(EMAIL_API_URL, {
body: JSON.stringify({ to }),
headers: { 'content-type': 'application/json' },
method: 'POST',
signal: context.signal,
})
if (!response.ok) throw new Error(`Email API returned ${response.status}`)
},
})Create one runtime module
Create src/runlane.ts. Every producer, delivery handler, worker, and maintenance process imports this module so they share the same environment, task catalog, queue definition, storage, and SQS binding.
Set DATABASE_URL and RUNLANE_SQS_QUEUE_URL before the module loads. Configure the AWS SDK region and credentials through your normal SQSClient environment or client options.
import { SQSClient } from '@aws-sdk/client-sqs'
import { createRunlane, RunRetention, queue } from '@runlane/core'
import { postgresSqsLane } from '@runlane/lane-postgres-sqs'
import { sqsQueue } from '@runlane/transport-sqs'
import * as z from 'zod'
import { sendEmail } from './tasks/send-email.js'
const env = z
.object({
DATABASE_URL: z.string().min(1),
RUNLANE_SQS_QUEUE_URL: z.url(),
})
.parse(process.env)
export const emailQueue = queue({ name: 'email', default: true })
export const runlane = createRunlane({
retention: {
succeeded: RunRetention.deleteAfter('7d'),
cancelled: RunRetention.deleteAfter('7d'),
failed: RunRetention.deleteAfter('30d'),
expired: RunRetention.deleteAfter('7d'),
},
lane: postgresSqsLane({
postgres: { connectionString: env.DATABASE_URL, schema: 'runlane' },
sqs: {
client: new SQSClient({}),
queues: [sqsQueue(emailQueue, { queueUrl: env.RUNLANE_SQS_QUEUE_URL })],
},
}),
queues: [emailQueue],
tasks: { sendEmail },
})The same emailQueue value appears in the runtime queue catalog and the SQS binding. A missing or mismatched binding stops startup instead of sending work to the wrong destination.
Run migrations during deployment
Create scripts/migrate-runlane.ts and run it as a release or deployment step before the new application starts. Do not call it from a request handler or worker startup.
import { applyPostgresStorageMigrations } from '@runlane/postgres-storage'
import * as z from 'zod'
const { DATABASE_URL } = z.object({ DATABASE_URL: z.string().min(1) }).parse(process.env)
await applyPostgresStorageMigrations({ connectionString: DATABASE_URL, schema: 'runlane' })Deployment tooling must validate and apply the complete migration history shipped with the installed provider before startup, not only the baseline. Behind PgBouncer, run migrations with a direct database URL; see run behind PgBouncer. Starting Runlane does not inspect or change the schema. Follow the storage compatibility rules and Postgres migration instructions.
Handle Lambda deliveries
For SQS-triggered Lambda, create src/handlers/runlane-sqs.ts and configure that export as the function handler:
import { runlane } from '../runlane.js'
export const handler = runlane.createDeliveryHandler()The handler has the lane's native Lambda event and result types. It accepts SQSEvent from @types/aws-lambda. It starts the runtime on the first invocation and reuses it when the Lambda environment stays warm. Shortly before the Lambda runs out of time, Runlane aborts context.signal with the task_interrupted Runlane error. If the handler then throws, Runlane interrupts the attempt without spending a retry. See Stop crash loops for the interruption allowance.
Framework, storage, parsing, or persistence failures leave the message available for SQS redrive. A stored task result such as failed, retrying, released, or cancelled means Runlane handled that delivery; it is not an SQS failure by itself.
Recursive loop detection
AWS recursive loop detection defaults to RecursiveLoop: Terminate. After about 16 Lambda → SQS → Lambda hops from one event, AWS drops the next invocation. CloudWatch reports RecursiveInvocationsDropped. SQS keeps retrying the message until its redrive policy moves it to the dead-letter queue. Other messages in a dropped batch wait for their visibility timeout too.
Runlane keeps this default safe for schedules. By default, an SQS Lambda handler accepts the current schedule fire but leaves the next fire's arming and wakeup to maintenance. The separate maintenance invocation starts a fresh AWS lineage. Keep maintenance running: a schedule that fires more often than the maintenance timer runs at maintenance cadence. This applies to runtime and declared schedules. Long-running SQS workers keep eager arming.
Deep chains of more than about 15 consecutive child, continuation, or invocation handoff hops published inside Lambda deliveries can still reach AWS's limit. Runlane recovers through maintenance's dispatch or queued delivery recovery. On unbounded queues, recovery can wait up to contractDefaults.maintenance.resendQueuedRunsAfter, plus the next maintenance pass. Watch RecursiveInvocationsDropped when these chains stall.
If you need eager schedule wakeups or deep delivery chains, opt in on both sides:
- AWS: set the function's CloudFormation
RecursiveLoop: Allow, CDKrecursiveLoop: RecursiveLoop.ALLOW, or Pulumiaws.lambda.FunctionRecursionConfigwithrecursiveLoop: 'Allow'. The CLI equivalent isaws lambda put-function-recursion-config --function-name YOUR_FUNCTION --recursive-loop Allow. - Runlane: set
sqs.recursiveLoop: LambdaRecursiveLoop.Allowon the lane, orrecursiveLoop: LambdaRecursiveLoop.AllowoncreateSqsLambdaHandler(). ImportLambdaRecursiveLoopfrom@runlane/transport-sqs,@runlane/lane-postgres-sqs, or@runlane/lane-redis-sqs; its values areallowandterminate. The default issqsLambdaDefaults.recursiveLoopfrom@runlane/transport-sqs(terminate).
Allow removes AWS's guard against application bugs that loop forever. Such a bug can keep invoking Lambda and produce an unbounded bill. Keep Terminate unless you accept that risk.
Run a long-lived consumer
If you run a service instead of Lambda, create src/worker.ts and use it as that service's process entry point:
import { emailQueue, runlane } from './runlane.js'
const worker = await runlane.createDeliveryWorker({
concurrency: 8,
queues: [emailQueue.name],
})
const close = () => void worker.close()
process.once('SIGTERM', close)
try {
await worker.waitUntilClosed()
} finally {
process.off('SIGTERM', close)
await runlane.close()
}The entry point handles cooperative SIGTERM shutdown. Your process supervisor should restart it when waitUntilClosed() rejects.
Deploy compatible task catalogs
First pick the right tool in change tasks safely. Runlane selects the SQS destination; your deployment decides which Lambda or service build consumes it. Runlane does not pin runs to those builds or retain old consumers.
The overlap advice below assumes both releases can read the same storage format. For the stored execution-policy upgrade, stop old runtimes before new ones create runs, even on separate queues.
An SQS worker receives a message before it knows the run's task. A worker that cannot execute that task does not claim the run. It leaves the run unchanged, returns the message for redelivery, and logs worker_task_missing, at most once a minute for each task. A worker with the task runs it on a later delivery. If the message ends up in a dead-letter queue first, maintenance delivery recovery publishes the run again later.
Every return costs one more SQS receive, and the run waits for the next delivery. For a short deploy, that is fine. To keep old and new consumers fully apart, give the new task version a new task id, a distinct logical queue, and a distinct physical SQS queue consumed only by the new catalog. For Lambda, map that SQS queue only to the new function version or alias. Changing only the logical queue name does not isolate work when old and new bindings share the same physical SQS queue.
Do not use competing Lambda event filters to route builds on one SQS queue. Lambda removes SQS messages that do not match its filter; it does not leave them for the matching consumer.
Upgrade every runtime that can run the outbox phase, including maintenance processes, with the new SQS binding before producers use it. Outbox claims span the environment rather than one queue, so an old publisher can claim a new queue's pending message but cannot publish it through a missing binding. Keep old task definitions and both queue bindings available until queued, retrying, released, waiting, delayed, and redriven work has drained. If a task id remains unchanged, its handler and saved payload, task-output, and step-output shapes must remain compatible with runs created by the previous release.
Tune delivery capacity
Each limit belongs to one part of the system.
Use a standard SQS queue when tasks do not require broker ordering. Lambda fits bursty work that finishes comfortably within its execution limit. A long-running consumer fits sustained work and tasks that may outlive that limit.
| Control | Owner | What it limits |
|---|---|---|
sqs.batchSize | Runlane SQS transport | Messages in one SQS publish request. It does not control task concurrency; see the transport configuration for its provider default. |
sqs.waitTimeSeconds | Runlane SQS transport | Long-poll wait for every queue consumer. See SQS polling options for bounds and the default. Lambda handlers do not poll. |
Delivery worker concurrency | Runlane runtime | Active deliveries in one long-running worker process, and the largest SQS receive batch. Its default is contractDefaults.worker.concurrency. |
Queue concurrency | Runlane storage | Reserved and active runs across every worker in one environment, queue, and concurrency key. |
| Lambda batch size and batching window | SQS event source | Records passed to one Lambda invocation. |
| Lambda polling mode, event-source scaling, and reserved concurrency | Lambda deployment | Concurrent Lambda invocations for the event source and function. |
| Queue visibility timeout and dead-letter redrive | SQS queue | How long a delivery stays hidden and when repeated failures move to a dead-letter queue. |
| PostgreSQL connections, compute, storage, and proxy | Database deployment | Durable coordination capacity shared by producers, consumers, maintenance, and application SQL. |
Size Lambda delivery
For a standard queue, Runlane starts every record in a Lambda event at the same time. Use this upper bound for full batches with Lambda's default polling and an event-source concurrency cap.
active deliveries =
event-source maximum concurrency x batch sizeWithin one FIFO event, Runlane handles records one after another in the same time budget and stops at the first record that cannot finish. Records behind it return to SQS, wait for the visibility timeout, and use one receive toward the dead-letter redrive count. A clean handoff counts as finished, so the next record starts with whatever time is left. Other message groups can run in separate Lambda invocations.
Lambda's Provisioned Mode cannot use event-source maximum concurrency. It scales between configured minimum and maximum poller counts. Each poller can support up to 10 concurrent invocations. Use maximum pollers x 10 as the invocation upper bound when sizing the database. Provisioned Mode costs more and is intended for queues that need faster, more consistent scaling.
When you use Provisioned Mode, AWS estimates poller demand with this formula.
events per second per poller =
minimum of(
round up(1,024 / average event size in KB),
round up(10 / average function duration in seconds) x batch size,
minimum of(100, 10 x batch size)
)
required pollers =
round up(
peak events per second
/ events per second per poller
)AWS uses mean function time in this formula. Use p95 time for a safer workload plan.
Estimate the task capacity you need from measured traffic.
required active deliveries =
peak deliveries per second
x 95th-percentile (p95) handler duration in seconds
x burst-headroom multiplier
required Lambda concurrency =
round up(
required active deliveries
/ observed records per invocation
)In the default polling mode, also calculate a starting cap. Available Lambda concurrency is what remains after other event sources and functions use their share.
starting Lambda invocation cap =
minimum of(
active-invocation database budget,
downstream-safe Lambda concurrency,
available Lambda concurrency
)
required Lambda concurrency <= starting Lambda invocation capThis is a planning limit, not proof that the deployment is safe. If required concurrency exceeds the starting cap, the deployment cannot meet the target rate with the current budgets. Increase database capacity or downstream quota, or use a different worker topology. Test the chosen cap and reduce it when database connections, latency, or downstream errors approach their limits.
Measure how full each batch is. Do not assume that every invocation contains the configured maximum. A busy queue may fill batches, while low traffic may produce one-record invocations.
If a downstream provider publishes request and token quotas, convert both to tasks per second. Use both quotas for a task that makes one provider request.
provider-limited tasks per second =
minimum of(
requests per minute / 60,
tokens per minute / average tokens per task / 60
)Reduce the result when one task makes more than one request. Keep this limit separate from Lambda and database capacity.
For the SQS event source:
- Start with a batch size of
10. Larger batches start more work inside one Runlane handler. Test them under load first. - For a FIFO queue, the whole batch must fit one invocation: batch size times your longest job must stay below the handler's budget, which is the remaining time minus the safety margin. Otherwise use a batch size of
1. A record that starts late has less time. See Stop crash loops for how the time limit affects the allowance. Use a batch size of1for jobs that hand off, since the next record would start with only the time left after the handoff time. When a record cannot finish, each record behind it returns to SQS and uses a receive, so a healthy record can reach the dead-letter queue without running. - Enable partial batch responses. This keeps one failed record from redelivering successful records.
- In default polling mode, reserve enough function concurrency for all of its event sources. The reservation must cover the sum of their concurrency caps.
- Set the queue visibility timeout using
visibility timeout >= 6 x Lambda timeout + batching window. Set the dead-letter redrive count to at least5. - Move work that may approach Lambda's 15-minute execution limit to a long-running consumer.
These requirements come from AWS's current SQS event-source configuration, scaling, and partial batch response guidance. The AWS example's values belong to its measured database budget. They are not Runlane defaults.
Budget PostgreSQL connections
Each postgresSqsLane() instance creates its own Postgres driver and internal pg.Pool. The current driver cannot accept an external pool or configure the pool maximum. Each instance can therefore lazily open up to node-postgres's current default maximum of 10 connections. With runHints: true (the default), each started lane also opens one dedicated LISTEN connection for run subscription hints, shared by all subscribers. Set runHints: false for Lambda consumers; the AWS example does this. Add that connection and any application database pools in the same process to the pool maximum. SQS still carries worker wakeups; polling-worker work hints stay disabled. Run hints are independent and carry no source values. Readers fall back to streams.pollInterval after a missed hint or listener loss; see run subscription hints.
The query pool uses postgres.connectionString. Set postgres.preparedStatements: false if a transaction pooler cannot track named statements. The run listener uses postgres.directConnectionString, which defaults to that query URL. With a transaction pooler, budget its server pool and these direct listener connections separately. SQS lanes never open a Postgres worker listener. See PgBouncer setup for both URLs and the background listener check.
First estimate connection demand from active Lambda calls.
available consumer connections =
database maximum
- operational reserve
- producer, observer, maintenance, and other fixed pool maximums
maximum connections per Lambda environment =
Runlane pool maximum
+ one Runlane run-listener connection only when runHints is true
+ application pool maximum
+ other pool maximums
active-invocation database budget =
round down(
available consumer connections
/ maximum connections per Lambda environment
)
nominal connections for active Lambda invocations =
event-source maximum concurrency
x maximum connections per Lambda environment
known-process pool budget =
operational reserve
+ sum(
maximum live long-running processes for each deployment unit
x maximum connections opened by each process
)
known-process pool budget <= database maximumFor each process, add the Runlane pool, its run listener when enabled, and every application pool it owns. For Lambda, that sum is the maximum connections per environment. Include HTTP functions, maintenance functions, producers, and long-running worker replicas. The known-process formula is a hard configured bound only when every process count is bounded.
The Lambda formulas estimate active calls only. Lambda may freeze an environment and keep its pools open after a call ends. It may also replace an environment. Thus, an event-source cap does not set a hard limit on open database connections. Keep headroom and measure connections under sustained load.
RDS Proxy can reuse connections and set a firmer limit for the database backend. It does not cut Runlane's SQL or write-ahead log (WAL). Measure connection borrowing and session pinning before raising consumer concurrency.
For example, each Emails Lambda environment can open up to 10 Runlane pool connections. The example sets runHints: false, so it opens no run listener. Its application pool can open 2 more connections. The function reservation and event-source cap are both 2. At two active invocations, the nominal pool budget is 2 x (10 + 2) = 24 connections before other services and the reserve. Remeasure after changing this configuration. Lambda can retain other warm environments, so 24 is not a hard connection ceiling. These values protect that example's small database; they are not general defaults.
Estimate database work separately from pool limits.
connections needed for task SQL =
tasks per second
x measured connection-seconds per task
x headroom multiplier
PostgreSQL requests per second =
tasks per second x measured SQL calls per task
WAL bytes per second =
tasks per second x WAL bytes per taskMeasure connection-seconds as total pool checkout time divided by completed tasks. This also covers batches that share one connection. Do not count time spent waiting for an external API or model.
Choose database compute from the observed workload. Provisioned non-burstable capacity fits steady traffic. Aurora Serverless v2 fits traffic with large peaks and valleys. Reader replicas do not raise Runlane lifecycle throughput. Claims, leases, events, and outbox updates use the writer.
For Aurora, start with Standard storage for low or moderate I/O. AWS says I/O-Optimized can cost less when I/O exceeds 25% of total Aurora database spend. Use billed I/O and database metrics to decide. Runlane SQL counts are not Aurora I/O request counts.
Size long-running workers
The concurrency: 8 in the example above is illustrative. Set each worker's concurrency from handler duration, downstream limits, memory, CPU, and database latency. Add replicas when queue age or backlog grows too large. Keep their combined pools inside the database connection budget.
required worker slots =
peak deliveries per second
x p95 handler duration in seconds
x burst-headroom multiplier
required worker processes =
round up(
required worker slots
/ measured safe slots per process
)
steady-state target backlog =
target average time in the selected backlog, in seconds
x measured total departures per second
backlog growth per second =
tasks entering the measured backlog per second
- tasks leaving the measured backlog per secondThis is a steady-state estimate. Choose one backlog population, such as runnable runs awaiting dispatch. Use the time spent in that population and the same population for both rates. If you count all accepted non-terminal runs, use total run time instead of queue wait. Departures include every transition that removes a task from the chosen population. This may include failure, cancellation, or dispatch.
Use queue age with backlog when scaling workers. Sustained positive backlog growth means the deployment is falling behind. A large backlog of short tasks may be healthy. A smaller backlog of old tasks may already miss the service goal. For a bounded Runlane queue, include runs waiting in Postgres. SQS depth alone does not contain the full backlog.
Worker concurrency is local to one process. For the durable global limit enforced by queue({ concurrency: { total: 5 } }), see limit concurrency. Eager runtimes reserve and publish ready bounded work after commit and refill freed capacity without waiting for maintenance. Deferred dispatch stays maintenance-owned. Keep maintenance for time-based work and dispatch recovery.
Understand consumer behavior
The SQS adapter owns receive batches, visibility renewal, FIFO order, and message settlement. Core receives delivery bytes, cancellation, an optional provider message id, and an optional acknowledgement callback.
Worker concurrency limits active deliveries across selected queues. Pending receive reservations share that worker-wide budget. Each request uses free handler capacity minus all pending reservations, up to SQS's ten-message maximum and the queue's remaining receive slots. A queue with no receive in flight can still ask for one message while a handler slot is free. This lets a busy queue start work while another queue waits in a long poll.
Each queue starts with one long poll that asks for one message. Its wait is sqs.waitTimeSeconds; see SQS polling options for bounds and the default. Non-empty responses allow larger batches and more overlapping receives. An empty response returns the queue to one poll that asks for one message. Each queue also bounds received messages plus its own pending reservations by concurrency.
With concurrency: 1, each receive asks for one message and each delete runs on its own. Raise concurrency to allow fuller receive and delete batches. Choose it from handler duration and the database budget in size long-running workers.
Deletes run in batches without waiting for the slowest handler from the receive batch. A delivery frees its handler slot before its final delete settles. Its queue's receive slot stays held until both delivery and settlement finish. This bounds held messages and pending deletes for that queue. FIFO messages run in order within each message group. Independent groups can progress concurrently. An unresolved delivery, visibility renewal, or delete blocks later messages in its group from that received batch.
FIFO publish order covers messages SQS accepts. A failed batch entry has no broker position. If Runlane retries it later, that retry follows messages SQS already accepted. This matches the transport's same-index per-message outcome contract.
Use runtime.createDeliveryWorker({ concurrency: 1 }) for serial work within one worker. The Lambda event source controls Lambda batches.
Estimate cost
Measure the fixed cost of keeping the deployment online and the extra cost of processing work. Report both numbers because a cheap task can still run on an expensive idle deployment.
cost per million successful tasks =
measured cost during the test
/ successful tasks during the test
x 1,000,000
measured cost =
Postgres compute, storage, I/O, and backups
+ Lambda requests and duration, or worker compute
+ Provisioned Mode event-poller EPU-hours, when enabled
+ SQS request units
+ database proxy
+ logs and metricsFor SQS, count every send, receive, delete, and visibility API action. Include repeated actions caused by retries and ReceiveMessage calls that return no records. Batch fill and message size affect billable request units. Use current regional prices for SQS, Lambda, and Fargate.
How the SQS worker holds messages
A long-running SQS worker receives messages with 30 seconds of visibility. It renews visibility every 10 seconds while a message is waiting or still needs to be held. Due renewals share queue-local batches of up to ten messages.
On a standard queue, core acknowledges the message just after storage saves the worker's claim on the run, before the handler starts. A schedule wakeup is acknowledged once storage saves its fire's run, because the saved run then drives its own delivery. If saving fails, the message stays and SQS delivers it again. The adapter stops renewing that message, waits for any renewal already in flight, and deletes it in a batch. The run's lease now protects the running task. Lease refresh and maintenance own recovery if the worker stops.
If the first native delivery (deliveryCount === 1) throws a retryable claim storage_conflict before acknowledgement, core requests redelivery after contractDefaults.delivery.claimConflictRetryDelayMs (1,000 ms). The worker stops renewal and applies that delay to the receipt's visibility, rounded up to whole seconds. This avoids holding a bounded capacity slot idle for the full receive timeout. The reservation stays fenced in storage; redelivery does not permit two executions. A failed visibility change falls back to visibility expiry.
This one fast retry consumes one native SQS receive toward maxReceiveCount. Later deliveries and unknown counts keep native visibility backoff. Other retries, including paused or full queues, missing handlers, storage outages, and unexpected errors, keep the receive visibility timeout as backoff. They do not release the receipt early or increase its receive count faster.
Lambda returns partial batch failures and leaves retry timing to the event source mapping.
FIFO messages stay held until the delivery finishes and its delete settles. Keeping the message hidden prevents another consumer from starting the next message in that FIFO group too soon. FIFO deliveries keep renewing visibility through deletion.
Graceful worker.close() stops new receives and lets in-flight polls finish. It releases any unstarted messages they return by setting visibility to zero. Polls drain in parallel with attempt grace. An idle close can take up to waitTimeSeconds (configured through sqs.waitTimeSeconds), plus request and release time. Aborting the worker's signal, or pressing Ctrl+C a second time in the CLI, aborts receives immediately; SQS may keep an unseen receipt hidden until its visibility timeout. It keeps renewing held receipts during shutdownGrace, then signals active handlers. With shutdownGrace: 'unlimited', there is no abort timer and visibility keeps renewing until attempts settle. The worker signal still stops immediately. A handler error after that abort releases the run and publishes a fresh wakeup through the durable outbox. Another worker can claim it without waiting for lease or receipt expiry, subject to queue admission. Bounded queues return through maintenance's capacity dispatcher. Standard receipts may already have been deleted after claim; their replacement wakeup uses the same outbox path. It deletes deliveries that finish as handled, even during shutdown. It returns held messages that have not been acknowledged or permanently rejected by setting their visibility to zero. This includes messages waiting for a handler slot and buffered FIFO successors. It waits for accepted deliveries, deletes, renewals, and releases to settle. A message whose renewal failed is neither released nor deleted, because another consumer may own it. After a renewal failure, closure still completes, and visibility expiry makes the message available later.
On standard queues, ApproximateNumberOfMessagesNotVisible excludes tasks whose standard-queue messages were deleted early. Use Runlane run counts for in-flight work. Visible backlog still counts messages waiting in SQS. Running tasks on standard queues can outlive SQS's 12-hour visibility limit, because they rely on renewable storage leases. FIFO messages remain subject to that limit.
How work recovers
| Situation | What happens |
|---|---|
| Worker closes: message received, task not started | Returned to the queue right away |
| Worker closes: task errors after shutdown abort | Run released and a fresh wakeup published, with no retry cost |
| Worker closes: task finished while closing | Message deleted, no duplicate |
| Worker closes: message taken by a cancelled long poll | Back in the queue within 30 seconds |
First native delivery throws retryable claim storage_conflict before acknowledgement | Receipt visibility set to the core-requested delay (1 second); storage still owns admission |
Other delivery returns retry | Receipt stays hidden until visibility expires |
| Worker crashes: message received, run not yet claimed | Back in the queue within 30 seconds |
Delivery returns reject, including during shutdown | Held until visibility expires, then subject to SQS redrive and dead-letter policy; not released on close |
| Worker crashes: task running | Recovered after lease expiry, or failed with task_interrupted when the run exceeds its interruption allowance |
Receipt renewal runs every third of the visibility duration, measured from request send times so reply latency does not move the retry cadence. A connection error is recorded and retried without immediately aborting delivery. The local safety deadline is the last confirmed acquisition or renewal’s monotonic send time, plus visibility duration, minus one renewal interval. Proven ownership loss stops delivery immediately; continued failures stop it after that deadline. A renewal whose planned slot is at or before the deadline is sent even if its timer wakes late. Its reply may arrive after that deadline. It must confirm before the hard bound: the last confirmed send plus the full visibility duration. At that bound, Runlane gives up even if the request is still in flight. A late success cannot restore ownership. Immediate renewal after a late blocking receive uses the same send-anchored visibility bound and stops on worker cancellation. A stalled request cannot hold delivery capacity past that bound.
When a worker closes with a received but unstarted message, it returns the receipt by setting visibility to zero. Successful release lets another worker receive it right away.
When a delivery finishes while closing, the worker still deletes its message. Shutdown does not create a duplicate by skipping that delete. SQS can still redeliver messages under its normal delivery guarantees; storage decides whether a run needs execution.
A cancelled long poll can still take messages. The service may hand messages to a receive after the worker has given up waiting for its response. The worker never learns those receipt handles, so it cannot release them. The receive's short visibility window bounds how long they stay hidden after receipt.
A crash before the run is claimed leaves its received message hidden until visibility expires. With the worker's default, that is at most 30 seconds after receipt or its last renewal.
A crash during a claimed task leaves recovery with the run's lease. Once it expires, maintenance makes the run eligible again and publishes another wakeup. The crash budget can stop repeated lease takeovers. The maintenance schedule and any backlog add to the recovery time.
To shorten lease recovery, use the execution lease settings. A worker that cannot refresh a shorter lease in time loses ownership, and another worker may run the task again.
When many workers fail at once, a long-running maintenance service drains full productive pages back to back. A scheduled maintenance handler re-requests at most deliveryRequestLimit runs per invocation. Raise that limit or use the service when a mass crash could leave a large recovery backlog. See run maintenance.
Give maintenance its own process
For a scheduled Lambda, create src/handlers/runlane-maintenance.ts:
import { runlane } from '../runlane.js'
export const handler = runlane.createMaintenanceHandler()Point an EventBridge schedule or equivalent scheduler at this handler. Do not run maintenance inside each SQS record handler. Maintenance arms schedule fires and starts due ones, wakes due retries and waits, recovers leases, finishes cancellations, and publishes pending outbox messages.
Each pass arms schedule fires due before the next pass (scheduleLookahead, default 1m; set it to your scheduler's interval) and sends each one a delayed wakeup. Standard queues hold the wakeup until the fire time, and the worker that receives it creates the run, so no maintenance pass is needed at the fire time. Accepting a fire arms the next one up to the queue's 15-minute delay limit, so schedules faster than your maintenance timer keep running on time.
For an always-on maintenance process, use the supervised service shown in run maintenance.
Delayed-run timing
Schedules, runAt, retry backoff, and timed releases set when work becomes eligible. Storage checks eligibility before claiming it. The handler starts later as delivery, queue admission, and worker capacity permit; there is no maximum start-latency guarantee. This applies to long-running workers and Lambda handlers. See eligibility and start time.
When a standard-queue wakeup is published before its due time, Runlane rounds SQS DelaySeconds up to whole seconds. With aligned clocks, rounding adds less than one second beyond the requested delay, before broker, receive, and processing latency. For example, a wakeup due in 2.3 seconds uses a 3-second delay. Clock skew can affect delivery timing, but storage still decides whether the run is due.
SQS FIFO queues cannot delay individual messages. A scheduled FIFO run waits for the first maintenance pass after it is due, then for delivery and capacity. Use a standard queue for scheduled work to avoid that extra dispatch wait. If the work needs FIFO ordering, have the scheduled task trigger a child on the FIFO queue. An always-on maintenance service can also reduce dispatch latency.
Check the deployment
Trigger one run from an application process that imports runlane from src/runlane.ts. Confirm its SQS wakeup reaches the selected consumer and ends in a stored terminal result. Replay the message and confirm it does not execute a second job.
Test partial batch failure and dead-letter behavior in an isolated AWS account or supported compatible service. Stop a consumer during a side effect and confirm the next attempt does not repeat it. See make side effects safe to repeat.
If SQS has messages but runs do not execute, check the queue binding, environment, task catalog, and delivery failure observer.
If the outbox is pending but SQS is empty, inspect maintenance and publishing. Do not create replacement runs.
If a run stays queued after its message left SQS, for example after a dead-letter queue purge or an expired retention period, keep maintenance running. Once the run has waited contractDefaults.maintenance.resendQueuedRunsAfter, delivery recovery publishes a new message for it. A consumer that later receives both messages executes the run once and acknowledges the other. See recover lost wakeups for the bounds on that recovery.
Run progress hints
runHints defaults to contractDefaults.realtime.runHints (true) on this lane and the raw driver. Set runHints: false on Lambda and other serverless consumers to avoid one extra LISTEN connection per container. Run subscribers watching work executed by a consumer with hints disabled fall back to streams.pollInterval. Keep hints enabled on long-running processes when prompt updates matter. SQS delivers work. This lane forces storage workHints: false and rejects workHints at the top level or inside postgres. Set runHints only at the top level.
Allow time for worker shutdown
Use unlimited grace in production only if the platform stop timeout permits the full drain. If the platform kills the process first, lease expiry recovers unfinished runs.
Set the platform's termination window above the worker's shutdownGrace, with time left for handler cleanup and result writes. Graceful SQS shutdown also waits for accepted long polls, which drain in parallel with attempt grace. Set waitTimeSeconds beside client and queues in the lane's sqs options to shorten the idle wait. Shorter polls increase empty receives and SQS request costs; Lambda handlers do not poll and are unaffected. The AWS example derives its ECS stopTimeout from the shared worker grace plus a 20-second long poll and 15 seconds for settlement, pool cleanup, and process exit: currently 60 seconds. Keep this budget below Fargate's 120-second maximum, and run Node directly as the container's main process so it receives SIGTERM.
Configure Kubernetes terminationGracePeriodSeconds or ECS stopTimeout. The worker guide describes grace and immediate abort.
Run long jobs on Lambda
Review recursive loop detection for jobs with deep child, continuation, or handoff chains.
A job can take longer than one Lambda invocation. Save completed work in durable steps so later attempts replay saved results and continue. Keep each single step short enough to finish within one invocation. Runlane does not predict step length or cap the number of steps. A step that cannot fit needs smaller units or a long-running worker.
Keep step effects safe to repeat. If Lambda stops after an external write but before Runlane saves the result, the next attempt repeats that step. Use the external service's idempotency key or another durable duplicate check.
The handler's budget is the invocation's starting remaining time minus the safety margin. When the margin leaves no usable time, the handler returns every record to SQS for retry without starting delivery. With a positive budget, Runlane uses it to set the handoff time. At the time limit, it aborts with createPlatformTimeLimitError(). See Stop crash loops for how time limits affect the interruption count.
The default safety margin is the smaller of 10 seconds and 20% of the invocation's starting remaining time: 600 ms for 3 seconds, 6 seconds for 30 seconds, and 10 seconds for 15 minutes. An explicit remainingTimeSafetyMarginMs is used exactly. Set it on createSqsLambdaHandler() or in the sqs options of postgresSqsLane() and redisSqsLane().
Keep maintenance running. A killed invocation cannot release its run. Maintenance recovers expired leases, publishes replacement wakeups, and resumes due waits and retries. Without it, a job may remain parked even though earlier steps were saved.
Reserve time for handoff
Set handoffBefore in the lane’s sqs options (or createSqsLambdaHandler()). It hands work to a fresh invocation at the next step boundary after that much time remains. Saved steps are replayed rather than run again. The reserve gives the current step time to finish and Runlane time to save progress and arrange continuation before the host deadline.
When unset, Runlane reserves 25% of the invocation budget (contractDefaults.delivery.handoffReserveFraction). A duration such as handoffBefore: '30s' reserves that much time instead. Choose a positive duration that covers your longest step plus storage and continuation time. A value at least as large as the whole budget makes handoff eligible from the start. Handoff still requires a new saved step in this attempt: handlers without saved steps never stop early for handoff.
Set handoffBefore: false to turn off step-boundary handoff. Work then runs until completion, a caller or task deadline, or the platform time limit. This does not extend the host's execution budget.
Lambda measures this budget after remainingTimeSafetyMarginMs. That separate final safety margin still applies when step-boundary handoff is disabled.