Skip to content
Darin Larimore
All posts

Idempotent: I learned the word this week

5 min read
On this page
  1. Check before you write
  2. Let the database say no
  3. Generators that run from two places
  4. Imports keyed on the thing itself
  5. Declaring it to a machine
  6. The rule

I picked up the word idempotent this week and had the slightly embarrassing experience of recognising it. An operation is idempotent when running it twice, or ten times, leaves the system in the same state as running it once. The second call is a no-op, not an error and not a duplicate. Once I had the word I grepped my own repositories for it and for the phrases I had been using instead: "safe to re-run", "already-attached files are skipped", "check before insert". It turns out I had been building it in five different shapes without ever naming it.

Check before you write

The one most people meet first is the Stripe webhook. Stripe retries deliveries, and for a single charge it can send both checkout.session.completed and payment_intent.succeeded. My billing portal's markPaid looks for the payment intent before it records anything.

if ($paymentIntentId && $this->payments()->where('stripe_payment_intent_id', $paymentIntentId)->exists()) {
    return;
}

$this->payments()->create([...]);

I wrote about the webhook side of this in Return 200 from webhooks you don't act on. The honest footnote is that check-then-insert has a gap: two deliveries arriving at the same instant can both pass the exists() before either inserts. The column has an index but not a unique one. For a one-person billing portal the odds are acceptable. For anything with real concurrency the database has to be the one saying no.

Let the database say no

My newsletter addon does it the stronger way. Each sendout records one terminal event per subscriber, sent or failed or skipped, and the row has a terminal_key of sendout id plus subscriber key with a unique index on it. The insert just happens, and a unique violation is read as "already recorded".

try {
    $sendout->events()->create([
        'subscriber_key' => $subscriber->getKey(),
        'terminal_key' => $sendout->id.'-'.$subscriber->getKey(),
        'type' => $type,
    ]);

    return true;
} catch (QueryException $exception) {
    if (in_array($exception->getCode(), ['23000', '23505'], true)) {
        return false;
    }

    throw $exception;
}

Returning false matters because the caller bumps counters, and a retried batch must not count the same subscriber twice. Rethrowing anything that is not a unique violation matters more: a real database error has to fail the job so the recipient is retried, not vanish as a quiet "already done". Those two codes are MySQL's and Postgres's integrity violations, so the same code runs against either.

Generators that run from two places

A task-board app I built for a client puts the day's recurring tasks on the board each morning. The generator runs from the scheduler, and it also runs whenever someone opens the tasks page, because the client's box did not always have cron working. That only works if generating the same day twice creates nothing new.

return TaskTemplate::where('active', true)->orderBy('sort_order')->get()
    ->filter(fn (TaskTemplate $template) => $template->isDueOn($date))
    ->map(fn (TaskTemplate $template) => $template->taskFor($date))
    ->filter(fn (GrowTask $task) => $task->wasRecentlyCreated)
    ->values();

Each template resolves its task for a date with a find-or-create on template plus date, and the last filter means the method returns only what it actually created this run. Call it once or call it on every page load; the board is the same.

Imports keyed on the thing itself

Two importers, two approaches. A command that ported my old cron scripts into database rows is keyed on slug: run it again and existing jobs are left alone, with a --force flag to rewrite their fields while leaving enabled untouched. A natural key per row is the cheapest idempotency there is.

The WordPress importer for my ordering portal could not do that cleanly, because one legacy row can become several new ones and the mapping changed between runs. So it is not idempotent, it is restartable: --inspect counts the source rows without touching anything, and --fresh wipes everything the importer created while keeping the admin account, so a run can be repeated against a production snapshot until the numbers match. When you cannot make an operation idempotent, make it trivially safe to start over from zero.

Declaring it to a machine

The newest shape is a contract rather than code. Laravel's MCP package lets a tool declare #[IsIdempotent], and my portal's stop-timer and my feedback tool's update-feedback-status carry it. The client on the other end is an AI, and the annotation tells it that if a call times out it can simply call again. Stopping an already-stopped timer returns the same entry; setting a status that is already set changes nothing. That only holds because the handlers were written that way, so the attribute is a promise I have to keep.

The rule

Idempotency is always about the key. Find the natural identity of the operation, a payment intent, a sendout plus subscriber, a template plus date, a slug, and make the second call with the same key land on the first call's result. Prefer a unique index to an exists() check when two callers could race. And when there is no clean key, give the operation a reset instead and treat "run it again from scratch" as the feature.