DEV Community

DonovanPierce4012
DonovanPierce4012

Posted on

How to Contain Login Retries — SMS OTP, Authenticator Apps, and Bounced Email Codes

Keep students able to sign in by suppressing confirmed invalid email recipients before another login code enters the queue. Start with one suppression record and a send-time check. The bill includes message attempts, event storage, recovery support, and authenticator enrollment; counting only the first send hides the work caused by retries.

Consider an illustrative workload, not a measured deployment: 1,000 login challenges, 100 addressed to permanently invalid mailboxes, and three additional sends for each invalid address. That produces 1,300 attempted messages. Invalid destinations account for 400 attempts, including all 300 avoidable repeats in this example. Suppression can remove those repeats after definitive failure evidence arrives; it cannot rescue the original 100 deliveries.

TL;DR: For edtech SaaS login, an enrolled authenticator app avoids the email/SMS delivery dependency during code generation. SMS OTP still needs a reachable telephone destination, and email codes need a usable mailbox. Keep those authentication choices separate from recipient health: suppress confirmed permanent email failures, bound transient retries, and provide recovery that does not silently weaken the required assurance. Choose US/EU controls from the actual account risk and data obligations, not a claim that one channel is universally simplest or cheapest.

Protect the next attempt.

How do SMS OTP, an authenticator app, and an email code change delivery work?

Before changing authentication methods, define the unit you are measuring. A login challenge is an authentication event. A send attempt is a delivery event. One challenge can produce several attempts, and successful transport does not establish that the student completed authentication. Mixing these counters makes a resend button look like rising engagement.

Use the following Python calculation to reproduce the opening example. Its values are planning assumptions; substitute your own aggregate counts before drawing a budget conclusion.

challenges = 1000
invalid_recipients = 100
extra_sends_per_invalid = 3

healthy_attempts = challenges - invalid_recipients
invalid_attempts = invalid_recipients * (1 + extra_sends_per_invalid)
avoidable_repeats = invalid_recipients * extra_sends_per_invalid

assert healthy_attempts + invalid_attempts == 1300
assert avoidable_repeats == 300
print({"total_attempts": 1300, "avoidable_repeats": avoidable_repeats})
Enter fullscreen mode Exit fullscreen mode

This example quantifies the dominant avoidable message term, not the largest component of every authentication budget. Support labor could dominate instead. Record recovery contacts alongside attempts, then decide whether fewer sends actually reduce operational work or merely move it into the help desk. No unit price is needed to see that distinction.

For a student who already has an enrolled authenticator, generating a time-based code does not require sending a message. RFC 6238 describes the time-based one-time password mechanism. Enrollment, secret protection, clock tolerance, lost-device recovery, and verifier throttling remain engineering responsibilities. Removing a delivery dependency does not remove those responsibilities.

SMS OTP trades mailbox dependence for telephone delivery and number ownership concerns. Email codes can be convenient where the mailbox is already accessible, but bouncing school addresses make that convenience conditional. Under NIST SP 800-63B-4, email is not permitted for out-of-band authentication, while PSTN-based authentication is restricted. These are assurance boundaries, not a declaration that every SaaS service falls under the same requirements. Neither manually entered OTP channel nor a conventional authenticator code supplies phishing resistance by itself.

Step 2: Which failure should suppress a student's address?

An SMTP reply and a delivery status notification are different evidence surfaces. RFC 5321 distinguishes temporary 4yz replies from permanent 5yz replies; RFC 3463 supplies enhanced status codes, including 5.1.1 for a bad destination mailbox address. A permanent policy rejection is not automatically proof that the mailbox is invalid. Suppressing every address associated with any permanent failure can lock out valid students after a sender configuration problem.

Keep the classifier narrow. Don't treat every permanent failure as an invalid mailbox.

The next executable example starts after a trusted adapter has authenticated and normalized a delivery event. It accepts only an address-specific failure, checks the outcome, and deduplicates the event. The event is synthetic fixture data. It demonstrates the decision boundary, not a webhook authentication implementation.

suppressed = set()
seen_events = set()

def apply_delivery_event(event):
    event_id = event["event_id"]
    if event_id in seen_events:
        return "duplicate"
    if event["action"] == "failed" and event["status"] == "5.1.1":
        suppressed.add((event["tenant_id"], event["recipient_id"]))
        outcome = "suppressed"
    else:
        outcome = "no_recipient_change"
    seen_events.add(event_id)
    return outcome

event = {
    "event_id": "fixture-bounce-17",
    "tenant_id": "school-demo",
    "recipient_id": "student-42-address-1",
    "action": "failed",
    "status": "5.1.1",
}
assert apply_delivery_event(event) == "suppressed"
assert apply_delivery_event(event) == "duplicate"
assert len(suppressed) == 1
Enter fullscreen mode Exit fullscreen mode

