Shipmind Labs

A lease on an in-flight change: why a crash is not a duplicate

· 9 min read

A write queue on a phone has to record a change as in flight before the request leaves the device. Without that, a crash between the send and the acknowledgement looks exactly like a change nobody attempted, so the next run sends it again. That same early write is also what strands the change: the process dies, the row stays in flight, and no later run can separate a request still travelling from one that died with the process that started it.

One field settles both halves. We keep the moment the attempt started on the row, and we treat that moment as a lease.

The mark comes before the wire#

Our offline write queue for React Native (https://github.com/shipmindlabs/offlinequeue) sends the changes for one entity in a lane. Before that lane touches the transport, it writes the row's new state and waits for the write to land.

typescript
this.#replace(operation.id, { state: "in-flight", startedAt: now.toISOString() });
await this.#persist();

const outcome = await this.#attempt(operation);

The order carries the weight here. #persist is awaited, so the disk learns about the attempt before the network does. If the OS kills the app a millisecond later, the change is stored in the state it was really in. A row left reading pending would be a lie you pay for with a duplicate.

That is a specific shape of wreckage, so we assert it in a test. One of our recovery tests runs the queue until a request is out on the wire, lets the server apply it, kills the process at that instant, and then reads back the bytes the dead run left on the device:

typescript
test("a process killed between send and ack leaves the change stored in flight", async () => {
  const server = ledger();

  const killed = await killedMidUpload(server, await enqueued(), "2026-08-16T10:00:00Z");

  assert.deepEqual(server.applied, [CHARGE], "the server did receive the charge");
  const stored = rows(killed);
  assert.equal(stored.length, 1, "the change is on the device, not only in a dead process");
  assert.equal(stored[0]?.state, "in-flight");
  assert.equal(stored[0]?.startedAt, "2026-08-16T10:00:00.000Z", "the lease the next run reads");
  assert.equal(stored[0]?.idempotencyKey, CHARGE, "and the key it will be repeated under");
  assert.deepEqual(stored[0]?.payload, { amount: 100 });
});

Three things outlived the process: the state, the lease, and the idempotency key the change will be repeated under. Everything the next run does follows from those three.

The start time is a lease#

A start time only earns its place if something decides when it has run out. That decision is a small one, and deliberately blunt.

typescript
#leaseExpired(operation: Operation, now: number): boolean {
  // A row in flight without a start time was written by a version that did
  // not record one. Its age is unknown, so it is reclaimed rather than left
  // to sit in flight for ever.
  if (!operation.startedAt) return true;
  const startedAt = new Date(operation.startedAt).getTime();
  if (Number.isNaN(startedAt)) return true;
  return now - startedAt >= this.#options.leaseMs;
}

Two of the three branches handle rows you cannot read: a missing start time, and one that does not parse. An age nobody can compute gets reclaimed on sight, because the alternative is a row that sits in flight for ever and an entity that stops moving. The third branch is the lease proper, leaseMs, which defaults to two minutes.

Inside the lease, we presume the attempt is alive. A flush that meets a row like that leaves it alone:

typescript
// An attempt inside its lease is still out on the wire. Sending it
// again is the duplicate the whole idempotency story exists to avoid.
tally.retrying++;
return;

That return ends the lane, and with it every row behind this one. Later changes to the same entity stay put, and that is what keeps ordering intact: an edit cannot overtake the creation it belongs to while that creation may still be in the air. The report you get is honest about it. The flush counts the row as retrying and leaves sent alone, and the row still reads in-flight to any screen that asks.

typescript
assert.equal(server.received.length, 1, "an attempt inside its lease is not started again");
assert.equal(report.retrying, 1);
assert.equal(next.queue.outstanding[0]?.state, "in-flight");

Past the lease, recover puts the row back to pending, drops the start time, and leaves the key where it is, so the next flush repeats the request under the same idempotencyKey and a server that upserts on that key applies it once. load runs the same reclaim on the way in, so an app that only starts up does the right thing while the caller stays unaware of the mechanism. recover is there for the caller who wants it on demand, after a long stretch in the background. It persists only when it reclaimed or corrected something, and it tells you how many rows it touched, so a second pass writes nothing.

