Prompt
How do I stop duplicate password-reset emails when my background job retries?
Latest observation
To stop duplicate password-reset emails during background job retries, you need to address the root cause of the retries. The solution depends on whether the job is retrying because the email failed to send (transient error) or because the job was enqueued multiple times (user double-clicking or a race condition).
Here is the step-by-step architectural approach to solving this, regardless of your tech stack.
1. Separate Token Generation from Email Delivery
The most common cause of duplicate emails is a single background job that does both: it generates a new database token and sends the email. If the email fails and the job retries, it generates a second token and sends a second email.
The Fix: Split the logic or make the token generation idempotent.
- Step 1: The job checks the database: Does this user already have a valid, unexpired password reset token?
- Step 2: If yes, reuse that exact token. Do not generate a new one.
- Step 3: Send the email using the existing token.
If the email fails and the job retries, it will find the existing token, reuse it, and simply attempt to send the email again without creating duplicate database records or confusing the user with multiple different links.
2. Implement an Idempotency Check (The "Cooldown")
Even if the token is reused, you don't want to spam the user's inbox if the job retries 5 times in a row. Add a "cooldown" check at the very beginning of your background job.
# Pseudo-code for the background job
def send_password_reset_email(user_id):
user = db.get_user(user_id)
# IDEMPOTENCY CHECK: Has an email been sent in the last 15 minutes?
if user.password_reset_email_sent_at > (now() - 15 minutes):
return "Skipped: Cooldown active"
# Generate or fetch token...
token = get_or_create_reset_token(user)
# Send email...
email_service.send(user.email, token)
# Update timestamp
user.password_reset_email_sent_at = now()
user.save()
Note: If the job retries after 15 minutes, it will send the email again, which is usually acceptable behavior.
3. Prevent Duplicate Jobs at the Queue Level (Deduplication)
If the duplicate emails are happening because the user clicked "Forgot Password" twice in rapid succession, you are enqueueing two identical jobs. You need to prevent the second job from entering the queue.
How to do this based on your stack:
- Sidekiq (Ruby): Use the
sidekiq-unique-jobsgem. You can set a unique constraint on the job using theuser_idas the lock key. If a job foruser_id: 123is already in the queue, the second one is silently dropped. - Celery (Python): Use a distributed lock (like Redis) at the start of the task, or use Celery's
worker_deduplicate_successful_tasks/ custom routing to ensure only one instance of a task per user runs at a time. - BullMQ (Node.js): Use the
jobIdoption when adding a job. If you set thejobIdtopassword_reset_${userId}, BullMQ will automatically ignore duplicate additions of the same job ID. - Hangfire (.NET): Use the
DisableConcurrentExecutionattribute or implement a distributed lock usingDistributedLockMutex.
4. Rate-Limit the API Endpoint
The best way to prevent duplicate background jobs is to stop them from being created in the first place. Apply rate limiting to the "Forgot Password" HTTP endpoint.
- Limit the endpoint to 1 request per IP address or 1 request per email address every 60 seconds.
- If a user (or a bot) requests a reset twice in 10 seconds, the API should return a
200 OK(to prevent email enumeration) but do not enqueue the background job the second time.
Summary Checklist
- API Level: Rate-limit the "Forgot Password" endpoint to 1 request per minute per email.
- Queue Level: Use unique job IDs (e.g.,
reset_password_{user_id}) so the queue drops duplicate enqueues. - Job Level: Check if a reset token was already generated for the user before creating a new one.
- Job Level: Check a
last_email_sent_attimestamp to ensure you don't send multiple emails for the same token if the job retries.