DEV Community

OwenSullivan9135
OwenSullivan9135

Posted on

Python SMS OTP Evidence: Retention Boundaries for Phone Verification and Backend Countdown

The bill for a phone-verified contact form includes message attempts, retained payloads, indexes, replicas, backups, and the work of investigating a missing support request. Short answer: make the backend authoritative for the SMS OTP resend countdown, commit the contact's support-queue assignment durably, and retain a compact decision record separately from the message body. A disabled resend button cannot establish any of those guarantees.

For an e-commerce support form, the useful question is how much evidence must survive to explain why a verified shopper's request reached the returns queue, stayed pending, or required another delivery attempt. The same separation matters when a phone-login screen sits beside fintech transaction alerts: verification, alert delivery, and support routing need distinct records and distinct meanings of success. A successful login should never be treated as evidence that a transaction alert arrived.

Before proposing a retention policy, quantify its dominant term. Let N be accepted contacts per day, P the retained payload bytes per contact, D the payload retention days, E the decision-record bytes, and L the ledger retention days. The logical storage terms are N × P × D and N × E × L. Payload storage dominates when P × D exceeds E × L. Replication, indexing, and backups add separate terms; without their sizes and billing rules, a universal monetary estimate would be fiction.

As an explicit design exercise, set the payload window to 7 days and the ledger window to 30 days. The payload term dominates whenever P exceeds about 4.29 times E. These are proposed settings, not observed traffic or a legal retention rule. Shortening the payload window moves that term directly; deleting a small dashboard field may accomplish very little.

What should a phone verification backend retain after an SMS OTP login?

Keep the contact request, verification challenge, outbound message attempt, and routing decision as separate entities. Give them identifiers that can be joined during an investigation, but don't let an outbound attempt identifier become the shopper's identity or the contact's routing key. Otherwise a retry can accidentally look like a second support request, especially when the browser submits again after losing the response to an accepted request.

Name the failure.

An ambiguous commit occurs when the backend has accepted work but the caller cannot tell whether it did. The proposed contract is that repeated submission of the same contact identifier returns the existing contact outcome; a new SMS attempt does not create a new contact. Store the selected queue and the routing-rule revision with that outcome, because recomputing yesterday's assignment against today's rules destroys the explanation you meant to retain. For this design, a shopper asking about an order return supplies a contact identifier, an order reference, and a reason code. The routing result might be a returns queue identifier. Keep the free-text description outside the durable routing ledger, and avoid copying the phone number or OTP into every event just because those fields happen to be available in the request. Even references can remain sensitive when other records can resolve them.

Count attempts separately.

The resend transition needs serialization around the challenge record. Inside that boundary, inspect expiry, verification status, attempt budget, and the next allowed resend time; then reserve an attempt and record the dispatch intent before allowing another caller to make the same decision. A read followed by an unrelated write leaves a race in which both callers see permission. The countdown displayed by a Next.js phone-login page is only a view of the server's deadline, so refreshing the page or opening a second tab must not reset the backend's decision.

Define the countdown without promising delivery

Here is an executable Python decision helper for a proposed backend contract. Its attempt limit and timestamps are inputs chosen by the application. It contains no transport calls. It must run against current challenge state inside the serialization boundary described above; calling it alone does not reserve an attempt.

from datetime import datetime
from math import ceil


def resend_decision(
    *,
    now: datetime,
    next_allowed_at: datetime,
    expires_at: datetime,
    verified: bool,
    attempts_reserved: int,
    attempt_limit: int,
) -> dict:
    timestamps = (now, next_allowed_at, expires_at)
    if any(t.utcoffset() is None for t in timestamps):
        raise ValueError("Timezone-aware timestamps are required")
    if attempts_reserved < 0 or attempt_limit < 1:
        raise ValueError("Invalid attempt budget")
    if verified:
        return {"allowed": False, "reason": "already_verified"}
    if now >= expires_at:
        return {"allowed": False, "reason": "expired"}
    if attempts_reserved >= attempt_limit:
        return {"allowed": False, "reason": "attempt_limit"}
    retry_after = max(
        0, ceil((next_allowed_at - now).total_seconds())
    )
    return {
        "allowed": retry_after == 0,
        "reason": "ready" if retry_after == 0 else "cooldown",
        "retry_after_seconds": retry_after,
    }
Enter fullscreen mode Exit fullscreen mode

Return the authoritative deadline and server time alongside the application response so the browser can render a useful countdown. Recheck on every resend request. The rounded-up interval prevents the display from announcing readiness during the remaining fraction of a second, but the backend still makes the final decision from its own clock. Across multiple backend processes, specify which clock supplies those comparisons and test the tolerated disagreement.

The button isn't the delivery boundary.

This helper does not verify an OTP, generate secrets, impose cross-account abuse controls, or guarantee delivery. Specify those separately. In particular, verification state should belong to the challenge and should not advance merely because a transport accepted a send request. A receipt should describe the event it actually reports; reserve stronger business conclusions for evidence that supports them. An uncertain send outcome also needs its own state. If a worker loses contact with the transport after submission, record an unknown outcome rather than silently declaring failure and issuing another message. Reconcile it when evidence becomes available, and define a bounded recovery policy for cases that remain unresolved. More retained SMS bodies cannot settle whether an external handoff happened.

Spend retention on decisions that explain the queue

A compact ledger is useful only if it preserves the decisions an operator will need. For this contact-routing design, retain the contact identifier, challenge reference, routing-rule revision, selected queue, attempt identifiers, transition timestamps, and the evidence used to advance each status. Keep routing acceptance distinct from downstream consumption. If the queue consumer can apply the same contact twice, an accurately recorded producer decision still leaves two support tickets.

Retained material What it helps establish Trade-off and recovery limit
Routing decision and rule revision Why this contact was assigned to this queue Cannot reconstruct omitted free text
Attempt state and correlation identifier Which handoff was attempted and which outcome was recorded An unknown outcome remains unknown without further evidence
Contact body in a short-lived store What the shopper originally described Expands the sensitive data retained and requires separate deletion work
Full payload copied into every log Convenient inspection of individual events Multiplies copies and makes a bounded retention claim harder to defend

The deliberately expensive choice here is retaining enough decision history to distinguish a routing error from a delivery delay. The deliberately cheap choice is avoiding full contact bodies in the ledger. Those choices trade reconstruction detail for a smaller set of records that must be protected and deleted; they don't justify a claim that the remaining system is anonymous.

Email fallback illustrates why evidence needs a precise label. RFC 6376 describes DKIM signatures that associate a signing domain with a message. That signature is not a support-queue acknowledgment or proof that a person read the email. Apple's Mail Privacy Protection guide describes privacy behavior that prevents senders from learning whether a message was opened. Neither source establishes SMS delivery semantics. Keep those limits visible when an operations dashboard tries to reduce everything to a single delivered flag.

Unknown means unknown.

For US and EU traffic, decide the applicable retention, access, and transfer requirements before choosing storage locations and deletion schedules. The two sources listed below do not establish those legal requirements, and the proposed 7-day and 30-day windows cannot stand in for that review. Treat a location label as configuration to verify across the body store, ledger, logs, and recovery copies.

Test deletion before relying on recovery

Test the transitions that could make the evidence lie: concurrent resend requests, a duplicate contact submission, expiry at the exact boundary, a lost response after acceptance, an unknown transport outcome, and a repeated queue delivery. Include a second browser tab. The expected result must say which record changes, which record stays pending, and how many dispatch intents or support tickets may exist. A visually correct countdown is a small part of that test.

Deployment deserves the same skepticism. Keep readers compatible with the previous routing-record schema while changing writers, and preserve rule revisions long enough to interpret retained decisions. Watch the age of pending dispatch intents, unresolved outcomes, rejected resends, and contacts awaiting queue acknowledgment. Review the labels: a graph that merges queued, accepted, and consumed hides the very boundary operators need during an investigation.

Then rehearse recovery after deletion. Restore a recovery copy in an isolated environment and verify that the proposed deletion process also addresses records whose live retention window has expired. Measure the actual retained bytes and outstanding deletion work before claiming that the storage term fell; a deleted live object with retained copies elsewhere does not support that claim.

Deletion has consequences.

The final retention choice is explicit: stop keeping contact bodies beyond their approved window, stop logging OTP values, and stop preserving duplicate payloads for convenience. Keep the minimal routing and attempt evidence for its separately approved window. When a shopper disputes the wording of an old request after the body has expired, that exact text may be unrecoverable; when an old transport outcome remains unknown, the ledger can explain the uncertainty but cannot manufacture a delivery receipt. Accept that loss deliberately, or change the retention decision before promising otherwise.

References

RFC 6376 supports the narrow discussion of domain signatures. The Mail Privacy Protection guide supports the limit on email-open evidence. The retention arithmetic, helper function, state boundaries, and recovery procedure above are proposed engineering choices, rather than claims that either reference specifies an SMS verification system.

Further reading

Top comments (0)