WriteConflict data runtime_error ai_generated true

WriteConflict:由于对同一文档的并发更新导致写入冲突

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

ID: data/mongodb-write-conflict-retry

其他格式: JSON · Markdown 中文 · English
78%修复率
84%置信度
1证据数
2023-09-05首次发现

版本兼容性

版本状态引入弃用备注
MongoDB 4.4 active
MongoDB 5.0 active
MongoDB 6.0 active
MongoDB 7.0 active

根因分析

MongoDB 的 WiredTiger 存储引擎检测到写入-写入冲突,当两个操作试图同时修改同一文档时,其中一个必须重试。

English

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.

generic

官方文档

https://www.mongodb.com/docs/manual/core/transactions-production-consideration/

解决方案

  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'); }`
  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.
  3. Reduce the likelihood of conflicts by sharding the collection on a field that distributes writes evenly across documents.

无效尝试

常见但无效的做法:

  1. 75% 失败

    Unacknowledged writes can silently lose data and still cause conflicts at the storage engine level.

  2. 50% 失败

    The operation is atomic but still subject to WiredTiger's conflict detection; a retry is necessary.

  3. 60% 失败

    The conflict is not a timeout issue; it's a concurrent modification that must be retried or avoided.