{"success":true,"name":"make-mongodb-writes-idempotent-retries-and-double-clicks-wil","description":"A MongoDB write triggered by requests that can repeat (retry, double-click, replay)","category":"ai-brimind","path":"ai-brimind/make-mongodb-writes-idempotent-retries-and-double-clicks-wil/SKILL.md","file":"SKILL.md","content":"---\nname: make-mongodb-writes-idempotent-retries-and-double-clicks-wil\ndescription: \"A MongoDB write triggered by requests that can repeat (retry, double-click, replay)\"\n---\n\n# Make MongoDB Writes Idempotent — Retries and Double-Clicks Will Happen\n\n## When to use\nProject uses MongoDB, and a write creates or changes data in response to user actions, webhooks, or jobs that may fire twice.\n\n## Example request\nOrder-submit clicked twice → two order documents; a unique index on a client-generated requestId makes the second insert fail loudly. Webhook redelivered by the provider → processing it twice double-charges; store the event id with a unique index and skip seen ones. $inc run again on retry → the counter is now wrong; $inc is not idempotent, but a set-based or event-logged design is. Network timeout after the write succeeded → the client retries a write that already happened; idempotency keys turn the retry into a no-op. Each maps to 'design writes so running them twice equals running them once'.\n\n## Instructions\nAct as a developer who assumes every write will eventually be delivered twice — by an impatient user, a retrying client, or a replaying webhook — and designs so the second delivery changes nothing. For each externally-triggered write on MongoDB: (1) classify the operation: naturally idempotent ($set to a value, upsert by natural key — safe to repeat) versus effect-accumulating ($inc, $push, insert — each execution adds damage), (2) for accumulating writes, install a named safeguard: an idempotency key (client-generated id or provider event id) stored with a UNIQUE INDEX so a duplicate attempt hits a duplicate-key error you catch and treat as 'already done'; or a conditional filter (only update if status is 'pending') making the second run match zero documents, (3) the unique index is the load-bearing part — an application-level 'check then insert' has a race window; the index does not, (4) test it literally: run the handler twice with the same input and verify the data equals one run. If it's unclear whether upstream can retry (webhooks almost always can), assume yes. Only ship the write once double-delivery is proven harmless, and explain which mechanism absorbs the duplicate rather than hoping duplicates won't occur.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1155\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}