When the Server Wins: Offline Conflicts That Don't Lie
A field worker accepts a mission offline while a dispatcher cancels it. Here is how we made the phone tell the truth without retry loops or optimistic lies.
First, the world this happens in
Before the code, here is the setup — the bug only makes sense once you know who is holding the phone.
The product is a field-service app. Think of a company that sends technicians or agents out to do jobs in the field:
- A mission is one job: an address, a set of steps to complete (a photo, a QR scan, a signature, a note), and a status such as
ASSIGNED,IN_PROGRESSorDONE. - A worker is the person doing the job. They use a React Native app on their phone, often with no reliable signal — basements, warehouses, remote sites.
- A dispatcher is the person in the office. They use a web dashboard to assign missions, change priorities, and sometimes cancel a job while the worker is already on the way.
- A sync is what happens when the phone gets coverage back: the actions the worker took offline are sent to the server, and the server sends back the current truth.
Underneath it all there is one Java API that owns mission state, and a SQLite database on the phone that holds a local copy of the missions plus a queue of actions waiting to be sent.
That last part is the tricky bit. The worker and the dispatcher can change the same mission at the same time, with no idea what the other person just did.
The moment things go wrong
Offline-first feels easy right up to that moment.
Picture this. A worker is inside a building with no signal. They tap Accept on a mission that was just assigned to them. At the same moment, the dispatcher cancels that mission from the dashboard. Ten minutes later the worker walks back into coverage, the app syncs, and the server replies:
409 MISSION_INVALID_TRANSITION — currentStatus: CANCELLED
Now what do you show the worker? The obvious move is to treat that 409 like any other failed request and retry it. That loops forever, because the mission will never become acceptable again. The other obvious move is optimistic UI: mark it accepted locally and let the next sync sort it out. That is worse — you have just told someone they have a job they no longer have.
This post is about how we handled it: a durable queue on the phone, a refusal that is recorded instead of retried, and a sentence on screen that the backend can honestly stand behind. Along the way I will show the four rules that came out of it:
- The server's status is the only status.
- Retry what might work; record what cannot.
- Contain a refusal to one mission, not the whole app.
- Say it in human words — and make the backend keep the promise.
The one rule that made everything else simple
The server's status is the only status. A tap never changes the cached mission. It writes one row to a durable queue and asks the sync engine to run.
// src/core/sync/actionService.ts
perform(missionId: string, action: MissionAction, reason?: string): string {
const userId = this.deps.currentUserId();
if (userId === null) throw new Error('perform needs a signed-in user');
const at = new Date(this.deps.now()).toISOString();
const payload: ActionPayload = { occurredAt: at, location: null };
const id = this.deps.uuid();
this.deps.queue.enqueue({ id, userId, missionId, kind: ACTION_KIND[action], payload, occurredAt: at, createdAt: at });
void this.deps.sync.run();
return id;
}No API call from the screen, no onMutate that pretends the write succeeded. Even a successful answer is only applied if it is newer than what the cache already holds:
// src/core/db/missionCache.ts
if (summary !== undefined && summary.version < version) {
tx.update(cachedMissions)
.set({ status, version, summaryJson: JSON.stringify({ ...JSON.parse(summary.summaryJson), status, version }) })
.where(eq(cachedMissions.id, id))
.run();
}That one guard is what makes out-of-order responses harmless. A late answer from an older request cannot roll the UI backwards.
Not every failure deserves a retry
Our first instinct was one retry policy for everything. That is the bug. A timeout means "I don't know what happened, ask again". A business refusal means "I know exactly what happened, and asking again changes nothing".
So the sync engine splits them:
// src/core/sync/actionSync.ts
if (failure instanceof ProblemFailure && !failure.isServerError) {
queue.markFailed(row.id, {
kind: 'rejected',
status: failure.status,
code: failure.code,
currentStatus: failure.currentStatus,
});
void this.deps.refreshMission(row.missionId).catch(() => undefined);
return 'refused';
}A 4xx business error is terminal: the row becomes FAILED with the code and the server's real status attached, and the app re-reads the mission. A 5xx or a network failure still goes back to PENDING with exponential backoff. Rows cut off mid-send during a crash are recovered on startup and retried once, but refused rows are never replayed.
Notice that we keep the error. FAILED is not a dead end — it is the evidence the worker is going to read.
Contain the damage to one mission
A refused action must not become a queue-wide traffic jam. The worker might have three other missions waiting to sync, and a cancelled one should not hold them hostage.
The sync loop keeps a held set of mission ids. When a row fails, only that mission is held; other missions carry on:
// src/core/sync/actionSync.ts
for (const row of queue.unsent(userId)) {
if (held.has(row.missionId)) continue;
const waiting = row.status === 'FAILED' || (!force && row.nextAttemptAt !== null && Date.parse(row.nextAttemptAt) > now());
if (waiting) {
held.add(row.missionId);
continue;
}
// ... send the row; hold this mission on any non-sent outcome
if (outcome !== 'sent') held.add(row.missionId);
}Holding the mission also means later actions for it are not sent against a cancelled mission. The worker tapped Accept, then Start. Only Accept reaches the server; Start stays pending and is released when the worker dismisses the refusal:
// src/core/db/actionQueue.ts — the worker has read the refusal
dismiss(id: string): void {
this.db.delete(queuedActions).where(and(eq(queuedActions.id, id), eq(queuedActions.status, 'FAILED'))).run();
this.changes.notify();
}Explicit dismissal turned out to be important. It is the moment the worker says "I understood", and it is what releases the hold on the rest of that mission's queue.
Don't let housekeeping erase the evidence
Cancelled missions normally disappear from the inbox. But if the mission vanishes, the explanation has nowhere to live. So we keep it visible while a refusal is unread:
// src/features/inbox/inbox.ts
.filter(({ mission, queue }) => !FINISHED_STATUSES.has(mission.status) || queue.refusal !== null)And while a refusal is waiting, the screen offers no new actions for that mission:
// src/features/mission/missionActions.ts
export function offeredActions(mission: { steps: readonly MissionStep[] }, overlay: QueueOverlay): ReadonlySet<MissionAction> {
if (overlay.refusal !== null || overlay.leaving) return new Set();
return availableActions({ status: overlay.status, steps: overlaidSteps(mission.steps, overlay) });
}Otherwise the worker could keep tapping buttons on a mission the server has already taken away.
Say it in human words, and mean it
An error code is not a user interface. We translate the two common late-refusal codes into a sentence that explains what happened:
// src/features/mission/refusalMessage.ts
case 'MISSION_INVALID_TRANSITION':
case 'MISSION_NOT_IN_PROGRESS':
// The dispatcher cancelled while the phone was offline.
if (currentStatus === 'CANCELLED') return { title, body: t('actions.refusedCancelled') };The English string is:
The mission was cancelled while you were offline, so this wasn't recorded. Your dispatcher can see that you tried.
That last sentence is a promise, so the backend has to keep it. When a worker action arrives too late, the refused action is rolled back and a LATE_ACTION_REJECTED event is written in a new transaction — but only while the mission still belongs to that worker. If the mission has been taken away in between, there is nothing to record.
The event also has to survive a lost response. If the phone never receives the 409, it retries the same action with the same device timestamp. We dedupe on actor, device time and the exact event body:
// MissionLifecycle.java
boolean repeat = events.latest(mission.getId(), Limit.of(1)).stream().anyMatch(last ->
last.getType() == MissionEventType.LATE_ACTION_REJECTED
&& Objects.equals(last.getActorUserId(), actor.userId())
&& last.getOccurredAt().equals(actor.occurredAt().truncatedTo(ChronoUnit.MICROS))
&& sameJson(last.getData(), written));
if (repeat) {
return false;
}
new Log(mission, actor).write(MissionEventType.LATE_ACTION_REJECTED,
mission.getStatus(), mission.getStatus(), reason, data);One refused action, one audit event. And deliberately no version bump, because the mission itself did not change — only our knowledge of what the worker tried.
The test that makes me trust it
The whole behaviour lives in one test, because a single scenario exercises every rule at once:
test('a 409 is FAILED with its code and real status, is not retried, and holds only its own mission', async () => {
routeAction(h.backend, 'a', 'accept', () => ({ status: 409, body: {
status: 409, code: 'MISSION_INVALID_TRANSITION', currentStatus: 'CANCELLED',
} }));
// 'a' also has a queued START; 'b' has an unrelated ACCEPT.
h.backend.offline = true;
h.services.actions.perform('a', 'ACCEPT');
h.services.actions.perform('a', 'START');
h.services.actions.perform('b', 'START');
h.backend.offline = false;
await h.services.actionSync.run({ force: true });
expect(refused).toMatchObject({ kind: 'MISSION_ACCEPT', status: 'FAILED' });
expect(held).toMatchObject({ kind: 'MISSION_START', status: 'PENDING' });
expect(h.backend.requestsTo('POST', '/v1/me/missions/a/start')).toHaveLength(0);
expect(h.backend.requestsTo('POST', '/v1/me/missions/b/start')).toHaveLength(1);
expect(status(h, 'a')).toBe('CANCELLED');
await h.services.actionSync.run({ force: true });
expect(h.backend.requestsTo('POST', '/v1/me/missions/a/accept')).toHaveLength(1);
});One refusal, no retry, no leaked actions, another mission still syncs, and the screen shows the server's status. If any of those guarantees break, the test fails.
What I took away
An offline conflict is not a merge problem. It is a trust problem.
- Do not invent success. One durable row, and the server is the only one who changes mission state.
- Classify failures. Retry what might work; record what cannot.
- Contain and explain. Hold only the affected mission, keep the evidence visible, and tell the worker what actually happened in words they would use themselves.
The worker cannot call the dispatcher to ask what happened. The app has to be honest on their behalf.