JavaScript · CODINGNEED
Handle a retried API write without applying it twice
Use stable request keys, compare request meaning, and test lost-response behavior with a downloadable API project.
A timeout does not tell you whether a write happened
A client posts an expense. The server stores it, but the connection closes before the response reaches the client. Retrying the same request without an identity can create a second expense. The client needs to reuse the same request key for that logical operation; generating a new key for every retry defeats the mechanism.
Remember both the key and the meaning
Store a normalized representation of the accepted payload together with the result. If the same key returns with the same payload, return that result. If the amount or category differs, report a conflict. Normalize only properties that the contract declares equivalent. Sorting arbitrary JSON or ignoring a meaningful field can make different operations look identical.
if (saved.has(key)) {
const prior = saved.get(key);
if (prior.fingerprint !== fingerprint) {
// Return HTTP 409: same key, different request.
} else {
// Return the previously stored result.
}
}A Map is a teaching model, not durable coordination
A Map disappears on restart and is not shared between server processes. A production design typically binds the key to the authenticated owner, enforces uniqueness in durable storage, and commits the business write and saved response atomically. Define how long keys remain valid, and how a request in progress is represented.
Test the failure story
Send an identical request twice and expect one stored record. Change the amount while reusing the key and expect a conflict. Restart the teaching server and observe the limit of its memory store. The Expense API download includes these behaviors, a test suite, and an extension plan for persistent storage. Explain its limitations before using any part of it in a live product.
Official reference: JavaScript documentation
Continue exploring
- TypeScript unknown vs any: validate an API response
- Why LEFT JOIN and COUNT(*) can report one order for a new customer
- ROW_NUMBER, RANK and DENSE_RANK: choose a tie policy
Suggest a correction: care@codingneed.com