Lease Expiry for REST Email Verification
Email verification is often implemented as a short sequence: create a token, send a message, and mark the user as verified when the token comes back. That model works until a worker retries, a user asks for a second email, or two API requests arrive at nearly the same time. The failure mode is simple: a verification flow look like one request in the product UI, but it is a distributed workflow in…
Email verification often operates as a simple sequence: generate a token, send an email, and mark the user as verified upon token confirmation. However, this model can break down when retries occur, users request new emails, or multiple API requests are submitted simultaneously. The verification flow appears as one request on the user interface, but it is a distributed workflow in the backend involving the REST API, PostgreSQL, queue, email provider, and browser.
To address this complexity, a lease-based design is preferred. A lease grants a specific time frame for a verification attempt to take action, clarifying which token can modify the authentication state at any given moment. Without an explicit state model, the service starts to rely on timing as business logic, leading to inconsistent behavior.
To implement this design, create a table for email verification attempts with fields such as id, user_id, token_digest, status, lease_expires_at, created_at, and consumed_at. The token should be random and only revealed to the user, while its digest should be stored securely. When a new verification attempt is issued, the previous pending one should be revoked, ensuring only one active lease exists per user. This transition should be handled deliberately and atomically within a transaction to prevent partial workflows.
The verification endpoint should perform a single atomic update, checking the token's status and lease expiration before updating it to 'consumed'. Following this, the user's authentication state should be updated or an outbox event should be recorded for the change. This approach ensures that even if the API fails after updating the token, the user's authentication state remains consistent.
Sending the verification email should be handled separately as an external side effect. The API should commit the verification attempt before the worker attempts to contact the email provider. This separation allows for idempotent retry mechanisms and decouples the verification process from the email delivery process. A scheduled cleanup job can mark old pending attempts as expired and delete old token digests according to the retention policy, keeping the system tidy and efficient.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to