Writing

Making every write safe to repeat, from the phone to the database

Phones retry, people double-tap, queues redeliver. How I make a repeated write change nothing: ids before the request, constraints that refuse duplicates, and dead letters.

· 4 min read· mobile, backend, reliability, postgres

Every write in a real system happens at least once, and sometimes twice. A phone loses signal after the server got the request, so the app retries. Someone taps “add” again because nothing seemed to happen. A worker dies after writing a batch but before acknowledging it, so the queue hands the batch out again.

You cannot stop repeats. You can make them harmless. This is how I do that, from the button on the phone to the row in the database.

A timeout is not a failure

When a request times out, the app does not know whether the server did the work. Retrying a read is always fine. Retrying a write is only safe if the server can tell the retry from a new request, and it can only do that if the request carries an identity.

So the identity is created once, when the person acts, and reused on every retry:

// Illustration: one key per user action, sent with every attempt.
final key = const Uuid().v4();
for (var attempt = 0; attempt < 3; attempt++) {
  try {
    return await api.placeOrder(order, idempotencyKey: key);
  } on TimeoutException {
    await Future.delayed(Duration(seconds: 1 << attempt)); // back off: 1s, 2s, 4s
  }
}

A new key per attempt would defeat the point. The server would see three different orders.

Guard the button, but do not trust it

At Third Wave Coffee, the add-to-cart button turns into a spinner while its request is in flight, so there is nothing to tap twice. In February 2026 I fixed it so that loading state is emitted consistently.

That stops the double tap. It does not stop a retry after a timeout, a second device, or a user who backgrounds the app mid-request. The button is good manners; the key on the request is the guarantee.

Give the write its id before it travels

GoloLink counts clicks on short links. When someone clicks, the redirect service appends the click to a Redis stream and answers with a redirect straight away. A worker reads the stream in batches of 100, writes them to Postgres, then acknowledges them. If the worker dies between the write and the acknowledgement, the batch is handed out again.

The easy mistake is letting the database invent the id. If it did, every redelivery would become a new row. Instead the id is created when the click is queued, and the worker uses it as the primary key:

// Redirect (simplified): the id exists before the click leaves the request.
void enqueueClick({ clickId: randomUUID(), placementId, clickedAt: new Date().toISOString() })
  .catch((err) => console.error("click enqueue failed", err));

// Worker (simplified): a redelivered batch inserts nothing new.
await db.insert(clicks).values(rows).onConflictDoNothing({ target: clicks.id });

Every copy carries the same id and collapses into one row. Writing before acknowledging means a crash costs a repeat, never a loss.

Let a constraint decide

Not every effect is an insert. When a click is a workspace’s first attributed click, the worker records that milestone with an update that only succeeds once (simplified):

update workspaces
set first_attributed_click_at = $1
where id = $2 and first_attributed_click_at is null;

A redelivered batch finds the milestone already set and changes nothing. The real statement returns only the rows it changed, so the analytics event that follows fires once too. In both cases the database, not the application’s memory, decides what counts as a duplicate.

Retry what can succeed, park what cannot

Safe retries are not the same as useful retries. A batch that fails because one row holds a value Postgres will never accept fails the same way every time, and holds back up to 99 good clicks with it.

So the worker sorts failures. Dropped connections, deadlocks and serialisation failures are temporary: the entries stay pending and are picked up again, and entries stuck on a dead worker are reclaimed after a minute. Data errors, like a malformed id, count against the entry. After five failed batches, the batch is retried one row at a time; rows that still fail go to a dead-letter stream with the error, so one bad row cannot block the rest.

What this costs

The guarantee starts at the queue, not at the click. The redirect does not wait for the append, so if the append itself fails, that click is logged and lost: a trade for a fast redirect. The stream is capped at about 500,000 entries, so a worker that fell far enough behind would lose the oldest clicks rather than exhaust Redis memory. And the failure count lives in the worker’s memory, so a restart resets it.

The checklist

  • Create the id when the person acts, and send the same id on every retry.
  • Treat a timeout as “unknown”, not “failed”.
  • Let a primary key or a guarded update refuse the duplicate.
  • Write first, acknowledge second.
  • Retry temporary errors; park permanent ones where someone will see them.
  • Disable the button, but never rely on it.

Written by Advait Bhitkar, mobile engineer. If this was useful, or wrong,email me.