Where duplicate writes come from

Imagine a service accepts a request, commits its transaction, and loses the connection before the client receives the response. The client has no proof of the outcome. A retry may be the correct action, but the API needs to identify the retry before it applies the write a second time.

Make the retry contract explicit in the public API, including when a key expires and how conflict responses behave.

Define the scope of a key

The caller generates an opaque key and sends it with the operation. Scope a key to the caller and the endpoint. Save a fingerprint of the request data that affects the result and compare it on each retry. An existing key paired with a different request should produce a conflict the caller can understand.

Situation API response Stored behavior
New key Process the write Persist result and fingerprint
Matching key and fingerprint Replay stored response Preserve the original transaction outcome
Matching key with different payload Return a conflict Preserve the original transaction outcome
Key already in progress Return documented in-progress result Leave ownership with the first request

Store the outcome atomically

When the application writes to a single database, save the key and outcome in the same transaction as the business change. A unique constraint ensures concurrent requests cannot both claim the key.

CREATE TABLE request_outcome (
  caller_id text NOT NULL,
  operation text NOT NULL,
  request_key text NOT NULL,
  fingerprint text NOT NULL,
  outcome jsonb,
  PRIMARY KEY (caller_id, operation, request_key)
);

External work

For side effects that leave the database, record a durable intent and propagate the request key to the receiving service. Document how a caller receives a final result when completion happens asynchronously.

Test the failure cases

Simulate a network failure after commit, two simultaneous requests with the same key, a conflicting payload, and expiry. Check that retries return compatible results and that the data layer records only one operation. See the Queue Relay case study for a worked example.

Back to blog