For SMS OTP backend authentication, release a seller's new-order alert from committed business state, and evaluate the buyer's verification evidence when authorizing that commitment. An SMS that arrives late must not move either boundary. In a fintech marketplace, confusing these clocks can turn a harmless delivery delay into an authorization error.
Short answer: separate SMS OTP expiry, authentication freshness, notification retry lifetime, and audit retention. Enforce guessing limits and recovery-code consumption in shared durable state. Preserve the evidence needed to explain authorization, while sampling delivery diagnostics independently. The decision here is about temporal correctness: which evidence remains valid for which decision, and when it can be discarded.
An SMS code alone is not two-factor authentication. The design below assumes an authenticated buyer session established through an independent first factor. NIST's authentication guidance treats the public telephone network as a restricted channel; a delivery receipt cannot resolve that assurance boundary.
How should SMS OTP backend authentication handle buyer verification expiry?
Order commitment does.
Consider an illustrative sequence, with offsets rather than measured service latencies. A buyer successfully consumes a challenge at time zero. The backend commits the authorized order 2 seconds later. A notification worker picks up its durable intent after another 40 seconds. Authentication freshness belongs to the authorization decision at commitment; it should not be reevaluated merely because the notification worker ran later. Otherwise, a backlog could change which already committed orders receive alerts. Conversely, evidence that expired before commitment must not become acceptable because a transport later reports successful SMS delivery.
These are proposed application invariants, not properties of SMS. The challenge must be bound to the buyer and purpose, have an expiry, and be consumed at most once. Verification must atomically check the attempt budget and update it across backend instances. If the policy binds verification to an order, commitment must check that binding and the relevant order state. A client-supplied challenge identifier only locates evidence; it does not prove that the evidence is valid. Resending cannot replenish the guessing budget. Treat issuance limits and verification-attempt limits as separate controls, with shared accounting where the policy requires it. Account limits address targeted guessing; destination and network limits address other abuse patterns, but shared networks complicate their interpretation. NIST requires rate limiting for short authentication secrets. Choose the actual thresholds from the assurance and abuse requirements rather than borrowing a universal number from an example.
Recovery has its own clock and consumption rule. A recovery code must be accepted only once, with a protected verifier and atomic redemption. It is another credential, so its plaintext must not enter request logs or traces. A recovery event should identify the authentication path used; it should not pretend that an SMS comparison occurred. Apply the resulting authentication policy explicitly before authorizing the order.
The failure boundaries follow from these rules. Authentication storage governs challenge consumption. Order storage governs commitment and durable notification intent. An external delivery system governs transport observations. Keeping an order and its notification intent in one transaction preserves pending work across a process restart, but it cannot make an external message side effect exactly once. A worker may send successfully and lose its acknowledgment before recording completion. Stable notification identity and receiving-side duplicate handling matter at that boundary.
Decision record for evidence lifetimes
The alternatives below differ in when they permit evidence to disappear. This is also an operational burden: records retained for authorization need stronger completeness guarantees than diagnostic traces.
| Option | Expiry and retention behavior | Decision and trade-off |
|---|---|---|
| Separate credential, business, and diagnostic lifetimes | Credentials expire under authentication policy; pending work survives until resolved; diagnostics have bounded retention | Selected. More lifecycle rules to maintain, but delayed delivery cannot rewrite authorization |
| Use one shared expiry for verification and notification work | A notification can disappear when authentication evidence expires | Rejected for committed orders because queue delay would affect business delivery |
| Keep complete request bodies indefinitely | Secrets and incidental payloads survive alongside useful evidence | Rejected. Extra bytes do not establish atomic consumption or reliable notification intent |
This design deliberately keeps less diagnostic detail. It pays for durable business evidence instead. That trade-off is defensible only if the team can explain what each retained record proves: a verification outcome proves a verifier decision, an order record proves commitment, and a delivery observation describes a transport result. None proves that a person read a message.
Give each record an owner and a deletion rule. Unresolved notification work needs a retry or terminal disposition policy; it must not vanish through a generic log-retention setting. Security audit retention needs its own documented justification and access controls. OWASP's logging guidance supports excluding authentication secrets and avoiding retention beyond the required period. It does not prescribe a universal retention duration for this marketplace.
Exercise consumption before measuring delivery
For a NestJS implementation, keep the controller thin enough that all application instances reach the same verifier and shared budget. A request guard can reject traffic, but the correctness argument must include the atomic state change underneath it. Two requests that both observe an unused code must not both redeem it.
The curl probes below deliberately take URLs from the application's existing API contract. They do not define new routes. Run them against an isolated test deployment with disposable credentials. Set the verification URL to an issued test challenge's attempt operation, the recovery URL to the documented recovery operation, and the session variable to a buyer session that has completed the independent first factor. The payload field names are illustrative contract assumptions and must match the implementation before execution.
curl --request POST \
--url "${VERIFICATION_URL:?Set the documented verification URL}" \
--header "Authorization: Bearer ${TEST_BUYER_SESSION:?Set a test session}" \
--header 'Content-Type: application/json' \
--data "{\"code\":\"${TEST_OTP:?Set a disposable test OTP}\"}"
curl --request POST \
--url "${RECOVERY_URL:?Set the documented recovery URL}" \
--header "Authorization: Bearer ${TEST_BUYER_SESSION:?Set a test session}" \
--header 'Content-Type: application/json' \
--data "{\"code\":\"${TEST_RECOVERY_CODE:?Set a disposable recovery code}\"}"
Use test values compatible with the JSON string encoding shown. Avoid shell tracing, HTTP verbose output, and command-output capture that would collect credentials. Environment expansion is a demonstration convenience, not a secret-storage design.
Repeat each operation with the same credential, then exercise concurrent redemption through the test harness. The first valid consumption may succeed; subsequent consumption must fail. Test expiry separately from exhaustion of the attempt budget, including attempts sent through different application instances. RFC 6585 defines HTTP 429 for excessive requests and allows Retry-After; document which issuance or attempt limits produce that response. Do not count a delivery retry as a new authentication attempt.
The deployment test should also hold notification processing until after authentication freshness has elapsed, while committing the order beforehand. Its notification intent should remain pending. Reverse the ordering in another test: let authentication freshness expire before attempting commitment, and require a fresh authorization decision. This pair isolates the temporal boundary without inventing a delivery benchmark. Add the worker's send-before-acknowledgment failure case and inspect durable state separately from transport attempts.
Budget the evidence that remains
Count dimensions first.
For an illustrative metric with 4 bounded outcomes, 3 channels, and 2 environments, there are 24 possible label combinations. Adding 100,000 buyer identifiers raises the theoretical product to 2,400,000. Neither figure is an observed workload. Prometheus guidance warns against unbounded label cardinality; challenge IDs, order IDs, and account references belong outside metric labels.
Retention multiplies volume.
Suppose a sizing exercise assumes 100,000 verification flows per day, 4 retained security events per flow, and 600 serialized bytes per event. The raw total is 240,000,000 bytes per day. Keeping that population for 30 days requires 7,200,000,000 bytes before indexing, replication, or compression. These are explicit assumptions, not a retention recommendation. Measure representative serialized records before allocating capacity, and include deletion behavior in the test.
Retain only fields with an evidentiary purpose: timestamp, bounded outcome and reason, applicable policy version, and controlled references needed to connect verification with authorization. Pseudonymous identifiers still need access and retention controls. Payload capture is especially expensive evidence when it includes secrets that should never have been retained.
A hypothetical 10% sample of routine transport traces provides less individual debugging coverage. Accept that loss explicitly. Preserve required security outcomes independently of trace sampling, keep aggregate outcomes and backlog age, and decide whether failure-focused tracing supplies enough context for diagnosis. Sampling reduces the trace population; it does not repair missing authorization evidence. The observability bill should reflect these different jobs, rather than one blanket instruction to retain everything.
Rejected option and its valid use case
A shared expiry remains reasonable for a disposable pre-commitment prompt whose usefulness ends with the challenge. After expiration, sending that prompt may serve no purpose. That is the valid use case for coupling a message's lifetime to credential validity.
It does not fit a seller's alert for an already committed order. Keep that work under the order's notification policy, preserve its disposition, and use bounded telemetry to explain delays. The acceptance criterion is concrete: authentication expiry can prevent a new commitment, while delayed delivery cannot erase notification work created by an authorized commitment.
References
- NIST Digital Identity Guidelines, Authentication and Authenticator Management: https://pages.nist.gov/800-63-4/sp800-63b.html
- OWASP Authentication Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html
- OWASP Logging Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html
- RFC 6585, Additional HTTP Status Codes: https://www.rfc-editor.org/rfc/rfc6585.html
- Prometheus instrumentation guidance: https://prometheus.io/docs/practices/instrumentation/
Top comments (0)