Skip to content

Conversation

@sliss
Copy link
Contributor

@sliss sliss commented Jan 2, 2026

Problem

When a task times out and has retryOnTimeoutCount > 0, the expireTimedOutTasks() function creates a retry task by spreading task.toObject({ virtuals: false }). This includes the _id field from the original task, causing MongoDB to throw an E11000 duplicate key error when trying to insert the retry task.

MongoServerError: E11000 duplicate key error collection: db.tasks index: _id_ dup key: { _id: ObjectId('...') }

Solution

  1. Copy the task data and delete the _id field before creating the retry task, allowing MongoDB to generate a new _id
  2. Decrement retryOnTimeoutCount so retries are properly limited (without this, the retry task would have the same count and retry indefinitely)
  3. Reset execution state fields (startedRunningAt, error, result, etc.) so the retry task starts fresh

Changes

// Before (buggy)
if (task.retryOnTimeoutCount > 0) {
  await Task.create({
    ...task.toObject({ virtuals: false }),
    status: 'pending',
    schedulingTimeoutAt: now.valueOf() + 10 * 60 * 1000
  });
}

// After (fixed)
if (task.retryOnTimeoutCount > 0) {
  const taskData = task.toObject({ virtuals: false });
  delete taskData._id;
  await Task.create({
    ...taskData,
    status: 'pending',
    retryOnTimeoutCount: task.retryOnTimeoutCount - 1,
    startedRunningAt: null,
    finishedRunningAt: null,
    workerName: null,
    error: null,
    result: null,
    timeoutAt: null,
    schedulingTimeoutAt: now.valueOf() + 10 * 60 * 1000
  });
}

When a task times out and has retryOnTimeoutCount > 0, the code was
spreading task.toObject() which includes the _id field. This caused
E11000 duplicate key errors when trying to create the retry task.

Also:
- Decrement retryOnTimeoutCount so retries are properly limited
- Reset execution state fields (startedRunningAt, error, result, etc.)
@vkarpov15 vkarpov15 merged commit b6c9112 into mongoosejs:main Jan 2, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants