DEV Community

jamesanderson3589
jamesanderson3589

Posted on

Why I Would Keep 2 Records for Email Code Login Fallback After SMS

For a property-management marketplace notifying a seller about a new order, email fallback for a login OTP when SMS is unavailable has a bill beyond message delivery: stored authentication state, logs, backups, and the work of reconstructing a failed login. Consider an explicitly hypothetical retention model: one challenge per recovery, one audit event per challenge, and the same daily volume for both. Keeping audit events for 30 days and active challenges for 10 minutes produces 4,320 retained audit events per active challenge at steady state. That is a record-count ratio, not a storage-price estimate; actual byte sizes and message volume decide which bill dominates. The first lever to examine is the audit retention window, because shortening the already brief challenge lifetime barely changes that particular inventory.

TL;DR: If the existing login form can accept an email verification code, that is the least complex fallback I would evaluate when SMS is unavailable. Use an already verified address, keep the order notification separate, and make a successful challenge consumable only once. A magic link is an alternative interaction with different browser and URL-exposure risks. Neither choice makes email equivalent to a stronger authentication factor.

The two records in my proposed design are a short-lived challenge and a credential-free audit event. They have different purposes and retention rules. This is a design choice, not a report of a production deployment. For a seller who needs to open a new order, the useful outcome is access under the account's established assurance policy; a delivered notification alone proves very little about that outcome.

What actually needs to survive a failed delivery?

An order notification says that work is waiting. A login challenge grants a way to prove control of an authentication channel. Combining them creates an awkward retention problem: the business may need the order history after the credential should have expired, while mail archives and notification logs can preserve whatever was placed in the message. Keep the notification useful without turning it into a credential archive. A normal sign-in destination is enough for the notification; issue a challenge through the login flow.

That separation also improves diagnosis. A marketplace can record that the order event entered its notification workflow, that a send attempt was accepted by its transport interface, and that a login challenge was later redeemed, but those are separate observations. Transport acceptance does not establish that a person received the message or completed sign-in. Calling every accepted send a successful recovery hides the failure the seller actually experiences.

Delivery isn't authentication.

For the illustrative calculation above, let daily challenge volume be V and the average stored record sizes be C for a challenge and A for an audit event. The retained bytes are approximately V × C / 144 plus 30 × V × A, assuming uniform arrivals and prompt removal. Under those assumptions the audit term exceeds the challenge term whenever A exceeds C / 4,320. Real cleanup delays, indexes, replicas, backups, and nonuniform arrivals change that estimate; measure them before treating a record ratio as a capacity forecast. The example deliberately excludes message prices, since there is no rate sheet or measured delivery workload here.

The change that moves the modeled term is keeping fewer days of detailed events or making each event smaller. Neither requires preserving a usable credential. A compact outcome event can retain an opaque challenge identifier, a channel, timestamps, a policy version, and a coarse result, while leaving out the code, link token, rendered message, and full recipient address. Even those identifiers need a retention decision if they remain linkable to a seller.

Should email fallback use a verification code when SMS is unavailable?

The cited NIST authenticator guidance prohibits email for out-of-band authentication and treats authentication over the public switched telephone network as restricted. Those boundaries matter more than a reassuring delivery dashboard. An application claiming alignment with that guidance cannot relabel email recovery as compliant out-of-band authentication merely because SMS is temporarily unavailable. The cited edition is a specific technical reference, not a blanket US or EU legal rule.

For an account policy that explicitly permits email recovery, a code fits an existing entry form and can be entered on a different device from the one receiving the message. A magic link transfers a bearer secret through a URL and can send the seller into a different browser context. Both require unpredictable secrets, bounded validity, guessing controls where relevant, and server-side enforcement of single use; neither establishes that a second independent factor exists just because it arrived through another channel.

Decision Email verification code Magic link
Existing login form Seller enters the code in the pending flow Callback must resolve the pending flow and browser context
Secret exposure to exclude Code in message bodies, support tickets, or application logs Token in URLs, request logs, or copied links
Accidental activation Reading the message does not submit the code Design the landing page so an automated fetch cannot complete authentication
Concurrency boundary Atomic challenge consumption Atomic token consumption
Evidence after deletion Outcome metadata, without the original code Outcome metadata, without the original token

My preference for a code is conditional: the form already exists, the seller can use it, and email recovery is allowed by the account policy. If the interaction instead needs a link, require deliberate completion in an appropriate login context and test that journey. This is an interface trade-off, not an assurance upgrade.

US and EU deployments need the same technical distinction between notification delivery and authentication. Regional handling requires a separate review of recipient-data retention, processing locations, support access, and the applicable account requirements. These two technical references do not establish regional legal compliance, and the seller's location alone does not settle the authentication policy.

Make consumption durable before deleting the evidence

