Skip to Content
Runlane
Run in production

Run maintenance

Keep schedules, waits, retries, recovery, and pending delivery moving.

Every production deployment needs a clear maintenance owner. Workers execute task attempts. Maintenance moves work that is due, deferred, or interrupted back toward execution. In local development, runlane dev runs maintenance against its own memory store. Local commands need dev running. In tests, use createTestLane() and call runMaintenanceOnce() after advancing controlled time.

For long-running processes, use await runlane.start({ maintenance: true }). For scheduled polling workers, export const handler = runlane.createDeliveryHandler({ maxDuration: '50s' }). For scheduled maintenance, export const handler = runlane.createMaintenanceHandler().

Immediate task dispatch

Eager transport runtimes try queue admission after ready work is committed and after a capacity slot is released. They use the same storage-owned concurrency and ordering checks as maintenance, then publish through the configured transport. Polling lanes keep their existing claim path.

Each capacity-release event makes its own attempt. It admits at most the slot it freed and waits only for the publication it started, so another release cannot keep it open.

Within one runtime, attempts that share capacity or a concurrency key take short turns to pick and reserve a waiting run, so simultaneous releases do not pick the same one. A queue with only per-key limits admits independent keys concurrently; a shared total limit or a queue-wide scan takes a queue-wide turn. Younger turns cannot overtake an older waiting turn that touches the same capacity or keys. A turn ends before any callback or publication, and other queues are not held.

One call that makes work ready on several queues, such as triggerBatch, tries those queues together, so a slow publication on one queue does not delay admission on another. This also applies when some queues have no concurrency limit: their publication does not hold admission on bounded queues. The call returns after every queue it tried has settled. Two runtimes can still pick the same run: storage admits it once, and the other runtime looks again.

Best-effort direct HTTP in_request leaves unrelated capacity refill to maintenance so a finished request does not wait for the next task. It tries explicit children in queue order; a child blocked by older work or capacity waits for maintenance. Named child triggers and child waits also try ready children from earlier bindings, including replayed steps and idempotency reuse. Child readiness uses storage time, so a slow worker clock does not skip an eligible child. Durable broker-backed HTTP adapters keep eager refill.

A full queue waits for capacity. Admission scans are bounded, and a process can stop after commit. Maintenance remains the recovery path for interrupted or unsuccessful dispatch. Failures log bounded_dispatch_failed without failing the operation that already committed.

A slow refill publication does not hold back the committing run's observations, terminal hooks, completion notifications, or explicit children on other queues. Hooks and refill can run concurrently. The caller waits for all work it starts, including started publications when another follow-up fails.

Sleeps, retry backoff, token deadlines, and crash recovery use maintenance timing. Armed schedule fires also wake through delayed transport hints or polling workers. On a bounded queue, admission follows order within each concurrency key, so a run whose sleep, retry delay, or start time has passed can be admitted by a later trigger or released slot on its key or queue. Without such an event, maintenance admits it. Deferred transport dispatch also remains maintenance-owned. Keep your existing maintenance setup.

Run one bounded pass

Use a scheduled function, cron job, or supervised command. Put the bounded call in that entry point, such as src/handlers/runlane-maintenance.ts:

src/handlers/runlane-maintenance.ts
import { runlane } from '../runlane.js'

export const handler = runlane.createMaintenanceHandler()

The handler starts the runtime lazily. Export it directly for Lambda; event and context arguments are ignored. Set tick options when creating the handler. Keep the shared runtime outside the handler to reuse it across warm invocations. For scheduled polling workers, use export const handler = runlane.createDeliveryHandler({ maxDuration: '50s' }) to run maintenance and drain due tasks in one invocation.

One pass can:

  • create runs for due schedules and arm future fires within the look-ahead window;
  • request delivery for due retries and waits;
  • time out due tokens and resume runs linked to terminal tokens;
  • finalize expired attempts and cancellations, and finish saved awaited-child cancellation cascades;
  • expire runs that missed their first-attempt start deadline;
  • recover delivery and publish pending outbox messages;
  • continue cleanup for pruned runs;
  • apply copied run rules, runtime rules for outcomes without a copied rule, and tombstone cleanup.

