Make side effects safe to repeat
Stop a rare repeated attempt from writing a row twice, charging twice, or sending twice.
A side effect is anything your task changes outside itself: a database write, a payment, an email, an API call.
Runlane runs every task at least once. In rare cases, a side effect can happen twice. This page shows when that happens and how to make a repeat harmless. Every job system that retries work has the same rule, including graphile-worker and pg-boss.
When a side effect can repeat
attempt 1: step A ✓ saved step B ✓ saved step C ── write succeeds ──✗ worker stops before saving
attempt 2: step A (from storage) step B (from storage) step C runs again ← the repeatA repeat needs bad timing: the side effect succeeds, but the worker stops before Runlane saves that it happened. Then the next attempt runs that code again. This can happen when:
| Cause | Example |
|---|---|
| The worker crashes or is killed | Out of memory, a node is drained, the process is killed during a deploy |
| A deploy outlasts the grace period | The attempt is still running when shutdownGrace ends |
| A serverless function times out | The task runs past the Lambda timeout |
| The worker loses its lease | A long network outage stops it from renewing ownership |
Runlane already limits the damage:
- Saved steps don't run again. A step whose result was saved returns that result from storage.
- Duplicate messages don't create duplicate runs. A worker reads the run from storage before it acts on any message.
- Deploys usually don't cause repeats. A stopping worker lets running attempts finish first.
What's left is one step whose side effect succeeded right before the worker stopped. Runlane can't close that gap alone, because your side effect and Runlane's record of it are not one transaction. An idempotency key closes it.
Use the step token as an idempotency key
Put each side effect in a step. The step's callback gets a token:
await context.step.run('charge', { output: z.string() }, async ({ token }) => {
// token is the same on every attempt of this step
})The token is unique to this run and step. It is the same on every attempt. Pass it to your side effect, so a repeat can tell it already happened.
attempt 1: charge(token = run_step_abc…) ✓ Stripe creates the payment ✗ worker stops
attempt 2: charge(token = run_step_abc…) ✓ Stripe returns the SAME payment, no new chargePick a pattern
| Your side effect | Pattern |
|---|---|
| A write to your own database | Unique column |
| An API that accepts an idempotency key | Pass the token |
| An API without idempotency keys | Record it and accept a rare repeat |
Your own database
Store the token in a column with a unique constraint. A repeat then finds the first row instead of inserting a second one.
create table invoices (
id uuid primary key default gen_random_uuid(),
idempotency_key text not null unique,
order_id text not null,
amount_cents integer not null
);await context.step.run('create-invoice', { output: z.object({ id: z.string() }) }, async ({ token }) => {
const { rows } = await db.query(
`insert into invoices (idempotency_key, order_id, amount_cents)
values ($1, $2, $3)
on conflict (idempotency_key) do update set idempotency_key = excluded.idempotency_key
returning id`,
[token, orderId, amountCents],
)
return { id: rows[0].id }
})db is your Postgres client. The on conflict … do update line makes the second insert return the existing row's id, so both attempts get the same invoice.
An API with idempotency keys
Many payment and messaging APIs accept an idempotency key. Pass the token:
await context.step.run('charge', { output: z.string() }, async ({ token }) => {
const payment = await stripe.paymentIntents.create(
{ amount: amountCents, currency: 'usd', customer: customerId },
{ idempotencyKey: token },
)
return payment.id
})Check how long your provider remembers keys. If a repeat can come later than that, the provider treats it as new.
An API without idempotency keys
Some APIs, such as many email services, have no idempotency key. You can make a repeat rare, but not impossible.
- Put the call in its own step, so it never repeats after its result is saved.
- Keep the step small, so the window between "sent" and "saved" is short.
- For anything that must never repeat, such as money, pick a provider that supports idempotency keys.
Keep these rules
- One side effect per step. Then a repeat redoes only that one effect.
- Keep the step key stable. The token comes from the run and the step key. Renaming the key changes the token.
- Don't do side effects outside steps. Code outside steps runs again on every attempt.
- A new run means new tokens.
runs.rerun()creates a new run on purpose, so its side effects run again. - Pass
context.signalto I/O. The task then stops quickly when a deploy or cancellation asks it to, which makes repeats rarer.
Test it
assertReplaySafe from @runlane/core/testing runs your handler, then replays it, and checks that both passes agree:
await assertReplaySafe(sendWelcomeEmail, { payload: { email: 'ada@example.com' } })Its factory form also wraps your side effects and fails when one runs outside a step or runs again on replay. It checks replay, not a crash in the middle of a side effect. Your idempotency key covers that case. See check one controlled replay.