Prevent duplicate runs
Use idempotency for repeated requests and singletons for overlapping work.
Runlane has three tools to prevent duplicate runs. They solve different problems.
| Key | Question it answers | Result on conflict |
|---|---|---|
runId | “Does this exact run already exist?” | Return it for the same task, in any status |
idempotencyKey | “Have I already accepted this logical request?” | Return the active or retained owner |
singletonKey | “Is work for this resource already active?” | Reject, or return an active run of the same task |
Define keys from stable business identity
import { task } from '@runlane/core'
import * as z from 'zod'
const env = z.object({ CUSTOMER_API_URL: z.url() }).parse(process.env)
export const refreshCustomer = task({
id: 'customers.refresh',
schema: z.object({ customerId: z.string() }),
idempotencyKey: ({ customerId }) => `refresh.${customerId}`,
idempotencyKeyTTL: '24h',
singletonKey: ({ customerId }) => `customer.${customerId}`,
async run({ customerId }, context) {
const response = await fetch(
new URL(`/customers/${encodeURIComponent(customerId)}/refresh`, env.CUSTOMER_API_URL),
{
method: 'POST',
signal: context.signal,
},
)
if (!response.ok) throw new Error(`Customer API returned ${response.status}`)
},
})In this example:
- repeated refresh requests for one customer return the same idempotency owner for 24 hours after it succeeds.
- different requests cannot overlap while the same customer singleton is active.
Idempotency keys are scoped by the Runlane environment and task. Singleton keys are scoped by the environment only, so two tasks that use customer.123 block each other. That is useful for one active operation per customer. Add the task name, such as customers.refresh.customer.123, when only one task's runs should compete. Use a stable domain id. Do not use the current time or a random value when you want deduplication.
Choose a run identity
Pass { runId: 'fulfill.order_123' } to trigger() when one ID should name one run until pruning finishes. Repeats for the same task return returned_existing, including failed runs. Use runs.retry() to retry a failed run deliberately. A pruned run is hidden while cleanup removes its records. Its ID rejects with a retryable run_id_conflict until cleanup finishes. Batch items with the same ID and task share one run; an item for another task rejects. Idempotency keys differ: failures release their ownership so another trigger can create a new run.
Run IDs are unique across tasks in an environment. Reusing an ID for another task throws non-retryable run_id_conflict. The same error applies when the call's live idempotency key belongs to a different run, whether or not the requested ID exists.
Understand idempotency retention
trigger() returns an outcome:
createdmeans it stored a new run.returned_existingmeans the run ID already existed for this task, the idempotency key already had an active or retained owner, or the singleton policy returned an active run of the same task.
idempotencyKeyTTL controls terminal retention. It requires an idempotency key. If omitted, Runlane uses contractDefaults.idempotency.defaultTTL; see defaults for its current value. Set IdempotencyKeyTTLMode.Active from @runlane/core to keep ownership only while the run is active. An operator can reset a terminal owner sooner, and manual runs.prune() removes its ownership.
The TTL does not expire an active owner. Failed runs release idempotency ownership immediately, regardless of TTL. Other terminal owners follow their captured TTL. A later trigger can reuse a failed run's key and create a new run.
Automatic retention keeps a live idempotency key after deleting its run. A repeat trigger within idempotencyKeyTTL returns returned_existing with the saved final RunSnapshot, without creating or executing work. During that window, runs.get() and runs.findCurrent() still return undefined for the deleted run. If the encoded owner and snapshot exceed contractDefaults.storage.maxRecordBytes, retention keeps the run until the key expires. Failed runs and IdempotencyKeyTTLMode.Active release the key when the run ends. Manual runs.prune() removes the key; idempotencyKeys.reset() also clears a saved result.
A caller-chosen runId has no TTL. Once deletion finishes, the ID is free again and the same trigger can execute new work. Use an idempotencyKey when you need a promised deduplication window.
Understand singleton ownership
A singleton protects only active work. Runlane releases it when the owning run becomes terminal.
singletonConflict chooses what a raw trigger does when the key is held:
SingletonConflict.Rejectkeeps the default behavior: reject with a retryablestorage_conflictof kindsingleton_key.SingletonConflict.ReturnExistingreturnsreturned_existingwhen the holder belongs to the same task. A holder from another task still rejects.
Import SingletonConflict from @runlane/core or @runlane/contracts. Set the policy on a task or in trigger options. The call option overrides the task policy. The default is contractDefaults.run.singletonConflict.
The holder is any run with this key that hasn't finished, including a delayed runAt run and one waiting for cancellation. The returned run can have a different ID than the runId you passed, so check result.run.id when you store it.
Returning a singleton keeps its first payload and settings. It creates no run, history, delivery, or outbox records and claims no new idempotency or debounce key. Run ID, debounce, and idempotency decisions still take precedence. A new debounce window that returns a singleton does not acquire that window's key.
This policy applies to trigger(), raw batch items, raw child triggers, and runNow(). runNow() returns the existing run without executing it. Schedules, linked retries and reruns, and named child steps still reject singleton conflicts, even when their options set ReturnExisting.
Use a singleton for resources that must not update concurrently. To let every request wait its turn, use a concurrencyKey on a queue with concurrency: { perKey: 1 }; see limit concurrency.
Override keys at a trigger boundary
runlane.trigger() and context.trigger() accept key overrides. Use them when the caller owns the request identity. Keep task-level resolvers for rules that apply to every caller.
Do not set different key rules in producers and workers. Register the same task definition everywhere.
Verify the policy
Test:
- the same idempotency key returns one run.
- a retained owner remains until the expected TTL or reset.
- a singleton conflict is visible.
- singleton ownership is released at terminal state.
- different keys can proceed independently.
- invalid resolver output creates no partial run.
Use limit concurrency for shared capacity and prune old runs for retention.