The result contains the records changed by that pass so you can publish operational metrics. Automatic deletion requires a run rule or a runtime rule. The retention phase always participates and owns maintenance physical cleanup. RunRetention.DeleteImmediately also deletes simple, unheld runs at completion; keep maintenance running for its fallback. Its sweep cadence and bounded work budget are independent of schedule and delivery timing; see automatic retention.

For workloads such as one million runs per week, plan physical-cleanup capacity separately from discovery. See operate retention at high volume for deployment, index and lock behavior, and load-test checks.

Set scheduleLookahead to the invocation interval. The default is contractDefaults.maintenance.scheduleLookahead (1m). A pass creates due runs and arms the next future fire inside that window, within scheduleMaterializationLimit. Arming creates no run and reserves no task key. Set scheduleLookahead: false for due-only discovery.

schedules.create, schedules.update, and schedules.activate also arm pending fires in the write transaction within the arming window. On a polling lane, any next fire is armed. On a transport lane, the window reaches as far as the queue can delay a wakeup, and at least contractDefaults.maintenance.scheduleLookahead. Wakeups and polling workers arm each following fire within the same window, so a schedule faster than the maintenance timer keeps running on time. Activation includes local declarations and skips cron or interval fires that came due while the schedule was paused. After commit, a due fire gets an immediate best-effort wakeup on any transport lane. Publish failure does not fail the write. Maintenance remains necessary for recovery and fires outside this window.

When the queue supports enough delayed delivery, arming publishes a schedule_wakeup hint directly, outside the run-owned outbox. The consumer creates the run at its fire time, then uses ordinary dispatch. Publish failures are logged. A later maintenance pass recovers a lost hint from the armed occurrence record. On transport lanes without delayed delivery, a due maintenance pass or service timer creates the run.

Polling workers also materialize armed fires. See scheduled polling workers for when a delivery handler waits for a fire. Service loops observe armed occurrences for precise timers. Delivery and queue capacity can still delay execution after eligibility. See schedule timing.

Updates, pauses, and deletion before acceptance affect the pending fire. Runlane reads the current definition at fire time. An accepted run keeps its payload and execution policy. A singleton conflict skips that fire permanently.

Set batch limits when one invocation needs a fixed budget. waitTokenTimeoutLimit and waitTokenResumeLimit use their matching contractDefaults.maintenance fields. See defaults.

The result reports waitTokensTimedOut and waitTokenRunsResumed. Keep limits consistent across replicas unless their capacity differs intentionally.

MaintenancePhase.WaitTokenResolution owns timeout and resume passes. Token completion also tries one small resume pass for lower latency.

Completion commits first, so a resume failure cannot undo it. Maintenance remains the recovery owner.

Run-completion waits use the same commit-first rule. Keep MaintenancePhase.DeliveryRecovery enabled so maintenance can resume a parent if a worker stops after saving the child's result. completionResumeLimit bounds this recovery work and defaults to contractDefaults.maintenance.completionResumeLimit. TickResult.completionRunsResumed lists the parents resumed by the pass. Track that count with maintenance errors and the number of parents still waiting on terminal children. Recovery logs run_completion_resume_failed for a failed source, continues with other sources and later phases, and retries the source on a later pass. Unregistered queues are skipped until a maintenance catalog can serve them.

If a pending child finishes while a group wait moves to it, core follows that completion immediately. Large groups use bounded pages. A page that makes no progress stops the immediate pass; maintenance retries the remaining parents later.

MaintenancePhase.RunFinalization also retries saved awaited-child cancellations. cancellationFinalizationLimit separately bounds expired cancellation finalizations and the recovered child positions processed per pass. Cancelling a child waiting on its own children starts another bounded cascade. A parent remains retained until its cascade marker clears.

