# Idempotency: the property that stops integrations doing things twice

> Networks sometimes lose replies, so a reliable integration has to retry, and each retry can produce a duplicate. Idempotency makes the retry safe, but it has to be designed into the receiver, which costs far less at the start than after the first double payment.

Systems integration · Technical deep dive · November 17, 2026 · 8 minute read · By Nabil Ahmed
Canonical: https://farside.works/insights/idempotency-explained/

![The lunar surface near 55°S, 6°E, lit by a low Sun with night falling across one side.](https://farside.works/content/images/2026/11/idempotency-explained.webp)

When the connection drops before a reply arrives, the caller cannot know whether its request was lost on the way out or the reply on the way back, because the two cases look the same from its side. It can give up and risk the work never happening, or it can send the request again and accept that the work may now happen twice.

Reliable integrations resolve this by retrying, and most message brokers make the same choice for consumers by offering at-least-once delivery, under which a message can arrive more than once. Duplicates are a normal consequence of refusing to lose work, so the question that matters is whether the receiver deals with them correctly.

An operation is idempotent if performing it several times has the same effect as performing it once, and that property is what makes a retry safe. We think idempotency belongs in the design of every write that crosses a system boundary, and that it is the receiver's job, because only the receiver can know whether it has already seen a given request.

## In brief

- A caller cannot distinguish a lost request from a lost reply, so an integration that refuses to lose work has to retry, and one that retries will sometimes deliver the same request twice.
- Idempotency is a property of the receiver, meaning that a second copy of the same request leaves the system in the state the first copy produced.
- An idempotency key protects anything only when it is recorded in the same database transaction as the business change it guards.
- What platforms call exactly-once behavior is at-least-once delivery combined with an idempotent receiver, and it ends at the boundary of the system that provides it.
- Idempotency needs deliberate replay tests, because the failures that expose its absence are rare in test environments and routine in production.

## Why duplicates are unavoidable

Consider one payment instruction sent from an order system to a finance system. It can fail on the way there, inside the finance system or on the way back, and only the first two mean no payment was made, so a failure on the return leg leaves a payment the order system cannot confirm.

Queues and event streams work the same way, because a consumer that crashes after doing the work but before acknowledging the message will, correctly, receive it again. Acknowledging first loses the message whenever the crash comes before the work, and brokers redeliver because lost work is usually worse than repeated work.

Some platforms advertise exactly-once processing, which can be accurate within their own boundary, since a stream processor can commit its output and its read position together. That guarantee stops as soon as the processing calls an external system such as an ERP or a payment provider, because the call can be repeated like any other, so it is safer to regard exactly-once as something you build by making the receiver idempotent than as a platform feature.

## Operations that are naturally idempotent

Some operations can be repeated safely without extra machinery, and a good design puts as many writes as possible in this group.

- **Setting a value is idempotent, whereas changing it by an amount is not.** You can apply "set the order status to shipped" five times and get the same result, while "add 10 to stock on hand" changes the total on each run.
- **Creating a record under an identifier the caller chooses is idempotent.** If the caller supplies the order number, the receiver can recognize a repeated create as the same order, whereas a receiver that generates the identifier itself will treat the repeat as a second order.
- **Deleting by identifier is idempotent in effect.** A second delete finds nothing left to remove, so the end state matches the one after the first delete.

The HTTP specification defines GET, PUT and DELETE as idempotent and POST as non-idempotent, but that describes what the methods are meant to mean and does nothing for a PUT handler of yours that also appends a ledger row each time it runs.

When a write cannot be made naturally idempotent, as is usually the case for anything that creates a financial entry, sends something to a person or calls a third party, an explicit mechanism is needed.

## How an idempotency key works

An idempotency key is a unique value chosen by the caller to identify one intended operation and sent again, unchanged, with every retry of it. Several public payment APIs accept such a key in a request header, and the pattern works as well between internal systems.

The receiver stores the keys it has already seen in a table.

```sql
CREATE TABLE idempotency_keys (
  caller_id       text        NOT NULL,
  idem_key        text        NOT NULL,
  request_hash    text        NOT NULL,
  status          text        NOT NULL,   -- 'in_progress' or 'completed'
  response_code   int,
  response_body   jsonb,
  created_at      timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (caller_id, idem_key)
);

-- Inside ONE transaction with the business change:
INSERT INTO idempotency_keys (caller_id, idem_key, request_hash, status)
VALUES (:caller, :key, :hash, 'in_progress')
ON CONFLICT (caller_id, idem_key) DO NOTHING;
-- 0 rows inserted: this key has been seen. Read the stored row and
--   return the stored response, or report "still in progress".
-- 1 row inserted: do the business write, store the response,
--   set status = 'completed', then COMMIT.
```

Five details decide whether this holds up when things actually fail.

**The key and the business change commit together.** If the key goes into one transaction and the invoice into another, a crash in between leaves either a key without an invoice, so the retry is wrongly ignored, or an invoice without a key, so the retry creates a second invoice, and a key kept in a separate cache has the same weakness. The check is atomic only because the primary key constraint lives in the same database as the business data.

**The key is scoped to the caller.** Two callers can produce the same value by chance, so scope the key by caller identity, and by operation type too when one caller performs several kinds.

**The request is fingerprinted.** The receiver keeps a hash of the request body next to the key, and the same key arriving later with a different body means the caller has a bug, so the receiver returns an error.

**Concurrent retries are handled.** When two copies of a request arrive together, the insert decides which proceeds, and the other gets a clear "in progress" response and retries later, so it neither blocks indefinitely nor repeats the work.

**Keys expire after a set period.** Keep them longer than any caller's longest retry window, allowing for someone replaying a message by hand from a dead-letter queue days later, and then delete them, because a key table that is never pruned grows until it becomes an operational problem of its own.

The caller has one rule too, which is to generate the key once per business intention and store it before the first attempt, since a fresh key on each retry makes the receiver see every attempt as a new operation.

## The same mechanism for message consumers

For a consumer of events the equivalent is a table of processed message identifiers, often called an inbox. The handler inserts the message identifier and applies the business change in one transaction, so that a redelivered message hits the unique constraint and is acknowledged with no further work.

That depends on every message carrying a stable identifier assigned by the producer. A broker-assigned offset is insufficient when the producer may publish the same event twice, which it will do if it also retries.

Ordering is a closely related problem. If both "address changed to A" and "address changed to B" can be redelivered, deduplication alone will not prevent the older event from overwriting the newer one, and the usual remedy is a version number or event timestamp on the record, with the consumer discarding anything older than what it holds. These costs belong to the wider trade-off discussed in [event-driven architecture: what it gives you and what it costs](https://farside.works/insights/event-driven-architecture-tradeoffs/).

## The invoice that posted twice

Take a mid-size distributor whose order management system posts an invoice to the ERP whenever a shipment is confirmed, over HTTP with a thirty-second timeout and three retries.

At month end the ERP is under load and one invoice post takes forty seconds, so the order system times out and retries. The second attempt returns success, but the first had also completed, and the customer receives two invoices for one shipment. Finance finds the duplicate at reconciliation and raises a credit note by hand, which happens a few times every month end under load and never in the test environment.

Raising the timeout only narrows the window in which a duplicate can happen, and closing it takes three changes.

1. The order system derives the key from the business event, in this case the shipment confirmation identifier, so every retry and any later manual replay carries the same value.
2. The integration layer in front of the ERP stores the key together with the ERP document number, and where the ERP has an external reference field with a uniqueness check, that field carries the key so the ERP itself refuses the duplicate.
3. When a duplicate arrives, the integration returns the original document number with a success status, so the caller gets the same result from a replay as from a first attempt.

If the downstream system has no uniqueness check, the fallback is to query for a document with that reference before writing and to create one only when none exists. A small race remains between the check and the create, so this should be paired with a reconciliation report that searches for duplicates by reference, and the design document should record that the gap is still open.

Success would be measured by duplicates found at reconciliation and the number of manual corrections. Work at this kind of boundary is central to [systems integration](https://farside.works/services/software-engineering/systems-integration/), and designing it in at the start costs far less than retrofitting it once finance has stopped trusting the interface.

## Where it gets hard

**Side effects outside the database.** An email, a text message or a call to a third party cannot be part of your transaction. If the third party accepts an idempotency key, pass yours on to it; if it does not, record the intent to send in the same transaction as the business change and let a separate process do the sending, which limits the risk of a duplicate to that one sender. Multi-step versions of this problem are covered in [long-running workflows: state, retries and compensation](https://farside.works/insights/long-running-workflows/) and, more broadly, under [workflow orchestration](https://farside.works/services/process-automation/workflow-orchestration/).

**Keys that mean too little or too much.** A key per HTTP attempt protects nothing, and a key per customer per day blocks a legitimate second order, so the key should identify exactly one business intention.

**The key is part of the contract.** Consumers need to know that a key is accepted, how long it is remembered and what a replay returns, and that information belongs in the published interface as part of ordinary [API design](https://farside.works/services/software-engineering/api-engineering/).

## What to check this week

- List each write that crosses a system boundary and note what happens if it is delivered twice, and where the answer is that it cannot be delivered twice, name the mechanism that prevents it.
- Confirm that each retrying caller stores its key before the first attempt and sends the same key every time.
- Check that each receiver records the key under a unique constraint in the same transaction as the business change.
- Check that every message consumer has a producer-assigned message identifier and a processed-message check.
- Add replay tests that send each write request twice, deliver each message twice and kill a consumer between the work and the acknowledgement, and after the first pass keep them in your [quality engineering](https://farside.works/services/software-engineering/quality-engineering/) baseline so they go on running as the integrations change.
- Review three months of manual corrections in finance and operations, since duplicates people have fixed by hand show where idempotency is missing.
