OTP service system design: architecture, workflow and test cases
Written and reviewed by the DiOTP team Published 30 November 2026Last updated 30 November 2026
10 min read
OTP service system design looks simple on a whiteboard: make a random number, text it, compare it later. In production it has to survive bots, slow networks, retries, double clicks and people who wait too long. This guide covers the OTP service architecture piece by piece, the verification workflow as a state machine, the failure modes that catch teams out, and a set of OTP verification test cases. Where it helps, it uses the public behaviour of the DiOTP API as a worked example, so every rule is one you can test.
Requirements
Start by writing down what the system must do and what it must never do. A typical list for an OTP verification system looks like this.
Functional
- Send a short numeric code to a phone number for a stated purpose, such as login, signup or payment.
- Check a code the user types and return a clear yes or no, with a reason when it is no.
- Let the user ask for a new code, with a short wait between requests.
- Tell the calling app what happened after the send: delivered, failed or verified.
Non-functional
- Codes expire quickly and work once. DiOTP uses 5 minutes, 5 attempts and a single successful verify.
- Codes are unpredictable and never stored in plain text.
- Abuse costs the attacker more than it costs you: limits per number, per IP and per API key.
- Retries from the caller never send a second message.
- The send path stays responsive even when the message network is slow.
OTP service architecture: the components
A clean design splits the work into small parts with one job each. The diagram shows the path of one request through a generic design; it describes a pattern, not the internals of any particular service.
Request path
Your app (server)
|
| POST /otp/send (API key, Idempotency-Key)
v
+-------------+ limits OK? +----------------+
| OTP API |----------------->| Rate limiter |
+-------------+ +----------------+
|
| generate code (CSPRNG), store HMAC + expiry
v
+-------------+ +----------------+
| Database | | Message queue |
+-------------+ +----------------+
^ |
| v
| +----------------+
| delivery receipt | Sender worker |--> SMS provider --> phone
+--------------------------+----------------+
|
v
+-------------+
| Webhooks |--> your HTTPS endpoint (signed)
+-------------+The API layer
Two endpoints carry nearly all traffic: send and verify. The API authenticates the caller, validates the body, applies limits and returns fast. It never waits for the message to reach the phone; it returns a request ID and an expiry time as soon as the work is queued. See the OTP API docs for how DiOTP shapes these two calls.
Code generation
Use a cryptographically secure random number generator, such as crypto.randomInt in Node.js, secrets in Python or RandomNumberGenerator in .NET. A general-purpose random function is predictable enough to guess. Six digits is the usual length: short enough to type, and with five attempts an attacker has five chances in a million per code.
Hashed storage with expiry
Store a keyed hash of the code, never the code itself. A plain SHA-256 of a six-digit number can be reversed by trying all million values, so use an HMAC with a server-side secret. Store the expiry time next to it and check it on every verify, rather than trusting a cache to delete old rows on time.
Attempt counting
Increment the attempt counter in the same atomic update that checks the code. If the read and the write are separate, parallel requests can each see "4 attempts" and each get a guess, which defeats the limit.
Rate limits
Limit three things independently: the phone number, the client IP or device, and the API key. Per-number limits stop one phone being flooded. Per-IP limits slow down bots that cycle through numbers. Per-key limits cap the damage of a leaked key. DiOTP applies a 30-second resend cooldown, 3 codes per number per hour, 10 per day and 30 sends per API key per minute; the IP limit belongs in your own app, because only your app sees the end user's address. The SMS pumping protection guide explains why these limits matter so much.
Queue and provider handoff
Put the message on a queue and let a worker hand it to the SMS provider. The queue absorbs bursts, lets you retry a provider timeout without holding the user's HTTP request open, and gives you a single place to switch routes if one provider has trouble. In India the message must also match a registered DLT template, so the worker fills the code into an approved template rather than building free text.
Delivery receipts and webhooks
Providers report back whether a message was delivered or failed. Record those receipts against the request and pass them on to the calling app as webhooks. Sign each webhook with an HMAC and a timestamp so the receiver can reject forgeries and replays, and retry deliveries that do not get a 2xx reply. DiOTP's webhook events follow this pattern.
Idempotency
Mobile networks drop responses. When the caller retries a send, the system must recognise it and return the first result instead of texting again. Accept an Idempotency-Key header, store it with a hash of the body, and replay the stored response for a matching retry. Reject the same key with a different body, since that is almost always a bug.
Data model
One table for requests is enough for the core flow. Delivery events and webhook attempts can live in their own tables, keyed by request ID.
| Column | Type | Purpose |
|---|---|---|
| id | UUID | The request ID returned to the caller. |
| account_id | UUID | Which customer or API key made the request. |
| phone | text | Normalised number with country code. |
| purpose | text | login, signup, payment and so on. |
| code_hmac | bytes | Keyed hash of the code. Never the code. |
| status | enum | pending, verified, expired or failed. |
| attempts | integer | Wrong guesses so far. |
| expires_at | timestamp | Created time plus the code lifetime. |
| verified_at | timestamp | Set once, on the successful verify. |
| idempotency_key | text | Unique per account, with a hash of the request body. |
| delivery_status | text | Latest receipt from the provider. |
Index phone with created time for the per-number limits, and add a unique index on account and idempotency key. Clear out old code hashes on a schedule; once a request has ended, nothing needs them.
The OTP verification workflow as a state machine
Every request is in exactly one state, and each verify call either keeps it there or moves it on. Writing the states down removes most edge-case bugs.
States
correct code
pending ------------------------> verified
| \
| \ 5 wrong attempts
| +-----------------------> failed
|
| 5 minutes pass
+----------------------------> expired
verified, expired and failed are final.- pending: a code exists and can be tried. A wrong code returns invalid_code and adds an attempt.
- verified: the code matched once. Any later verify on this request is refused with already_verified.
- expired: the lifetime passed. The first verify after that reports expired; the request is then closed, so later calls report not_pending.
- failed: the attempts ran out. The user needs a fresh code.
Keep the transitions in one function or one database statement. Expiry should be checked at verify time against expires_at, so a request is never accidentally verified a second after its lifetime ends.
Failure modes and retries
- Provider timeout: retry from the worker with backoff, but only while the code is still valid. A text that arrives after expiry only confuses the user.
- Lost response to the caller: solved by the Idempotency-Key. DiOTP returns 503 sending_unavailable when it cannot send, and a retry with the same key is safe.
- Double submit of the verify form: the second call returns already_verified. Your app should treat that as a no-op, not an error screen.
- Webhook receiver down: retry on a schedule. DiOTP retries at 1 minute, 5 minutes, 30 minutes, 2 hours and 12 hours. Receivers must handle duplicates.
- Message never arrives: let the user resend after the cooldown, and consider WhatsApp as a second channel where it is enabled.
Security checklist
- Generate codes with a CSPRNG and compare them in constant time.
- Store only a keyed hash, and only until the request ends.
- Keep API keys on servers. Browsers and apps call your backend, which calls the OTP service.
- Bind the request ID to the session that asked for it, so a code cannot be used to verify someone else's attempt.
- Put a bot check in front of any public send button.
- Never log codes. Log request IDs and outcomes instead.
- Verify webhook signatures and reject old timestamps.
Our OTP security best practices guide goes deeper on the session and fraud side.
Build versus buy
Building your own OTP service is a reasonable choice in some cases. If you already send high volumes of SMS, hold your own DLT registration and provider contracts, have strict data-residency or audit rules, or need deep control over routing, an in-house service can pay off. The logic in this guide is not large, and a strong team can build it well.
The cost is in everything around the logic: provider contracts, DLT templates, delivery monitoring, limits tuned against abuse, webhook retries, on-call cover and keeping all of it current. For most teams whose product is not messaging, a hosted API is faster to ship and cheaper to run. A useful test is to list who would be paged when codes stop arriving at night. If there is no clear answer, buying is probably right for now, and you can revisit it as volume grows.
OTP verification test cases
These cases match DiOTP's documented behaviour, so you can run them against the API in test mode. If you build your own service, use them as the acceptance tests for your design.
| Case | Steps | Expected result |
|---|---|---|
| Successful send | POST /otp/send with a valid number. | 200 with request_id, channel and expires_at. |
| Correct code | Verify with the code that arrived. | 200 with verified true and verified_at. |
| Wrong code | Verify with a wrong code. | 400 invalid_code; the request stays pending. |
| Second verify | Verify the same request_id again after success. | 409 already_verified. |
| Verify after expiry | Wait more than 5 minutes, then verify. | 410 expired. |
| Verify again after expiry | Verify once more after the expired reply. | 409 not_pending. |
| Attempts used up | Send five wrong codes, then try again. | 429 too_many_attempts. |
| Unknown request | Verify a request_id that does not exist. | 404 not_found. |
| Malformed code | Verify with a code of 3 characters. | 422 invalid_request. |
| Quick resend | Send to the same number twice within 30 seconds. | 429 resend_cooldown; nothing sent or charged. |
| Hourly cap | Send a fourth code to one number within an hour. | 429 phone_hourly_limit. |
| Daily cap | Send an eleventh code to one number in a day. | 429 phone_daily_limit. |
| Key burst | Make more than 30 sends with one key in a minute. | 429 api_key_minute_limit. |
| Idempotent retry | Repeat a send with the same Idempotency-Key and body. | Same response as the first; no new message. |
| Key reuse | Same Idempotency-Key with a different body. | 409 idempotency_key_reused. |
| Bad API key | Send with a missing or wrong key. | 401 unauthorized. |
| Test mode | In test mode, send to a number other than your own. | 403 trial_restricted. |
| Channel off | Send with channel whatsapp before it is enabled. | 409 channel_not_enabled. |
| Forged webhook | Post to your webhook URL with a wrong signature. | Your endpoint rejects it with 401. |
Automate the cases that do not need a real phone, and keep a short manual run for the ones that do. Remember that resend and hourly limits apply across tests, so space out runs against the same number.
OTP API documentation Verify endpoint and errors SMS pumping protection