For triggers with startBefore, keep MaintenancePhase.RunFinalization enabled. Workers refuse a late first start even if maintenance is delayed; this phase records the terminal expired status, releases owned capacity, and wakes joined parents. startExpiryLimit bounds the pass and defaults to contractDefaults.maintenance.startExpiryLimit. TickResult.runsExpired reports the runs finalized by that pass. Storage-polling workers that read past an expired run finalize it the same way, so it does not stay at the head of the runnable index between passes; those runs are not included in runsExpired. See start expiry for deadline and replay rules.

For debounced triggers on transport lanes, keep MaintenancePhase.DeliveryRecovery and MaintenancePhase.OutboxFlush enabled. Recovery creates delivery work once the quiet period ends; no initial outbox message is written. Both phases use storage time, including when the maintenance process's clock is behind.

Recover lost wakeups on transport lanes

On a transport lane, a queued run on an unbounded queue holds exactly one published wakeup. If the broker loses that message, for example when a dead-letter queue is purged or the message passes its retention period, nothing would wake the run. MaintenancePhase.DeliveryRecovery covers this case. Once a queued run has waited resendQueuedRunsAfter (default: contractDefaults.maintenance.resendQueuedRunsAfter, or 15 minutes) since its due time or last update, the pass requests delivery again and the outbox phase publishes a new message.

Set the delay on the runtime:

const runlane = createRunlane({ lane, queues, resendQueuedRunsAfter: '1m' })

Every process sharing runs should use the same value. Each run follows the value of the process that last wrote it. Core saves that policy with the run and derives its recovery index from it. Existing runs keep the default until rewritten. The delay starts from the later of the run's due time and last update; maintenance runs on its own interval.

The same option also sets the next hook-wakeup resend interval on transport lanes. That interval uses the maintenance process's setting when it schedules a replacement, rather than the run's saved writer policy. The maintenance pass owns that next wakeup schedule. This does not change callback retry backoff, which is controlled by hooks.retry.

A claim gives one worker or publisher time-limited ownership in storage. Recovery uses these bounds:

  • A backlog shorter than the delay costs no extra messages.
  • A run whose wakeup is still pending, claimed, or retrying in the outbox is skipped. A slow outbox drain is not a lost message, so it gets no duplicate.
  • Each run is re-requested at most once per delay, because the new request updates the run and restarts its wait.
  • One pass re-requests at most deliveryRequestLimit runs, shared with the other delivery recovery work and ordered by how long each run has waited.
  • A duplicate wakeup is safe. The consumer reads storage first and acknowledges a message whose run is already claimed, finished, or not due.

Bounded queues do not use this path; their expired dispatch reservations are retried by dispatch recovery. Polling lanes do not need it, because their workers read queued runs directly from storage.

When a bounded queue or concurrency key is full, recovery skips other runs that need the same capacity for the rest of the pass. This leaves room to recover work with free capacity. See maintenance limits for how deliveryRequestLimit counts recovery attempts.

Understand duplicate delivery

Keep MaintenancePhase.OutboxFlush running so saved wakeups reach the transport. Several replicas can publish at once. Each handles a limited batch and records which messages it owns. A replica that has lost ownership cannot overwrite another replica's result. If a replica stops, another can take over after its ownership expires.

If an eager publisher stops before sending a saved pending message, maintenance can send it after dispatch.eagerOutboxGrace; see the runtime dispatch options.

The producer keeps ownership of saved eager messages while live observers finish. It can then publish without waiting for grace. Delivery due times and retry delays still apply.

Runlane releases a message still waiting for a publish slot when its age reaches eager grace. This applies even while other batches keep finishing. Age starts when the commit returns. Changes to the system clock do not change this waiting limit.

A successful release makes the message available to maintenance immediately. Calls waiting for a publish slot can then return successfully. The eager publisher gives up that message and will not publish it later.

An eager trigger can reserve publishing ownership when saving its first message. Age and shutdown rules let maintenance take over if publishing has not started.

If saving a message takes too long to confirm, the producer gives up publishing ownership. This prevents a delayed response from making it publish after maintenance has taken over.

Handing a message to maintenance leaves another publisher's work and saved results unchanged. A late observer cannot publish a handed-off message again. Signal, token, and child-completion resumes follow the same rules.

Deferred messages and messages created by maintenance do not wait for eager grace. This includes bounded reservations made by maintenance and due retries. They are available on the next outbox pass. A bounded reservation made by an eager runtime after commit follows the eager rules above.

Closing the runtime also releases saved messages waiting to publish. It stops acquisition at once and drains maintenance and workers concurrently. See runtime shutdown for the close order and admission errors.

If saving the handoff fails, Runlane logs the failure and retains the waiting rows. A later successful eager commit in the same runtime prompts another release attempt. Without a successful write, contractDefaults.maintenance.outboxRetryDelay is the fallback retry delay. During shutdown, a release failure rejects close() after cleanup drains work and closes lane resources. A trigger() still waiting to publish returns its saved run, and maintenance publishes the retained row after its claim expires. If publication already failed, a later release failure is logged without replacing the original error. The saved run remains durable. Pending messages remain recoverable after storage-time grace. Messages already owned by a publisher remain recoverable after contractDefaults.lease.duration. These limits also cover a process that dies before handing off its messages. Keep maintenance running on another replica.

A publish that has started cannot be taken back: its message may already have arrived. The publisher keeps ownership until the transport answers, the provider's timeout fires, or ownership expires and allows recovery. A batch rejected before transport starts hands untouched messages to maintenance.

A retryable transport failure waits for contractDefaults.maintenance.outboxRetryDelay. Eager grace adds no further delay. If Runlane cannot confirm whether a publish or its acknowledgement succeeded, recovery may publish the message again. The transport must tolerate that duplicate.

After publication, Runlane can split fenced settlement writes to fit storage capacity. Splitting settlement never repeats the transport publish.

Run supervised service loops

For an always-on deployment, run the service loop inside a worker process or in its own process. runlane work and createDeliveryWorker() start it by default in the worker process. Opt out with --no-maintenance or maintenance: false when it runs elsewhere. Processes that register the same declared schedule IDs share one schedule owner. Processes with different scheduled tasks each create runs for their own schedules. Shared schedules still create one run per occurrence. Keep maintenance running for every scheduled task. For your own entry point, see the one-process worker in deploy with Postgres polling. A separate entry point such as src/maintenance.ts looks like this:

src/maintenance.ts
import { runlane } from './runlane.js'

await runlane.start({ maintenance: true })
process.once('SIGTERM', () => {
  void runlane.close().catch((error: Error) => {
    process.stderr.write(`${error.message}\n`)
    process.exitCode = 1
  })
})

The example reports retained service failures when shutdown finishes. Pass an onServiceError(error, { phase }) callback in the maintenance options to report each failure as it occurs. With an observer, the application owns the error policy; without one, the first failure rejects close() after cleanup.

Postgres-backed storage coordinates replicas with durable maintenance leases. This allows failover without making every replica run every pass. runlane.close() stops acquisition at once, then drains maintenance and workers concurrently before closing lane resources.

Changing a cron expression or registration order keeps the same schedule owner when the declared schedule IDs stay the same. Other maintenance bands keep one owner per environment.

Every schedule owner also reads runtime schedules, the ones created through runlane.schedules. An owner that lacks the schedule's task logs schedule_task_missing and leaves the fire for a process that has the task. Each process logs the warning at most once a minute per task, until a process with the task creates the run. Replicas with the same declared schedule IDs share one owner even when their other tasks differ. So register each runtime-scheduled task on every replica of at least one such group.

Storage supplies lease time after the ownership row is read. Process-clock skew cannot steal or shorten a live lease.

If refresh fails, that replica stops the band. After expiry, another replica can take over. The old lease token cannot change the new owner's lease.

Shut down maintenance and workers

Call await runlane.close() to stop acquisition and reject new external producer calls at once. Maintenance and running attempts drain concurrently before lane resources close. Attempts can still trigger children and use their task context during grace. Close waits for external producer calls admitted before shutdown, including their writes and observers. Observers of committed events can finish storage reads during draining. Set createRunlane({ shutdownGrace }) to control the observer and direct execution deadline. Observers committed during draining get only the remaining time. Workers inherit this grace unless overridden. It defaults to contractDefaults.worker.shutdownGrace; 'unlimited' removes the deadline. A worker or drain override governs its drain, even when longer than runtime grace. Close waits for the longest active worker grace, including unlimited. A timeout logs observer_shutdown_timed_out and allows cleanup to continue. The log includes the observation type as phase and its run_id when the observation belongs to a run.

Only one set of loops can run per runtime. A second start({ maintenance }) rejects with configuration_invalid. Plain start() remains a no-op after startup. A closed runtime cannot restart.

Timer precision

start({ maintenance: true }) uses timers over armed occurrence records. scheduleLookahead belongs to one-shot maintenance and is not a start({ maintenance: { maintenance: tickOptions } }) option. Services look ahead for work and wake when it is due. This covers sleeps, calendar waits, retry backoff, delayed and debounced triggers, token timeouts, and armed schedules from either source.

Each service loop also has an idle interval. Runlane varies that interval randomly from half to one and a half times its configured value. The default is contractDefaults.maintenance.services.interval. Looking ahead does not increase idle polling. An early timer pass keeps the next idle deadline, so it does not postpone discovery of other work.

When a full pass makes progress, the loop runs another bounded pass without sleeping for the interval. A full pass that makes no progress keeps the normal delay.

Saving a nearby timer can shorten the sleep of a service loop owned by the same runtime. This adds no storage calls to the save. More distant timers are discovered by later passes. Delivery recovery also wakes that runtime's outbox loop when it saves a message to publish.

If a local save overlaps a service loop gaining ownership, the loop checks storage again after the save commits. Its first scan may have finished before the saved work became visible.

On a lane without a native work signal, the runtime wakes its own idle polling workers when it saves work that can run now. This covers triggers, signal and token resumes, child completion, and maintenance delivery requests. Future work still needs polling or maintenance to discover when it is due. Separate runtimes use their lane's native signals or ordinary polling.

A polling slot that sees additional due candidates wakes one idle sibling in its worker. The Postgres polling lane therefore needs only one hint for a burst; its driver sends coalesced hints after commit. A lost hint leaves discovery to ordinary idle polling. See how idle workers wake for the delay bound.

Child completion normally notifies waiting parents immediately. Delivery maintenance retries interrupted notifications.

Wakeups may use the process clock to decide when to check storage. They reuse storage time when it is already available. Maintenance reads storage time before acting, and workers check it before claiming a run. A skewed process clock may delay discovery until the next interval pass. It cannot make work run early.

A timer saved by another runtime after the owner's last pass can wait for the next idle pass. For example, a 30s interval allows up to 45s before discovery. To shorten this wait, run services and workers in the same runtime. Reduce deliveryRecoveryInterval for sleeps, retries, and delayed starts. Reduce waitTokenResolutionInterval for token timeouts.

Storage latency, worker polling backoff, busy workers, and transport delivery can still add lateness. Clock-skew tolerance, eager outbox grace, and ownership checks remain in force.

Monitor progress, not only process health

Alert on:

  • repeated maintenance errors;
  • growing pending outbox work;
  • retrying or released runs past their due time;
  • queued runs on a transport lane that stay queued longer than resendQueuedRunsAfter;
  • pending tokens past their timeout;
  • terminal tokens whose waiting-run count does not fall;
  • expired active leases or runs stuck in cancellation_requested;
  • unstarted runs past startBefore that have not become terminal;
  • run tombstones whose remaining child count does not fall.

A healthy process heartbeat does not prove that each phase is progressing.

In an isolated environment, test one case from each phase you use: a due schedule, retry or release, token timeout and completion, expired lease or cancellation, and pending outbox message. Confirm another replica takes over after the lease owner stops.

Do not catch and discard storage failures. The scheduler or service error observer must see a failed pass so supervision can retry it.

Queue pause and capacity override expiry need no maintenance phase. Admission reads active controls at storage time and reclaims expired slots in bounded probes. Keep delivery recovery running for bounded dispatch backlog, including after resume or a limit increase. See queue operations.

Recover terminal hooks

The existing DeliveryRecovery phase also scans the sparse RunsHooksPending index within its delivery-request budget. It alternates source priority so ordinary wakeup backlogs cannot starve hooks, even with a one-item budget. It republishes lost hook wakeups and expired claims through the existing outbox. A full maintenance pass publishes newly recovered wakeups in its outbox phase, within the claim limit; separate services use their configured intervals. It suppresses duplicates while a wakeup of the same type remains in flight. No separate hook table or maintenance phase is required. A producer-only process may publish wakeups; a worker with the task registered must discover and invoke callbacks. Maintenance also expires unresolved discovery for queues no runtime registers.

Polling workers and drain() read RunsHooksPendingByQueue, one partition per served queue. Task claims and executeNext() make no hook queries.

A polling worker follows these rules:

  • Each queue keeps its own read position, and each pass over a queue only reads callbacks due when that pass began.
  • Queues take turns as slots become free.
  • A queue with no callback this process can claim stops after a fixed number of empty scans. It rests for one interval, then continues from its saved position. Each rest ends on its own timer, so a busy queue cannot keep another queue asleep.
  • An idle worker reads the first entry of each served queue once per interval, in parallel. Empty queues cost no storage-time transaction.
  • The worker does not wait for a callback to finish before it polls again. A running callback holds only its own slot.

drain() works in rounds. Each round shares its slots across queues and skips callbacks this process cannot run. The next round starts after that round's callbacks finish.

Materialize runtime schedules

MaintenancePhase.ScheduleMaterialization handles both local task declarations and stored runtime schedules under one pass limit. Runtime discovery uses SchedulesByDue; deleted-definition cleanup uses the same index and budget. Cleanup removes the one occurrence record and the definition marker together. It never creates runs.

Runtime occurrence/run acceptance, occurrence completion, and nextFireAt advancement commit together. Declared acceptance checks persistent active overrides in that same transaction. A nearby following fire is armed atomically with acceptance. Missing task registrations emit schedule_task_missing at most once a minute per task and leave the occurrence unchanged; bounded continuation lets later definitions progress.

A materialization pass with no schedules uses two bounded empty due-index queries and one transaction to read storage time, with zero point reads or writes. The default combined maintenance pass already reads storage time for its other phases. A pass that excludes schedule materialization makes no schedule query. Enabled declarations outside the arming window add zero override reads. Due declarations and declarations disabled in code share one batched override read per pass; fire-time preparation and the acceptance transaction also check the override. Ordinary workflow execution adds zero schedule reads, writes, or index entries.

Armed fires use ScheduleOccurrencesDue, partitioned by environment and sorted by (fireAt, scheduleId). Each armed record names its task and optional explicit queue. A process skips fires whose task or explicit queue it lacks without spending its runnable result limit. Schedule queues resolve by name to the current registered policy. Discovery logs schedule_queue_missing at most once a minute per missing queue. Writes refresh routing in the same transaction. A due scan disarms an armed declaration when its task is registered but no longer declares that schedule ID. It keeps the last processed fire, so re-adding the schedule cannot replay it. It leaves other catalogs' tasks alone. Keep the task registered for this cleanup; removing the whole task leaves its records in storage. The occurrence record is the recovery owner. Transport hints only improve timeliness; they are not stored run delivery work. A wakeup only signals its schedule: the armed record decides which fire runs, so a hint for a moved fire cannot skip the new one. Polling scans keep their position across passes, so a large backlog of fires that other services own delays an owned fire by a few polls at most.

On this page