Backend & Distributed Systems
Idempotent Session Writes with Conflict Detection
A production-minded API design for retry-safe learning session writes, semantic conflict detection, and response-loss recovery.
A client cannot know whether a timed-out write failed before reaching the server or succeeded and lost its response. Retrying a normal POST may therefore create a duplicate session. The implementation described here makes the client generate one request ID when a timer starts and reuse it until that session is acknowledged.
The identifier belongs to the user action
Generating a new UUID for every network attempt defeats idempotency. The ID must describe the logical session, not the HTTP request. It is persisted with the running timer, so reload and retry use the same value.
The database owns the final uniqueness rule:
CREATE TABLE learning_sessions (
id TEXT PRIMARY KEY,
area TEXT NOT NULL,
unit TEXT NOT NULL,
result TEXT NOT NULL,
minutes INTEGER NOT NULL
);An insert uses the primary key as the atomic gate. A preflight lookup alone would leave a race between two concurrent requests.
Duplicate and conflict are different outcomes
If the stored area, unit, result, and duration match, the retry is a success and returns the existing row. If the same ID arrives with a different unit or result, the API returns 409 Conflict. Silently accepting changed semantics would hide a client bug; overwriting the first write would make audit history unreliable.
Validation also rejects malformed IDs and impossible durations before touching storage. Error responses preserve the client payload so a temporary 503 can be retried without rebuilding the session.
Verification must include the lost-response path
The regression suite covers the first write, an identical retry, and reuse of the ID for a different learning unit. A local D1 end-to-end run confirmed that only one row remains after the identical retry and that the conflicting request is rejected. The remaining limitation is multi-region replication: strict global ordering would require a storage system and consistency model designed for that boundary.
Related writing
Backend & Distributed Systems
Capacity-Aware Weekly Planning with Locking
A deterministic weekly planning API that protects deadlines, respects time capacity, limits daily load, and locks accepted plans.
Backend & Distributed Systems
Tombstones for Delete and Reseed Safety
How to permanently delete user-visible records while preventing startup seed logic from recreating the same unwanted item.
Backend & Distributed Systems
Backend API and Data System Design Foundations
A backend design note covering API boundaries, data ownership, validation, transactions, caching, and operational observability.