# WriteConflict: write conflict due to concurrent update on the same document

- **ID:** `data/mongodb-write-conflict-retry`
- **Domain:** data
- **Category:** runtime_error
- **Error Code:** `WriteConflict`
- **Verification:** ai_generated
- **Fix Rate:** 78%

## Root Cause

MongoDB's WiredTiger storage engine detects a write-write conflict when two operations try to modify the same document concurrently, and one of them must retry.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| MongoDB 4.4 | active | — | — |
| MongoDB 5.0 | active | — | — |
| MongoDB 6.0 | active | — | — |
| MongoDB 7.0 | active | — | — |

## Workarounds

1. **Implement retry logic in the application with exponential backoff. Example in Node.js: `async function updateWithRetry(collection, filter, update, retries=3) { for (let i = 0; i < retries; i++) { try { return await collection.updateOne(filter, update); } catch (e) { if (e.code !== 112) throw e; await new Promise(r => setTimeout(r, 100 * Math.pow(2, i))); } } throw new Error('Max retries exceeded'); }`** (85% success)
   ```
   Implement retry logic in the application with exponential backoff. Example in Node.js: `async function updateWithRetry(collection, filter, update, retries=3) { for (let i = 0; i < retries; i++) { try { return await collection.updateOne(filter, update); } catch (e) { if (e.code !== 112) throw e; await new Promise(r => setTimeout(r, 100 * Math.pow(2, i))); } } throw new Error('Max retries exceeded'); }`
   ```
2. **Use optimistic concurrency control with a version field: add a `__v` field to the document and increment it on each update; the update condition includes the current version.** (80% success)
   ```
   Use optimistic concurrency control with a version field: add a `__v` field to the document and increment it on each update; the update condition includes the current version.
   ```
3. **Reduce the likelihood of conflicts by sharding the collection on a field that distributes writes evenly across documents.** (70% success)
   ```
   Reduce the likelihood of conflicts by sharding the collection on a field that distributes writes evenly across documents.
   ```

## Dead Ends

- **** — Unacknowledged writes can silently lose data and still cause conflicts at the storage engine level. (75% fail)
- **** — The operation is atomic but still subject to WiredTiger's conflict detection; a retry is necessary. (50% fail)
- **** — The conflict is not a timeout issue; it's a concurrent modification that must be retried or avoided. (60% fail)
