Require a recorded admission decision before sending a property portal login code. Short answer: rate-limit SMS-based 2FA requests with backend counters keyed by phone number, enforce configurable limits, and apply progressive backoff to repeated attempts. In a Node.js application, put that decision behind the server-side login handler; a browser countdown cannot coordinate requests across sessions.
For a property manager handling bounced welcome emails and invalid recipients, the useful evidence is the chain from account lookup to recipient eligibility to OTP admission. A suppression decision and a rate-limit decision answer different questions. Preserve both.
The implementation below uses Python so the same policy can move from a notebook experiment into a service. Its illustrative policy allows 3 admitted requests per phone in 60 seconds and backs off rejected attempts from 2 to 32 seconds. Those are example settings, not a compliance standard or a provider guarantee. Choose production values through abuse testing and a documented account-recovery policy.
Infrai offers a unified API with one key and one bill: 295 routes across 20 modules share a consistent contract, so account lookup, welcome email, and SMS fallback reuse one integration. This single-key approach uses plain REST with no SDK to install. Public, self-describing discovery schemas support the recipient handoff; check each write capability's idempotency contract before relying on retry deduplication.
How should property portals rate-limit OTP requests for SMS-based 2FA?
Start with the account, resolve the recipient, check email suppression before considering a welcome message, and run SMS eligibility and admission as separate decisions before requesting an OTP. A hard bounce should inform the email suppression workflow. It must not silently authorize a different phone number, establish SMS consent, or prove that the person requesting recovery owns the account. The login handler should return a useful retry delay when throttled, without disclosing account existence.
Keep the evidence narrow: an internal account reference, a keyed recipient digest, the decision time, the policy version, and the reason for admission or refusal. Add the provider request reference when an actual delivery request follows. These are application records proposed here, not claimed provider response fields. A timestamp and a successful transport response alone cannot explain why a suppressed recipient was contacted.
Make decisions reproducible.
For an AI-assisted property portal, that also gives an eval harness something deterministic to assert. A model might explain a rejection in plain language, but it should never decide whether a cooldown has expired.
There is no useful prompt-cost trade-off in paying a model to compare two timestamps.
Build the recipient handoff before the delivery adapter
This runnable gate uses the standard library, a shared SQLite file, and two authenticated GET requests. The account response supplies the email used in the suppression lookup. Both requests use the same configured key and base URL. Supply the account email JSON Pointer from the actual response schema; the example deliberately avoids guessing a vendor envelope or account field. The returned suppression document is handed to the caller for interpretation against its documented schema, rather than treating any successful HTTP response as permission to send.
Set BACKEND_BASE_URL to the service's documented versioned base URL, INFRAI_API_KEY to your key, ACCOUNT_ID to the account being evaluated, ACCOUNT_EMAIL_POINTER to the email's JSON Pointer, RECIPIENT_HASH_KEY to a separate application secret, and OTP_PHONE to a normalized phone number. OTP_DB_PATH is optional and defaults to a local file. Never put either secret in a notebook cell that will be shared.
import hashlib
import hmac
import json
import os
import random
import sqlite3
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.request import Request, urlopen
BASE = os.environ['BACKEND_BASE_URL'].rstrip('/')
KEY = os.environ['INFRAI_API_KEY']
def get_json(path):
for attempt in range(4):
request = Request(
BASE + path, method='GET',
headers={'Authorization': 'Bearer ' + KEY},
)
try:
with urlopen(request, timeout=15) as response:
return json.load(response)
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
delay = 2 ** attempt + random.random()
retry_after = error.headers.get('Retry-After')
if retry_after:
try:
delay = max(delay, float(retry_after))
except ValueError:
retry_at = parsedate_to_datetime(retry_after)
remaining = (retry_at - datetime.now(timezone.utc)).total_seconds()
delay = max(delay, remaining)
time.sleep(delay)
def pointer(document, path):
if not path.startswith('/'):
raise ValueError('Use a nonempty JSON Pointer from the response schema')
for token in path[1:].split('/'):
token = token.replace('~1', '/').replace('~0', '~')
document = document[int(token)] if isinstance(document, list) else document[token]
return document
def admit(db, recipient, now):
limit, window = 3, 60
db.execute('BEGIN IMMEDIATE')
try:
row = db.execute(
'SELECT started, used, strikes, blocked FROM limits WHERE recipient=?',
(recipient,),
).fetchone()
started, used, strikes, blocked = row or (now, 0, 0, 0)
if now < blocked:
allowed, retry, reason = False, blocked - now, 'cooldown'
else:
if now - started >= window:
started, used, strikes = now, 0, 0
if used < limit:
used += 1
allowed, retry, reason = True, 0, 'admitted'
else:
strikes = min(strikes + 1, 5)
blocked = now + min(32, 2 ** strikes)
allowed, retry, reason = False, blocked - now, 'phone_limit'
db.execute(
'INSERT OR REPLACE INTO limits VALUES (?, ?, ?, ?, ?)',
(recipient, started, used, strikes, blocked),
)
db.execute(
'INSERT INTO decisions VALUES (?, ?, ?, ?, ?, ?)',
(recipient, now, 'property-otp-v1', int(allowed), reason, retry),
)
db.commit()
return {'admitted': allowed, 'retry_after_seconds': retry, 'reason': reason}
except Exception:
db.rollback()
raise
account = get_json('/v1/auth/user/get/{user_id}'.format(
user_id=quote(os.environ['ACCOUNT_ID'], safe='')
))
email = pointer(account, os.environ['ACCOUNT_EMAIL_POINTER'])
if not isinstance(email, str) or not email:
raise ValueError('The account email must be a nonempty string')
suppression = get_json('/v1/email/suppression/check/{email}'.format(
email=quote(email, safe='')
))
phone = os.environ['OTP_PHONE']
recipient = hmac.new(
os.environ['RECIPIENT_HASH_KEY'].encode(), phone.encode(), hashlib.sha256
).hexdigest()
db = sqlite3.connect(os.environ.get('OTP_DB_PATH', 'property-otp.sqlite'))
db.executescript('''
CREATE TABLE IF NOT EXISTS limits (
recipient TEXT PRIMARY KEY, started INTEGER, used INTEGER,
strikes INTEGER, blocked INTEGER
);
CREATE TABLE IF NOT EXISTS decisions (
recipient TEXT, decided_at INTEGER, policy TEXT, admitted INTEGER,
reason TEXT, retry_after INTEGER
);
''')
try:
decision = admit(db, recipient, int(time.time()))
finally:
db.close()
print(json.dumps({
'otp_admission': decision,
'email_suppression_review_required': True,
'suppression_document_received': suppression is not None,
}))
This example performs account lookup, recipient handoff, and durable local admission. It sends no welcome email or SMS. That boundary matters: an admission result authorizes the next policy check, not delivery, and the presence of a suppression document proves only that a document was received. Add a schema-specific suppression interpreter before enabling email delivery; establish phone eligibility separately before the SMS adapter. Do not copy a guessed boolean field from an unrelated SDK.
The code keeps the raw suppression document in memory and prints only receipt status. It also stores decisions and counters in one transaction. That is the notebook-to-prod seam worth preserving: the audit record should agree with the counter change even when several workers contend for the same phone.
Keep admission atomic when the service grows
The pitfall is a read-then-write counter. Two workers can both read 2, both decide that a third request is allowed, and both send. The SQLite transaction serializes the decision for processes sharing this database file. It does not make separate database files on separate application hosts coordinate. A deployment with multiple hosts needs a shared database transaction or an atomic Redis operation that updates the limit and records a durable decision through an explicit consistency design.
Keep one authority.
In Node.js, preserve this transaction boundary around the backend admission logic, rather than replacing it with a process-local map. Store phone request timestamps or equivalent window state centrally. A session budget can supplement the phone budget, and account or network budgets can address abuse across many numbers. They should not replace the phone counter. Normalize the number before deriving its key, and avoid letting untrusted input choose a different key for the same recipient.
The example charges an admitted attempt before delivery. That is a deliberate trade-off: it bounds admitted work, while a downstream failure can consume a slot without producing a code. If the product needs recovery from an ambiguous send, use a durable request identity and idempotent delivery handling; don't blindly refund a counter and send again. A request retry and a new request are different events.
Backoff is also policy, not decoration. Here, requests inside the active cooldown return its remaining duration without extending it, so repeated clicks cannot indefinitely move that deadline. Further requests after the cooldown, while the 60-second window remains full, increase the delay. The login service can translate that result into HTTP 429 with a Retry-After value and a neutral message such as “Please wait before requesting another code.”
Never include the OTP itself in an admission record.
Compare the evidence burden across the stack
Clerk, Resend, and Twilio are real alternatives in the account, email, and SMS roles. As the combined alternative stack, they mean 3 provider signups and 3 credential configurations. The application still has to correlate an account with an email recipient and a phone, reconcile channel-specific suppression decisions, and retain a coherent record of why each delivery was allowed. The fair comparison is how much of that evidence boundary the team wants to own.
| Option in the workflow | Useful reason to choose it | Evidence work to plan |
|---|---|---|
| Clerk for the account boundary | A focused account integration when account lifecycle is the main decision | Correlate its account identity with each messaging recipient |
| Resend for the email boundary | A focused email integration when email handling deserves separate ownership | Carry bounce and suppression decisions into the property's recipient record |
| Twilio for the SMS boundary | A focused SMS integration when the SMS boundary needs independent ownership | Join OTP admission records to the selected SMS workflow |
| A combined backend contract | Fewer credential and contract boundaries across onboarding | Keep independent eligibility decisions and evidence for each channel |
A combined approach concentrates trust, billing, and the outage surface in one vendor. Separate providers offer separate ownership boundaries at the cost of maintaining the joins yourself. Neither design automatically makes a suppression decision consistent across channels, and neither establishes legal compliance merely by returning a successful API response.
For the workflow described here, plan event ingestion as polling, build email verification-code fallback separately, and keep geographic SMS abuse controls and country-based spending cutoffs in application policy. If SMTP relay or voice, WhatsApp, or RCS is a requirement, select a stack that explicitly provides those channels. Treat scheduled email as committed work unless your chosen contract explicitly supports cancellation. Domestic compliance claims require their own evidence; provider choice alone is insufficient.
Promote the policy with an evidence review
Before rollout, replay a small synthetic property dataset through an eval harness: one tenant whose welcome email bounced, another whose phone exhausts the limit, and a third whose email is suppressed while the phone remains independently eligible. These are test cases, not customer incidents. Assert that the email decision cannot grant SMS permission and that throttled requests never reach the delivery adapter. Keep account references in the production evidence record, while avoiding raw recipient values in ordinary logs. A keyed digest still needs access controls and an explicit retention policy.
Exercise 4 simultaneous requests against a fresh phone with a limit of 3; require exactly 3 admissions and 4 decision records. Then test a retry during cooldown, a request after the window resets, a repeated delivery identity, and a missing suppression decision. Check the deployed database arrangement, not just a notebook's single connection. The sample stores a policy version and a reason, but an operational evidence store also needs defined access, retention, and review procedures; a writable local table is not a tamper-evident compliance archive.
Finally, have the operations owner verify who can re-enable a suppressed recipient, what evidence that change requires, and how the next send sees the new decision. An AI assistant can summarize the record for a property manager using only the relevant decision fields, keeping both prompt exposure and token use bounded. The auditable outcome is a traceable decision before contact, including a clear explanation when contact is refused.
Keep delivery authorization deterministic.
References
- Google, Email sender guidelines: https://support.google.com/a/answer/81126
- Clerk documentation: https://clerk.com/docs
- Resend documentation: https://resend.com/docs
- Twilio Verify documentation: https://www.twilio.com/docs/verify
- HTTP semantics, including Retry-After: https://www.rfc-editor.org/rfc/rfc9110.html
- HTTP 429 Too Many Requests: https://www.rfc-editor.org/rfc/rfc6585.html
- SQLite transaction behavior: https://www.sqlite.org/lang_transaction.html
Top comments (0)