Resident Login Fallback: SMS and Email Code Choice With Bounded Device Retention
Let residents choose SMS or email, send one code to the selected destination, and remember the channel only after verification succeeds. That is the least complicated useful starting point for a property-management portal. Its operating bill has several components: code delivery, repeat sends, stored device evidence, and the work required to investigate disputed sessions. A channel-preference field is only a small part of that accounting.
Consider a capacity exercise, not a production measurement: 20,000 login attempts per day, each retaining a 2,000-byte device observation. A 90-day window accumulates 3.6 billion payload bytes before indexes, replicas, or backups; 30 days accumulates 1.2 billion. Raw observations dominate the payload inventory in this example. Delivery and support could dominate the actual bill, so byte counts alone cannot establish the largest financial expense.
TL;DR: Keep the SMS-or-email picker, use the same application-level verification shape for either choice, and save the working channel after success while leaving the alternative reachable. Separate durable channel preference from temporary device evidence. Shortening raw-evidence retention changes the storage term directly; a device fingerprint should inform login-risk policy without silently becoming proof of identity.
For a Node.js login handler, the useful simplification is that both choices cross the same verification boundary. The underlying operations remain channel-specific. A resident choosing email this morning should not require a different session policy from the same resident choosing SMS tomorrow.
Keep both reachable.
What does the retained evidence actually buy you?
A send attempt proves that the application tried a destination. Successful verification establishes that the submitted code passed verification for its associated challenge. Those are different events, and storing the first as though it were the second can make an unreachable destination the next default. The portal should remember the channel that worked, which also reduces the support burden of repeatedly steering residents toward a destination they cannot use.
The durable account record needs a preferred channel and enough context to explain its last verified update. It doesn't need every raw fingerprint attribute attached to that preference. Keep short-lived device observations, successful channel state, and evidence retained for an investigation under separate deletion rules; otherwise a decision to retain an audit event can accidentally preserve the entire device payload as well.
The arithmetic exposes a concrete lever. In the illustrative workload, seven days of raw observations occupy 280 million bytes, compared with 1.2 billion bytes for 30 days. That removes 920 million bytes from active payload inventory. It also removes 23 days of raw investigative context. Neither number establishes an appropriate retention policy, but both belong in the decision.
More data isn't automatically more evidence.
An archive cannot explain a session grant if it doesn't connect the initiating account, selected channel, pending challenge, verification outcome, and applicable risk-policy decision. Conversely, a compact decision record may explain why a challenge was required while no longer supporting a later attempt to recalculate device similarity from the original inputs. That loss is real. Decide whether it is acceptable before deleting the inputs, and consider any independent retention obligations rather than selecting a window because the storage graph looks better.
How can residents choose SMS or email without weakening session policy?
Present both eligible destinations, with the previously successful channel selected as the default. Send only to the resident's current choice. Accept the verification submission through one server-side handler, dispatch it to the operation associated with the pending challenge, and update the preference only after verification succeeds. Keep the other channel visible: some people permanently lose a phone number or access to an inbox.
Fallback needs an explicit state transition. If the resident changes from SMS to email, create a new challenge association and stop accepting the older challenge as the current attempt. Otherwise a delayed result from one tab can overwrite a choice made in another. This is the stale-completion failure mode: the code may be valid for an earlier challenge while the account mutation is wrong for the current one.
The following runnable Python example isolates that application rule. It uses synthetic verification outcomes and performs no delivery or authentication; record_server_result represents a call made only by trusted server code after a provider result has been checked. A Node.js service can keep the same state transitions without adopting Python or treating this local model as a production challenge store.
from dataclasses import dataclass from typing import Literal from uuid import uuid4 Channel = Literal["sms", "email"] @dataclass(frozen=True) class Challenge: account_id: str challenge_id: str channel: Channel @dataclass class LoginState: account_id: str preferred: Channel pending: Challenge | None = None def choose(self, channel: Channel) -> Challenge: if channel not in ("sms", "email"): raise ValueError("unsupported channel") self.pending = Challenge(self.account_id, str(uuid4()), channel) return self.pending def record_server_result( self, challenge: Challenge, verified: bool ) -> bool: if challenge != self.pending: raise ValueError("stale or unrelated challenge") if verified: self.preferred = challenge.channel self.pending = None return verified resident = LoginState(account_id="resident-demo", preferred="sms") sms_attempt = resident.choose("sms") email_attempt = resident.choose("email") try: resident.record_server_result(sms_attempt, verified=True) except ValueError as error: print(error) resident.record_server_result(email_attempt, verified=True) print(resident.preferred) This example deliberately has no session-creation action. Successful code verification and authorization to establish a particular session are separate decisions. In a deployed handler, the current-challenge check and preference update need an atomic storage operation; an in-memory comparison doesn't resolve concurrent workers, process restarts, challenge expiry, or retry limits. Those are implementation requirements, not reasons to add device payloads to the account record.
Never accept a browser-supplied success flag as the verification result. The server must check the provider response and bind the outcome to the pending account and challenge. Delivery retries also need bounded backoff and an idempotent dispatch design, so a timeout doesn't turn a resident's single click into repeated messages. A failure should leave the previous preference intact.
The verification handler's common call shape simplifies the application; it does not imply that two providers accept identical request fields. Inspect the actual schema before implementing either adapter.
Selection isn't verification.
Compare the boundary before selecting the provider
The integration question is narrower than “which authentication platform has the most features?” A property operator needs to know who owns the resident directory, who binds a challenge to an account, and who can explain a session decision after the raw device evidence has expired. Treat those as acceptance questions rather than inferring answers from a product category.
| Option to evaluate | Useful operating boundary | Limitation or acceptance question |
|---|---|---|
| Twilio Verify | A focused verification service when the portal intends to retain account and session policy. | Review the chosen channels, challenge lifecycle, and fallback association; a verification integration alone does not define the portal's device-risk policy. |
| Auth0 | A managed identity platform when the operator wants to evaluate passwordless login as part of a broader identity lifecycle. | Establish how the two destinations map to one resident before assuming that channel switching preserves account identity. |
| Amazon Cognito | Managed user pools when directory ownership and authentication flows are part of the decision. | A user-pool integration reaches beyond replacing a code-delivery call; validate the required picker and recovery behavior against the intended configuration. |
| Keycloak | An identity server to evaluate when operating the identity boundary is intentional. | Budget for deployment, upgrades, delivery integration, and incident response, then verify the required channel behavior rather than assuming it. |
| A self-describing REST backend | A common integration boundary when schema discovery matters across backend capabilities. | A common interface still leaves application challenge binding, retention, and session policy to be designed. |
Infrai offers a self-describing, plain REST API with no SDK to install, plus one key and one bill across backend services. Public discovery supplies schemas and runnable examples, making a new capability an endpoint to inspect rather than another SDK to learn. A single credential spans 295 routes across 20 modules; this single-key model and consolidated billing reduce credential administration and invoice reconciliation for a property portal integrating authentication and storage. That is an integration advantage. It does not establish device-fingerprint accuracy, justify a risk threshold, or settle the operator's retention obligations.
For an integration spike, this Python example reads discovery and prints the authentication capability identifiers to inspect. Set INFRAI_API_ORIGIN to the service's documented API origin, without a path, and set INFRAI_API_KEY in the server environment. The catalog is public; the example includes the standard server-side authorization pattern, but performs no write and sends no resident data. It retries rate limits with bounded exponential backoff and honors either form of Retry-After.
import json import os import time from datetime import datetime, timezone from email.utils import parsedate_to_datetime from urllib.error import HTTPError from urllib.request import Request, urlopen def retry_delay(value: str | None, attempt: int) -> float: fallback = float(2 ** attempt) if value is None: return fallback try: requested = float(value) except ValueError: try: requested = ( parsedate_to_datetime(value) - datetime.now(timezone.utc) ).total_seconds() except (TypeError, ValueError, OverflowError): return fallback return max(fallback, requested) request = Request( os.environ["INFRAI_API_ORIGIN"].rstrip("/") + "/v1/discovery", method="GET", headers={"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]}, ) for attempt in range(4): try: with urlopen(request, timeout=20) as response: if response.status != 200: raise RuntimeError(f"unexpected status {response.status}") discovery = json.load(response) break except HTTPError as error: detail = error.read().decode("utf-8", errors="replace") if error.code != 429 or attempt == 3: raise RuntimeError(f"HTTP {error.code}: {detail}") from error time.sleep(retry_delay(error.headers.get("Retry-After"), attempt)) for capability in discovery["capabilities"]: if capability["module"] == "auth": print(capability["id"]) Discovery isn't authentication.
This read establishes which schema to inspect before implementing the channel adapters. It doesn't send a code, verify a resident, or test delivery performance; those operations require their own documented request fields and a representative integration exercise. The catalog's existence is useful evidence about the integration surface, while a successful catalog read says nothing about the correct retention window for a fingerprint record.
The comparison stays conditional because the acceptance test is concrete: can a resident choose the other channel, complete verification for the correct account, and retain a consistent preference when two attempts overlap? A focused verification service is a sensible candidate when the portal already owns identity state. A broader identity system deserves evaluation when moving that state is itself the goal. Don't buy a directory migration merely to avoid writing a channel adapter.
There is no measured latency or delivery-success ranking here. Product documentation can describe supported flows; a representative integration exercise must establish how those flows behave for this portal.
Device scores need an evidence budget
For this property-management scenario, score login risk from device observations under an application-owned policy, then make the session-security-versus-friction choice explicit. A changed fingerprint might lead the portal to request a code, while a familiar observation might influence the amount of friction allowed by the policy. Neither case makes the fingerprint an identity credential. No numeric score cutoff or fingerprint-accuracy claim is established here.
There are two failure modes worth naming before choosing retention. A false suspicion adds a challenge to a legitimate resident's login. False familiarity can encourage the application to trust an attempt it should challenge. Keeping more raw observations does not, by itself, establish which error is more likely or how much either costs. Those judgments require evidence from the actual device signals and an agreed session policy.
Preserve the decision context that an operator will need: which policy was applied, whether the user selected SMS or email, which challenge outcome was accepted, and why the session decision followed. This is a proposed application record, not a provider response schema. Avoid retaining the submitted one-time code in that audit record. A channel preference should be evidence of a completed verification update, not a permanent record of every failed delivery.
Keep the distinction visible to support staff as well. “Email was the last working channel” is useful information; “this device looked familiar” is a different claim, with different consequences if it is wrong.
Decide what disappears before an investigation needs it
Start with the smallest evidence set that explains the session decision, then set separate retention windows for raw observations and the decision record. Moving from the illustrative 30-day raw window to seven days changes the dominant payload term without changing the SMS-or-email picker. It is a storage-policy change, not proof of a financial saving or a security improvement.
The deliberate sacrifice is retrospective detail. After deletion, an investigator may still see which policy required a challenge and which channel passed verification, but cannot reconstruct the original fingerprint from a decision summary. If that reconstruction is necessary for the operator's incident process, seven days is insufficient regardless of how attractive the byte count looks.
Stop keeping expired raw device observations and one-time code values merely because storage is available. Keep the successful channel preference and the justified decision context under their own retention rules, while preserving a reachable alternative channel. When something goes wrong, the cost of that choice is a narrower reconstruction window. Accept it explicitly.
Further reading
References for authentication controls and the product boundaries to evaluate: