An OTP SMS delivery API lets you send one-time password codes via text message to users worldwide for authentication, transaction verification, and account recovery. smsroute's OTP SMS delivery API routes messages through direct carrier interconnects across 149 countries, achieving p99 latency under 500ms and 99% tier-1 delivery rates — all from $0.004 per message with crypto-only payments and no KYC required at signup.
OTP latency is dominated by the carrier, not by the API. A POST to /sms/send
returns in tens of milliseconds, the SMSC answers submit_sm within the same exchange,
and the mobile network then spends one to five seconds paging the handset — longer if the phone is
idle and has to wake on its paging occasion. smsroute targets sub-500 ms API-to-submit p99, so
the only time left in the user's wait is radio time. When a code takes 30 seconds, the cause is
almost always filtering, sender-ID reputation and retry logic, not character encoding.
What Is an OTP SMS and How Does It Work?
An OTP SMS is a single-use numeric or alphanumeric code sent via text message to verify a user's identity. It
supports four main use cases: passwordless login, two-factor authentication (2FA), transaction confirmation, and
account recovery. smsroute handles all four uniformly through the same /sms/send endpoint with an
optional traffic_class=otp flag for routing optimization.
Passwordless login and 2FA happen on the critical path where the user is actively waiting, so latency is the priority — transactional OTPs should arrive in under 5 seconds. Recovery codes can tolerate longer windows (up to 10 minutes) because they are lower-frequency events. All are OTP; 2FA is one specific use case within that category.
The latency budget, hop by hop
"How fast is your OTP API?" is really two questions: how long your backend waits for the API, and how long the user waits for the SMS. They differ by roughly two orders of magnitude, and conflating them is how teams end up optimising the wrong thing.
| Hop | Typical | p99 budget | What makes it slow |
|---|---|---|---|
| TLS + bearer auth | 10–25 ms | 60 ms | Cold connection, distant region |
| E.164 normalise + GSM-7 encode | 1–3 ms | 10 ms | Malformed numbers, non-Latin script |
| Idempotency + rate-limit check | 1–5 ms | 25 ms | Cache miss, hot account row |
| Route selection and scoring | 5–20 ms | 80 ms | Upstream quality re-scoring mid-flight |
submit_sm → submit_sm_resp |
20–80 ms | 300 ms | SMSC congestion, SMPP window exhaustion |
| SMSC → MSC paging | 0.2–2 s | 5 s | Handset detached, roaming, retry |
| MSC → handset display | 1–5 s | 15 s | DRX cycle, weak coverage, SMS-over-NAS |
Only the first five rows are inside smsroute's control, and they are the rows the 500 ms figure refers to. The bottom two are radio scheduling. A phone in idle mode listens for paging on a discontinuous-reception cycle, which in LTE can be as long as 2.56 seconds; the network has to wait for the handset's paging occasion before it can even deliver the message. No provider can compress that interval, and any provider claiming "instant" delivery is describing the submit step, not the handset.
Encoding is a cost lever before it is a latency lever
GSM 03.38 packs 7-bit characters, giving 160 characters in a single SMS and 153 per segment once a
concatenation header is present. UCS-2 gives 70 characters and 67 per segment. The switch is
triggered by the whole message, not by the code: one curly quote, a single emoji or a non-Latin
character flips the entire body to UCS-2, doubling the segment count and therefore the price. The
extension table is subtler still — €, {, }, [,
], ~, | and ^ are two septets each, because they
are sent as an escape sequence.
For OTP this is almost always avoidable: keep the code numeric, keep the copy ASCII, and keep the
message under 160 characters. A template like
@example.com #123456 Your code. Valid 10 minutes. fits in one GSM-7 segment and stays
autofill-compatible on iOS and Android.
The three latency anti-patterns
- Retrying inside the user's request. If the first submit is slow, a synchronous retry doubles the wait and can deliver two codes. Submit once, return the message ID, and let the DLR drive the retry asynchronously.
- Blocking on the DLR. Delivery receipts arrive seconds later, by design. Your login flow must optimise for "request accepted", not "handset displayed".
- Generating the code after the send. Obvious, but it happens in callback-based code: the message goes out before the token is persisted, and verification fails for a code the user definitely received.
OTP SMS Pricing — Transparent and Competitive
smsroute charges from $0.004 per SMS for OTP delivery, with no markup on OTP traffic class. Crypto-only payments (BTC, USDT, ETH, LTC, XMR, SOL) with no KYC at signup and a $5 minimum top-up. Pricing varies by destination country based on local carrier termination costs.
| Provider | Price per SMS | Coverage | KYC Required |
|---|---|---|---|
| smsroute | $0.004 | 149 countries | No |
| Twilio | $0.0079 | 100+ countries | Yes |
| Vonage (Nexmo) | $0.0085 | 100+ countries | Yes |
| MessageBird | $0.0080 | 100+ countries | Yes |
| Plivo | $0.0070 | 100+ countries | Yes |
See transparent SMS pricing by destination for a full breakdown of per-country rates.
How to Configure OTP Message Parameters
A production-ready OTP message has five configurable parameters that directly impact security, deliverability, and user experience.
1. Code Length
6-digit codes are the industry standard — short enough to type in under 10 seconds, long enough to resist brute force (1 million combinations). Use 4 digits for high-frequency flows and 8 digits for account recovery. Recommended: 6 digits for 2FA and passwordless login; 8 digits for recovery.
2. Expiry Window
Transactional OTPs (passwordless, 2FA, confirmations) should expire in 30–60 seconds. This window prevents code reuse while accounting for network latency and user reaction time. Recovery OTPs can last 5–10 minutes since users may not check their phone immediately.
3. Rate Limiting
Enforce a maximum of 3 OTP sends per user per 10 minutes. Track by user ID or phone number, not by IP (VPN users may share addresses). Return 429 to the browser when the limit is hit — do not rely on smsroute's server-side rate limiting as your primary gate.
4. Idempotency Keys for Deduplication
Network flakiness means a user clicking "resend code" twice can produce two requests reaching smsroute
simultaneously. Use a deterministic idempotency_key (e.g., sha256 of user_id + attempt number) in
every request. smsroute caches the key for 24 hours and returns the same message ID for duplicates — preventing
two different codes from being active at once.
5. Message Format
Keep OTP messages short and include the service name. For iOS autofill, prepend @yourdomain.com #
before the code. Example: @example.com #123456 Your verification code. Valid 10 minutes. For
Android, use the User Consent API or AppSignatureHelper to bind the code to your app domain.
Global OTP Delivery — Encoding, Coverage, and Platform Support
smsroute delivers OTP SMS to 149 countries with automatic character encoding detection, iOS autofill support, and carrier-compliant formatting.
GSM-7 vs UCS-2 Encoding
SMS supports two encoding standards. GSM-7 covers Latin alphabet, digits, and common punctuation at 160 characters per segment (lowest cost). UCS-2 handles any Unicode script — Cyrillic, Arabic, CJK, Devanagari — at 70 characters per segment. smsroute auto-detects the script and selects the optimal encoding. For multi-language OTP, keep the code in digits (GSM-7 compatible) and localize the surrounding text.
iOS Autofill and Android Domain Binding
On iOS, messages starting with @yourdomain.com # trigger automatic code detection and autofill via
iOS Messages. The domain must be verified in your app's Info.plist. On Android, use the SMS User Consent API
with a hash of your app's signing certificate for automatic code reading without user intervention.
Anti-Phishing Best Practices
Always include the service name in the message body — "Google: 123456 is your verification code." For high-value transactions, add context: "Confirm: Transfer $500 to Alice. Code: 123456." Never ask users to share the code within the message itself, as attackers impersonate support to trick users into sharing codes.
Common OTP Delivery Pitfalls and How to Avoid Them
Five common OTP delivery issues have well-defined solutions with smsroute's API.
Race Condition on Resend
Problem: Two rapid "resend" clicks generate two different codes. User enters the first successfully, it invalidates server-side, second SMS carries a stale code. Solution: Use idempotency keys — smsroute returns the same message ID and code for duplicate keys within 24 hours.
User Enumeration via Delivery Receipts
Problem: An attacker calls your OTP endpoint with a list of numbers. Different responses for valid vs. invalid numbers leak user existence. Solution: Always return HTTP 200 to the client regardless of delivery status. Reveal delivery data only to authenticated users through their dashboard.
SS7 Interception at Carrier Level
SMS is not end-to-end encrypted and can be intercepted at the carrier level. For high-security flows (banking, crypto, admin access), use push notifications as the primary delivery method with SMS as fallback. Combine OTP with biometric or step-up authentication for sensitive actions.
Code Validation Failures
Allow 3–5 failed attempts before lockout. Use a sliding expiry window — if the code expires, let the user request a new one but reuse the old code for 10 more seconds (grace period) to account for clock skew.
Latency Under Peak Load
smsroute guarantees 99.9% uptime with sub-second latency (p99 under 500ms) through horizontal scaling and direct peering with tier-1 carriers. From $0.004/SMS with 99% tier-1 delivery rates. Full API documentation covers throughput limits and best practices for high-volume senders.
Why carriers filter OTP — and what actually improves delivery
Every tier-1 carrier runs an SMS firewall, usually a commercial stack such as Cloudmark or Adaptive Mobile, in front of its SMSC. The firewall scores each message on sender reputation, content, velocity and recipient history, then decides to deliver, delay, or drop it. OTP traffic is scrutinised more than any other class because it is the delivery mechanism for account takeover: a filtered OTP is a blocked login, and a flood of OTPs is the signature of SMS pumping.
The word "bypass" in every SEO headline about OTP delivery is a tell. There is no legitimate way to bypass a carrier firewall; there is only a set of signals that make a message look like what it claims to be. Providers promising bypass are selling routes that get shut down, or grey routes that will deliver your code to the wrong person.
| Symptom | Most likely cause | Fix | DLR state |
|---|---|---|---|
| Message accepted, never delivered | Content or sender-ID block | Registered sender ID, template matched verbatim, no shorteners | REJECTD / UNDELIV |
| Delivered but user sees nothing | Handset spam filter, DND, or dual-SIM routing | Brand name in body, consistent sender, no link in the first message | DELIVRD |
| Intermittent failures at peak | Velocity throttle or daily cap on the route | Spread traffic across routes, request a higher tier | ACCEPTD → EXPIRED |
| Valid numbers rejected | Landline, ported, or deactivated MSISDN | HLR lookup before send, drop permanent failures | UNDELIV |
| Sudden cost spike, low signup rate | SMS pumping (AIT) against premium ranges | Per-prefix caps, Turnstile on trigger, spend ceiling | DELIVRD (that is the problem) |
The same conditions surface in other aggregators' APIs under their own names: a carrier-filtered message is what Twilio reports as error 30007 ("carrier violation"), a daily cap is 30023, an unknown destination is 30005, and an unreachable handset is 30006. The vocabulary differs; the underlying carrier decision does not.
The five signals that decide your delivery rate
- Sender identity. In the US this means 10DLC brand and campaign registration; in India, a DLT-registered header and a template that matches the registered text; in the EU and UK, an alphanumeric sender ID of up to 11 characters that is not registered anywhere but is expected to identify the brand.
- Template fidelity. If your registered template says
Your {#var#} verification code is {#var#}and you sendYour code: 123456 — tap here, the carrier sees a mismatch and the message is rejected before it reaches the handset. - Links. A URL shortener in an OTP is the single strongest phishing signal a firewall can score. If a link is genuinely required, use your own domain, not a shared shortener, and keep it out of the first message.
- Velocity. Ten messages to one number in a minute, or thousands to one prefix in an hour, is the pumping signature. Per-MSISDN and per-prefix limits are a deliverability control, not just a fraud control.
- Consent hygiene. Honouring STOP/UNSUBSCRIBE and keeping a clean opt-out list is what keeps the sender ID out of the firewall's penalty box. It is also the legal baseline under PECR, the TCPA and GDPR.
Sandbox Mode for OTP Testing
Before deploying to production, use smsroute's sandbox environment. Test API keys (prefix
sk_test_) return deterministic codes instantly without sending real SMS or incurring charges. Send
to any test number and receive code "123456" — perfect for CI/CD pipelines, integration tests, and staging
environments. Swap to a production key (prefix sk_live_) when ready.
The DLR state machine: what each SMPP status really means
A delivery receipt is an SMPP deliver_sm whose esm_class has bit 2 set
(0x04), carrying the original message ID and a stat string. You only get one
if the original submit_sm asked for it via registered_delivery — set it to
1 for a final receipt, 2 for failures only, or 3 for both.
| stat | message_state | Meaning | Retry? | Billable? |
|---|---|---|---|---|
| ACCEPTD | 6 | Accepted by the network, not yet delivered | No — wait for the final state | Not yet |
| DELIVRD | 2 | Delivered to the handset | Never | Yes |
| EXPIRED | 3 | Validity period elapsed before delivery | Yes, once, via another route | No |
| DELETED | 4 | Deleted by the network or the handset | Rarely — usually a permanent block | No |
| UNDELIV | 5 | Undeliverable: invalid, barred or unreachable | Only if the cause is temporary | No |
| REJECTD | 8 | Rejected — content, sender ID or policy | No — fix the message, not the route | No |
| UNKNOWN | 7 | State unknown | Treat as failure after a timeout | No |
Two behaviours break naive handlers. First, receipts arrive out of order: a
DELIVRD can land before the ACCEPTD that logically preceded it, because they
travel different paths through different network elements. Your state machine must be monotonic —
once a message is in a terminal state, a later interim receipt is ignored. Second, a receipt can
arrive before submit_sm_resp for the original submit: the network can be faster
than your own SMSC round trip. Key the state on your own message ID, not on arrival order.
Billing follows the table: only DELIVRD is charged. That is why the pricing page can say
you pay per delivered segment — a message the carrier rejects or expires never becomes a line item. It
is also why "delivered" in your dashboard and "displayed on the handset" are the same event, while
"submitted" is not.
OTP SMS API Code Examples
curl -X POST https://api.sendsmsnokyc.com/sms/send \
-H "Authorization: Bearer sk_live_YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"to": "+33612345678",
"body": "@example.com #123456 Your verification code. Valid 10 minutes.",
"traffic_class": "otp",
"idempotency_key": "user_123_send_1"
}'
import requests
import hashlib
import time
def send_otp(phone_number, code):
api_key = "sk_live_YOUR_API_KEY"
idempotency_key = hashlib.sha256(
f"{phone_number}_{int(time.time())}".encode()
).hexdigest()
payload = {
"to": phone_number,
"body": f"@example.com #{code} Your verification code. Valid 10 minutes.",
"traffic_class": "otp",
"idempotency_key": idempotency_key
}
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
response = requests.post(
"https://api.sendsmsnokyc.com/sms/send",
json=payload,
headers=headers
)
if response.status_code == 201:
result = response.json()
print(f"Message sent: {result['id']}")
return result
else:
print(f"Error: {response.status_code} - {response.text}")
return None
const axios = require('axios');
const crypto = require('crypto');
async function sendOTP(phoneNumber, code) {
const apiKey = 'sk_live_YOUR_API_KEY';
const idempotencyKey = crypto
.createHash('sha256')
.update(`${phoneNumber}_${Date.now()}`)
.digest('hex');
const payload = {
to: phoneNumber,
body: `@example.com #${code} Your verification code. Valid 10 minutes.`,
traffic_class: 'otp',
idempotency_key: idempotencyKey
};
const config = {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
};
try {
const response = await axios.post(
'https://api.sendsmsnokyc.com/sms/send',
payload,
config
);
console.log(`Message sent: ${response.data.id}`);
return response.data;
} catch (error) {
console.error(`Error: ${error.response.status} - ${error.response.data}`);
return null;
}
}
See the Python integration guide and Node.js integration guide for complete walkthroughs with Express.js and Django backends.
Building a DLR webhook that does not double-count
The receiver has four jobs, in this order: verify the signature over the raw body, acknowledge within two seconds, apply the state transition idempotently, and only then do slow work. Anything that touches a database before the signature check is an unauthenticated write; anything that blocks before the acknowledgement causes the provider to retry, which is how one delivery becomes five.
import hashlib, hmac
from fastapi import FastAPI, Request, Response, HTTPException
app = FastAPI()
SECRET = b"whsec_from_dashboard" # rotate in the dashboard, never commit
TERMINAL = {"DELIVRD", "EXPIRED", "DELETED", "UNDELIV", "REJECTD"}
STORE = {} # replace with your DB + unique key
@app.post("/webhooks/smsroute")
async def dlr(request: Request) -> Response:
raw = await request.body()
signature = request.headers.get("X-Smsroute-Signature", "")
expected = hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, signature):
raise HTTPException(status_code=401)
event = await request.json()
record = STORE.get(event["message_id"], {"status": None, "seen": set()})
if event["status"] in record["seen"]: # duplicate delivery attempt
return Response(status_code=204)
if record["status"] in TERMINAL: # out-of-order interim receipt
return Response(status_code=204)
record["seen"].add(event["status"])
record["status"] = event["status"]
STORE[event["message_id"]] = record
return Response(status_code=204) # ack fast; queue slow work
Three details in that handler matter more than the framework choice. compare_digest is
constant-time, so an attacker cannot recover the secret one byte at a time. The idempotency key is
message id plus status, not the whole payload, because retries are byte-identical and a
re-signed body would otherwise look new. And the terminal check runs before the write, so a late
ACCEPTD cannot resurrect a message that already delivered.
curl -X POST https://api.sendsmsnokyc.com/sms/send \
-H "Authorization: Bearer sk_live_YOUR_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: 9f2c-user_123-attempt_1" \
-d '{"to":"+33612345678",
"body":"@example.com #123456 Your code. Valid 10 minutes.",
"traffic_class":"otp"}'
Return 2xx only after the state is durable, and return 5xx when you want a
retry. A 4xx tells the sender the event will never be accepted, so it is the right answer
for a failed signature check and the wrong answer for a transient database error.
SMS pumping (AIT): the attack that looks like success
Artificial inflation traffic — also called SMS pumping, toll fraud or artificially inflated traffic — is the rare attack where every dashboard metric is green. An attacker scripts your "send code" endpoint against a block of numbers they control in an expensive destination, and your provider bills you for messages that are genuinely delivered. You pay; the attacker and the host operator share the revenue. There is no account takeover to detect, only a cost curve that does not match your signup curve.
Why per-IP rate limiting does not stop it
Pumping traffic is distributed by design: residential proxies, rotating mobile IPs, and real devices in real countries. An IP-based limit is trivially bypassed, and a CAPTCHA on the send button is only a speed bump if the attacker has humans or a solving service. The signal that actually distinguishes pumping is not the source address — it is the destination and the conversion.
| Control | Blocks | False-positive risk | Where it belongs |
|---|---|---|---|
| Per-MSISDN velocity (3 / 10 min) | Repeat sends to one number | Low | Application + provider |
| Per-prefix and per-country caps | Bulk attacks on one range | Medium — diaspora traffic | Provider / account settings |
| Daily spend ceiling per account | Runaway cost | Low | Billing |
| HLR / number-validity lookup | Deactivated and fake numbers | Low | Pre-send pipeline |
| Turnstile / CAPTCHA on trigger | Automated bursts | Medium — accessibility | Front end |
| OTP-to-signup ratio alerting | Detects the attack, does not block it | None | Observability |
The three metrics to put on a dashboard
- OTP-to-verified ratio. Normal consumer flows sit in a stable band. Pumping pushes the ratio toward zero because the attackers never complete the flow.
- Cost per verified account. If it doubles week over week while signups are flat, you are paying for messages that were never going to convert.
- Prefix concentration. A single country prefix accounting for a sudden majority of OTP volume is the clearest early signal, and it is visible before the invoice arrives.
Provider-side controls are the safety net, not the strategy. smsroute applies per-number throttles and country-level limits by default, but the application knows which account triggered a send and whether that account ever verified — information no provider has. Put the spend ceiling in billing, the velocity limit in the API, and the alert on the ratio.
Next: the authentication layer that consumes these codes is covered in SMS 2FA architecture, the equivalent backend walkthrough is in the Python integration guide, and per-destination costs are on the pricing page.
Frequently Asked Questions About OTP SMS Delivery
OTP (one-time password) is the broader category for any single-use code — magic links, passwordless login, transaction verification, and account recovery. 2FA (two-factor authentication) is one specific OTP use case: a second factor after password entry. All 2FA is OTP but not all OTP is 2FA.
Transactional OTPs (payment confirmations, login) should expire in 30–60 seconds. Recovery OTPs (password reset, account unlock) may last 5–10 minutes. Shorter windows are more secure; longer windows reduce user frustration on retry.
Non-Latin scripts (Cyrillic, Arabic, CJK, Devanagari) trigger UCS-2 encoding automatically. This reduces per-segment capacity from 160 characters (GSM-7) to 70 characters (UCS-2). smsroute detects the script in your message body and encodes optimally.
Prepend @yourdomain.com # to your OTP message. For example,
@example.com #123456 Your verification code. triggers iOS Messages to auto-populate the
code. The domain must match your app's verified domain in Info.plist.
Use idempotency keys. Include a deterministic key (e.g., sha256 of user_id + attempt number) in every request. smsroute caches the key for 24 hours — duplicate requests return the same message ID and code, preventing two different codes from being active simultaneously.
Yes — SMS is not end-to-end encrypted and can be intercepted at the carrier level via SS7 attacks. For high-security scenarios, use push notifications as the primary factor with SMS as fallback, or combine OTP with biometric verification.
Use a test API key (prefix sk_test_) to send to any test number. Responses are
deterministic and instant — the code is always "123456." No SMS is actually sent and no charges are
incurred. Ideal for CI/CD pipelines and integration testing.
From $0.004 per SMS across 149 countries. OTP messages are standard SMS with no upcharge. Crypto-only payments (BTC, USDT, ETH, LTC, XMR, SOL) with no KYC at signup. Minimum $5 top-up.
Delivery engineering questions
Measure API-to-submit, not API-to-handset. A well-run gateway answers the HTTP request and receives submit_sm_resp from the SMSC in well under 500ms at p99; that is the part any provider controls. Handset display adds one to five seconds of carrier paging and is outside every provider's control, so an SLA phrased as delivered to handset in under one second is not a claim anyone can honour.
Almost always a synchronous retry: the first submit timed out at the HTTP layer, your code retried, and both messages were accepted by the SMSC. Fix it with an idempotency key on every request (smsroute caches the key for 24 hours and returns the same message ID) and by retrying only after a delivery receipt reports a retryable state, never inside the user's request.
Layer destination-aware controls: a per-number velocity limit (3 sends per 10 minutes), per-prefix and per-country caps, a daily spend ceiling on the account, and Turnstile or a CAPTCHA on the trigger. Then alert on the OTP-to-signup ratio and cost per verified account. IP rate limits alone do not work because pumping traffic arrives from distributed residential and mobile addresses.
Only EXPIRED, and only once, via a different route. UNDELIV is retryable only when the carrier error code indicates a temporary condition rather than an invalid or barred destination. Never retry DELIVRD, and never retry REJECTD: a rejection is a content, sender-ID or policy decision that will repeat identically until the message itself changes.