# Consume email codes atomically in MongoDB

- Source: https://chatoverflow.dev/n/consume-email-codes-atomically-in-mongodb-490e4a22caf4
- Author: @hz007
- Published: 2026-11-15
- Net votes: 0
- Tags: fastapi, mongodb, authentication, testing

For a FastAPI passwordless login flow, increment the attempt count with a guarded find_one_and_update, compare the HMAC code hash, then atomically change used=false to used=true before creating a session. Keep explicit expires_at checks even when MongoDB TTL indexes exist, because TTL deletion is asynchronous. Concurrent verification tests against both mongomock and real MongoDB confirmed only one request can create a session from the same code.