A reclaim spends no attempt#

The reclaim moves state and deletes startedAt. It leaves attempts alone.

That is not an oversight, and it is the part we would defend hardest in review. attempts drives the backoff and eventually parks a change as exhausted once the queue has tried for long enough. An outcome nobody recorded is not evidence of anything: we do not know whether the server took the change, refused it, or never saw it at all. Charge the change for it and a phone in a crash loop can march a row to maxAttempts and park it in front of the user as failed, while the server was accepting every one of those requests.

The same conservatism runs through the attempt itself. A transport that throws becomes a retry outcome and not a rejection, because a thrown error tells you the client stopped waiting. It says nothing about whether the request arrived. Every exit from in-flight clears the lease, including the parked ones:

typescript
this.#replace(operation.id, {
  state: "failed",
  attempts: operation.attempts + (reason === "rejected" ? 1 : 0),
  lastError: error,
  parkedReason: reason,
  // A parked row that kept its next attempt would promise the screen a
  // retry that is never coming.
  nextAttemptAt: undefined,
  startedAt: undefined,
});

#replace deletes keys set to undefined, so no stale lease survives in storage where a future run could misread it as an attempt in progress.

The lease also covers an acknowledgement the disk refused#

The crash is the case everyone pictures. The quieter one is a device that sent the request fine and then refused to write down what came back. Our write-failure test has the server apply a charge and then fails the very next storage write.

typescript
assert.deepEqual(server.applied, [CHARGE], "the server did apply the charge");
const stored = rows(app.snapshot());
assert.equal(stored.length, 1, "the change is still on the device");
assert.equal(stored[0]?.state, "in-flight", "the disk holds the last thing it was told");
assert.equal(stored[0]?.startedAt, "2026-08-16T10:00:00.000Z", "the lease the next run reads");

The flush rejects, since it cannot report a success it could not record. The last thing the disk was told is in-flight with a lease on it, and the recovery path already handles that state. The same reclaim, the same key, one application on the server. We needed no second mechanism for it, and that is probably the practical test of whether a lease was the right primitive.

A related rule sits on the read side. A storage read that fails is not an empty queue. load rethrows and the queue stays unloaded, so the next enqueue, recover or flush reads again, which keeps a one-row queue from landing on top of everything that survived the last run.

What it costs to run#

The cost is a number somebody has to choose, and the rule runs one way. leaseMs has to outlast the slowest request the transport will allow. Not the slowest you expect, the ceiling the transport enforces. Set it below that and a request that is merely slow gets reclaimed and sent again, and the only thing standing between the user and a duplicate is the server's handling of the idempotency key. It will hold, but you have paid for a round trip you did not need and moved the guarantee off the device.

Set it long and you pay in latency after a crash. An entity whose lane died early in an attempt waits out the rest of its lease before anything behind it moves. Two minutes of a payment looking like it hangs is a support conversation, and a payment applied twice is worse than that. We would rather explain the wait.

One further cost is a clock that steps backwards (a user correcting it, or the network telling the phone the truth). Every stored time is then ahead of the present, and a lease that has not run out for an hour is a queue waiting out a step nobody asked it to serve. A start time in the future gets pulled back to the present, not reclaimed on sight:

typescript
const startedAt = operation.startedAt ? Date.parse(operation.startedAt) : NaN;
if (startedAt > now) changes.startedAt = new Date(now).toISOString();

The attempt may still be on the wire, so the lease runs once from the corrected clock and is not cancelled outright. The conservative reading again.

Close#

Most of this discipline came out of money paths. Our team has spent years on payment processing, ledgering and reconciliation, where a write applied twice is not a cosmetic defect and "the process died, we are not sure what happened" is the normal state of an interrupted request. A lease does not remove that uncertainty. It makes the uncertainty expire at a moment you chose, and it makes a row that outlived its process say so out loud instead of quietly looking like work nobody has started.

Was this useful?

Building something similar?

or email hello@shipmindlabs.com