> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Reject or Queue SMS Rate Limit

> Strategies to handle SMS login send spikes by collapsing duplicate requests, per-phone cooldowns, queuing, and global rate limiting to prevent retry storms and respect provider throughput

When building SMS-based login (send a six-digit code to a phone number), your backend typically forwards send requests to an SMS provider (e.g., [Twilio](https://www.twilio.com/)). If the provider enforces a hard throughput limit, a sudden traffic spike can overwhelm your capacity. This article explains strategies to handle excess requests safely while preserving user experience and provider limits.

Assumptions

* Provider limit: 100 texts/sec
* Normal traffic: 20 texts/sec
* Burst traffic after an outage: 1,000 requests/sec

Your backend can only forward at 100/sec, so 900 requests/sec cannot be sent immediately. The question: what do you do with those excess requests?

![A stylized diagram titled "LOGIN BY SMS" showing many mobile phones and message dots funneling down into a backend system and then to a Twilio SMS box with rate limits noted. The graphic highlights message flow and throughput (e.g., 1,000/sec to the backend, Twilio limit 100/sec).](https://mintcdn.com/kodekloud-c4ac6d9a/2h0o-_DtLcLu6HM7/images/DevOps-Interview-Questions-and-Answers-Scenario-Based-Prep/System-Design/Reject-or-Queue-SMS-Rate-Limit/login-by-sms-twilio-rate-limits.jpg?fit=max\&auto=format\&n=2h0o-_DtLcLu6HM7\&q=85\&s=a58d3f337a399255cf44671bf822775d)

Callout: warning about retry storms

If you reject requests without a well-behaved client backoff, users tend to retry repeatedly (tap “Send code” many times), which can multiply the load and create a retry storm — a self-inflicted denial-of-service.

## Options

### Option A — Reject the extra requests

* Immediately return an error to clients that you couldn't send the code.
* Typical client behavior: users tap "Send code" again and again when they see an error.
* Retry storms: a few retries per user multiply the load. Example: 1,000 initial requests × 4 retries = 5,000 requests/sec — effectively a self-inflicted DoS.

![A dark infographic slide with the headline "REJECT THEM" and a circled "A" showing a grid of smartphones all displaying error messages. The graphic illustrates "Thousands of users retry" and a denial-of-service scenario with traffic rising to \~5,000 requests/sec.](https://mintcdn.com/kodekloud-c4ac6d9a/2h0o-_DtLcLu6HM7/images/DevOps-Interview-Questions-and-Answers-Scenario-Based-Prep/System-Design/Reject-or-Queue-SMS-Rate-Limit/reject-them-dos-5000-phone-errors.jpg?fit=max\&auto=format\&n=2h0o-_DtLcLu6HM7\&q=85\&s=b96b26a546658f27b32a6438bc1df218)

### Option B — Accept and enqueue every request

* Accept each request and append it to a queue; return success to the user ("Code sent").
* Dequeue at the provider limit (100/sec). This prevents client retries but allows the queue to grow large.
* Problem: codes can arrive very late. Time-limited login codes become useless if delayed beyond their TTL, harming UX and security.

![A dark infographic showing an SMS delivery flow: a backend sends messages into a growing queue which forwards to Twilio SMS while many phone icons show success or failure. Headings read "QUEUE THEM" and "CODE ARRIVES LATE," illustrating delayed code delivery.](https://mintcdn.com/kodekloud-c4ac6d9a/2h0o-_DtLcLu6HM7/images/DevOps-Interview-Questions-and-Answers-Scenario-Based-Prep/System-Design/Reject-or-Queue-SMS-Rate-Limit/sms-delivery-queue-twilio-delayed-codes.jpg?fit=max\&auto=format\&n=2h0o-_DtLcLu6HM7\&q=85\&s=da96de63f1bdae9ba80e90dadd3ef50b)

### Option C — Collapse duplicates + intelligent throttling (recommended)

* Treat requests for the same phone number as duplicates within a short window (cooldown).
  * If a code was recently sent (or already scheduled), return a success response without enqueuing another message.
  * This collapses N attempts by the same user into 1 provider call and prevents retry storms.
* Combine with:
  * Per-phone cooldown (e.g., one SMS per phone per 60–120 seconds).
  * Global rate limiting (e.g., token bucket) to protect provider capacity.
  * Queue trimming: drop older/outdated messages for the same phone, or enforce a maximum queue depth and TTL for queued items.
  * Client-side UX: disable the "send code" button briefly after it is pressed and show remaining cooldown time.
  * Proper status codes and headers: when rejecting, return `429 Too Many Requests` with a `Retry-After` header to help well-behaved clients back off.

## Strategy comparison

| Strategy | When to use | Pros | Cons |
| - | -: | - | - |
| Reject aggressively | If strict provider limits and clients respect backoff | Keeps provider load low and predictable | Risk of retry storms if clients ignore backoff; poor UX |
| Enqueue everything | If you want no client-visible failures and can tolerate delays | Minimizes client retries | Large queues, late or expired codes, higher costs |
| Collapse duplicates + throttling | Most production cases where UX and predictability both matter | Prevents retry storms, reduces queue size, good UX | More complex server logic and per-phone state required |

## Implementation pattern — Redis coalescing lock per phone

Key idea: set a short lock/flag for a phone number in Redis when a code is sent or scheduled. If another request arrives while the key exists, treat it as a duplicate and return a success-like response without enqueuing another SMS.

High-level steps:

1. On request, compute `key = sms:last_sent:{phone}`.
2. Try to create the key atomically with expiry (SET NX EX).
3. If set succeeds:
   * Generate a code.
   * Enqueue send job (e.g., push to Redis list or broker).
   * Return success.
4. If key exists:
   * Return success or informative response without enqueuing.
   * Include `Retry-After` header (ttl of the key) so clients can show cooldown.

Example (Flask + Redis — conceptual):

```python theme={null}
from flask import Flask, request, jsonify, make_response
import redis
import time
import random

r = redis.Redis()  # configure host/port as needed
app = Flask(__name__)

CODE_TTL = 120  # seconds; time that "code sent" status should be considered recent
RATE_LIMIT_KEY = "sms:last_sent:{}"  # phone -> timestamp

@app.route("/send_code", methods=["POST"])
def send_code():
    phone = request.json.get("phone")
    if not phone:
        return jsonify({"error": "phone required"}), 400

    key = RATE_LIMIT_KEY.format(phone)

    # Use an atomic SET with NX and EX to create the per-phone lock and expiration
    # redis-py: set(..., nx=True, ex=seconds) returns True if set, None otherwise
    if not r.set(key, int(time.time()), nx=True, ex=CODE_TTL):
        # A code was recently sent or scheduled for this phone; return success to avoid duplicates
        retry_after = r.ttl(key)
        resp = make_response(jsonify({"message": "Code already sent"}), 200)
        # Include Retry-After to help well-behaved clients prevent immediate retries
        resp.headers["Retry-After"] = str(retry_after if retry_after > 0 else CODE_TTL)
        return resp

    # Generate a 6-digit code (zero-padded)
    code = f"{random.randint(0, 999999):06d}"

    # Enqueue the SMS send job (e.g., push to a queue or message broker)
    r.lpush("sms_queue", f"{phone}:{code}")

    return jsonify({"message": "Code sent"}), 200
```

Notes on global capacity saturation

* Maintain a global token bucket or semaphore representing available sends to provider.
* When tokens are exhausted:
  * For coalesced requests (duplicates for phones with recent keys), you can return `200` without enqueueing (because there is already a scheduled send).
  * For new/different phones, return `429 Too Many Requests` with `Retry-After` until capacity returns.

Collapsing duplicate requests per phone plus a short cooldown gives the best balance of UX and operational safety: it prevents retry storms, keeps queue sizes manageable, and delivers codes promptly for most users.

## Summary checklist

* Enforce per-phone cooldowns to collapse retries.
* Use a global rate limiter (token bucket) to protect provider throughput.
* Avoid enqueuing everything blindly; enforce TTLs and queue limits.
* Return appropriate HTTP status codes:
  * `200` for collapsed successes (where a code was recently sent),
  * `429 Too Many Requests` for rate-limited requests where no collapse is possible.
  * Include `Retry-After` headers so clients can back off.
* Improve client UX: disable resend button, display cooldown timer, and handle `Retry-After`.

Which approach to choose depends on your business goals (UX vs. strict rate control) and tolerance for delayed messages. In practice, combine coalescing, sensible cooldowns, and global throttling for a robust solution.

## Links and references

* [Twilio](https://www.twilio.com/)
* [Redis](https://redis.io/)
* Token bucket algorithm: [Token Bucket — Wikipedia](https://en.wikipedia.org/wiki/Token_bucket)
* HTTP 429: [MDN — 429 Too Many Requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429)
* `Retry-After` header: [MDN — Retry-After](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After)
* Flask: [Flask documentation](https://flask.palletsprojects.com/)

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/devops-interview-prep/module/ef53ec43-96e9-4d1b-8a6e-e6eb97b0d0dc/lesson/919765e2-a3ea-42a9-a6dd-d6b402292c7c)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.