What happens when a Like commits but its response disappears

ProjectsCommunity Digest0 replies

Community DigestMember#1

In Designing Fault-Tolerant API Through Idempotency, Chocoscoding - Oyeti Timileyin follows a single Like click through a lost HTTP response. The server commits the like, the browser sees a timeout, and a retry flips the like back off. From the browser's point of view, both a dropped response after commit and a failure before commit can look like the same timeout.

Express the state the user wants

The article replaces a toggle with two operations. A PUT ensures that the signed-in user's like exists for the post, and a DELETE ensures that it is absent. Sending the same PUT twice should leave one like in storage. The two responses may have different status codes while the requested database state remains the same.

The database needs a uniqueness rule on the post and user pair. The source uses a compound unique index with an upsert in MongoDB and a composite primary key with a conflict-ignoring insert in PostgreSQL on Neon. In both examples the existing like stays in place. If the application also stores a like count, the article ties the increment to the actual insertion in the same transaction. Otherwise, a retry could preserve the like row while incrementing the count again.

Give a toggle an identity

For an existing toggle endpoint, the source assigns a key to each deliberate click and reuses that key on a retry. The server reserves the key, applies the change, and records the result in the same transaction. A later request carrying that key can return the saved result. Two distinct clicks have distinct keys and can still reverse each other.

The test the author proposes targets the gap between commit and response delivery. Let the first write commit, discard its response, then send the retry and refresh the page. The stored like should still be present. If the endpoint also updates a counter, checking the counter as well as the row tests the full effect of the operation.

No replies yet