From a storage perspective, the difficult boundary is between a credential being checked and the resulting login being authorized. Two workers must not both validate an unused challenge, independently mark it used, and each authorize a session. Treat expiry, attempt limits, revocation, and consumption as part of the same authoritative decision; caching a stale unused status is an invitation to replay.

A record becoming invisible in an application query is also different from its bytes disappearing from replicas or backups. Expiry must deny redemption even when physical cleanup is delayed. Restoration procedures must preserve the rule that an old challenge cannot become usable again. If the consumed state and the session outcome live in separate systems, define what a crash between those writes means before shipping the flow. A retry should have a documented result, including when the seller must start again.

The following Python sketch makes the policy outcomes explicit. Its repository method is an interface contract, not an implementation of transaction isolation or a complete authentication endpoint. The storage implementation must enforce the whole operation atomically against authoritative state. For short codes, protect the stored verifier with a server-held key; an ordinary unkeyed hash leaves a small code space open to offline enumeration if the records leak.

from enum import Enum
from typing import Protocol


class Outcome(Enum):
    ACCEPTED = "accepted"
    REJECTED = "rejected"
    EXPIRED = "expired"
    EXHAUSTED = "exhausted"


class ChallengeRepository(Protocol):
    def verify_and_consume(
        self,
        *,
        challenge_id: str,
        flow_id: str,
        candidate: str,
    ) -> Outcome:
        """Atomically check binding, expiry, attempts, and the keyed verifier.

        Use authoritative time. Count failed guesses. Consume on success.
        Already consumed or revoked challenges must return REJECTED.
        """
        ...
Enter fullscreen mode Exit fullscreen mode

Don't log candidate.

The flow binding matters because possession of an order number should not let a caller select another seller's recovery challenge. A fallback request must also avoid becoming an unauthenticated account-enumeration interface. Keep public responses appropriately nonspecific while preserving enough internal outcome detail to investigate the affected flow under controlled access.

Resends deserve their own decision.

If a new challenge revokes an old one, a late message will contain an unusable credential; if multiple challenges remain active, the account has a larger acceptance surface. Document which behavior the application promises and test delayed delivery against it. Never let the arrival order of SMS and email messages silently determine the account's policy.

Exercise the path that loses the message

The relevant deployment test begins with a committed new-order event and ends with the seller either reaching the authorized order view or receiving a clear recovery outcome. Test transport rejection, a timeout with an unknown send result, delayed mail, exhausted guesses, expiry, and two concurrent redemption attempts. For a magic link, include an automated fetch before the seller clicks and a click in a different browser context. These are proposed test cases, not measured incident frequencies.

The unknown send result is especially easy to mishandle. Retrying a timed-out request can create duplicate messages, and a provider's acceptance response still does not justify granting a session. Keep message-attempt identifiers separate from challenge identifiers so retries can be investigated without confusing two messages with two successful authentications.

Message rendering belongs in the test path too. The Mustache manual distinguishes escaped variables from unescaped forms; inserting an untrusted seller name through an unescaped form can change an HTML email's markup. Escaping is context-specific, so do not assume that HTML escaping makes a value safe to place inside an authentication URL. Keep seller-controlled text outside credential construction, and inspect the rendered text and HTML variants without recording live secrets in test artifacts.

A small set of observations is enough to start: challenge issuance, transport outcomes, expiry, rejection, and redemption. Measure time to redemption separately from time to transport acceptance. Restrict raw identifiers in telemetry, then check during deployment that redaction covers both the email-code and link paths. A release that changes the event schema should make its policy version distinguishable in retained records, or later investigations may compare incompatible outcomes.

Decide what an investigation may no longer recover

I would keep the proposed challenge only for its operational validity and cleanup needs, and retain the separate audit event for a documented investigation window. The 10-minute and 30-day values above are modeling inputs, not universal retention recommendations. Choose actual windows from the account's assurance policy, observed delivery behavior, investigation needs, and applicable obligations.

Then delete deliberately.

Stop retaining expired credential material, rendered authentication messages, and full token-bearing URLs in routine diagnostic storage; give backups and exports a defined lifecycle too. Retaining a verifier after expiry buys little diagnostic value if the question is whether the server accepted the challenge, yet it increases the material that has to be protected.

There is a cost to that choice. Once detailed message content and transport metadata are gone, support may be unable to reconstruct precisely what the seller saw or distinguish a late delivery from an overlooked message. Outcome events can establish what the service recorded, but they cannot recreate a deleted inbox. Accept that limit explicitly rather than promising complete forensic reconstruction from a deliberately small record.

For this seller workflow, my decision is an email code when the existing form and account policy support it, atomic redemption for either interaction, and separate retention for order history and authentication state. If the required assurance excludes email recovery, retain that boundary and provide a recovery path that meets it. Reliable notification delivery should help a seller reach a legitimate login; it should never choose the assurance level on the seller's behalf.

Further reading

References:

Top comments (0)