Use a recipient record that represents a particular address version. Otherwise a late bounce for an old school mailbox could suppress the replacement address. Preserve the original address semantics; an opaque identifier avoids treating arbitrary lowercasing as proof that two mailboxes are equivalent.

In production, commit the deduplication marker and suppression change atomically in durable storage. Authenticate the event source, correlate it with a message your system actually submitted, and authorize its tenant boundary before applying the change. A caller-provided failure code is not sufficient evidence. Transient failures should enter a bounded retry policy with backoff; an expired login challenge should never be revived merely because transport is ready to retry.

Step 3: Check suppression where the message leaves

A bounce can arrive after several resend requests are already queued. Checking only when the request enters the application leaves those queued jobs eligible to send. Read current recipient state at dispatch, and check the challenge lifetime there too. The following independent Python example makes both decisions visible.

def dispatch_decision(job, suppressed, now):
    if now >= job["expires_at"]:
        return "expired"
    key = (job["tenant_id"], job["recipient_id"])
    if key in suppressed:
        return "suppressed"
    return "eligible"

job = {
    "tenant_id": "school-demo",
    "recipient_id": "student-42-address-1",
    "expires_at": 120,
}
blocked = {("school-demo", "student-42-address-1")}
assert dispatch_decision(job, blocked, now=100) == "suppressed"
assert dispatch_decision(job, set(), now=120) == "expired"
assert dispatch_decision(job, set(), now=100) == "eligible"
Enter fullscreen mode Exit fullscreen mode

The timestamps are test values, not a recommended OTP lifetime. Likewise, “eligible” is permission to continue evaluating a send, not proof of delivery. The dispatcher still needs rate limits, challenge state checks, and a policy for ambiguous submission outcomes. A timeout after submission may mean the message was accepted; blindly resubmitting can create duplicate mail. Durable job identifiers and transport reconciliation reduce that ambiguity. A suppression event arriving after the final check can still race with submission, so define the guarantee as blocking subsequent dispatch decisions after committed evidence becomes visible.

Do not turn that internal precision into an account-discovery endpoint. Return a generic login response while exposing actionable recipient state only in an appropriately authenticated recovery flow. A student should be able to correct an obsolete address through verified recovery; silently falling back from a required second factor to an email code changes the security policy.

Deliverability has its own boundary here. DKIM signs selected message headers and body content under a signing domain, as specified by RFC 6376. It does not prove that a student mailbox exists or guarantee inbox placement. Mail Privacy Protection also makes remote-content loading unsuitable as direct evidence that the intended student read a login message. Neither a signature nor an open signal should clear a confirmed invalid-recipient suppression.

For rollout, replay duplicate, delayed, and out-of-order fixture events before enabling enforcement. Then compare eligible sends, suppressed sends, expired jobs, and completed logins using aggregate counts. Investigate a fall in sends that accompanies a fall in completed logins. That may be an overbroad classifier, not an improvement. Keep OTP values and authenticator secrets out of these operational logs.

Step 4: Keep the decision after discarding the payload

Retention is a design choice with a failure cost. For EU processing, GDPR Article 5 requires data minimization and storage limitation; it does not prescribe one universal retention period for bounce payloads. US and EU obligations need a review of the service's users, contracts, processing roles, and applicable rules. A channel selection alone cannot establish compliance.

Separate short-lived diagnostic payloads from the minimal recipient state that prevents another invalid send. This runnable example expresses a configured diagnostic deadline. Seven days is an illustrative policy input, not a legal requirement or a universal operational recommendation.

from datetime import datetime, timedelta, timezone

def diagnostic_record(event_id, received_at, retention_days):
    if retention_days <= 0:
        raise ValueError("retention_days must be positive")
    return {
        "event_id": event_id,
        "delete_after": received_at + timedelta(days=retention_days),
    }

received_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
record = diagnostic_record("fixture-bounce-17", received_at, 7)
assert record["delete_after"] == received_at + timedelta(days=7)
Enter fullscreen mode Exit fullscreen mode

A timestamp does not perform deletion. Schedule and verify deletion across primary storage, replicas, exports, and the relevant backup lifecycle. Give the suppression record its own justified retention and review process; dropping the raw payload must not accidentally make a known invalid address eligible again. Keep deduplication evidence for the accepted replay window, or explicitly reconcile older events before they can affect newer recipient state.

For this design, deliberately stop retaining message bodies, OTP values, full raw bounce payloads beyond their diagnostic window, and per-student open histories for recipient-health decisions. Retain only the justified suppression reason, address-version reference, evidence timestamp, and controlled recovery transition. Those records still need access controls and deletion rules.

The trade-off is concrete: once the diagnostic payload expires, support can't reconstruct every rejected header or reparse the original event to investigate a classifier mistake. Aggregate counters may reveal the pattern, but an individual dispute may require fresh, authorized verification. Accept that loss explicitly. Reliable student access depends on accurate suppression and recoverable identity, not indefinite storage of every failed message.

Further reading

References:

Top comments (0)