API Protection: Rate Limiting, Replay Prevention, Idempotency, and Validation
🎯 Introduction
By the end of this article, you will be able to distinguish rate control, duplicate request handling, and malicious replay and choose appropriate server protections.
⏱ Control request counts with rate limiting middleware
Login and verification code endpoints need attempt limits. Express projects can use express-rate-limit to configure a time window and count without maintaining a counter table manually.
Install the dependency for this section:
npm install express-rate-limit@8.7.1
Create rate-server.mjs:
import express from 'express';
import { rateLimit } from 'express-rate-limit';
const app = express();
Allow five requests per minute:
const limiter = rateLimit({
windowMs: 60_000,
limit: 5,
standardHeaders: 'draft-8',
legacyHeaders: false,
message: { error: 'Too many requests. Try again later' }
});
windowMs is the counting window in milliseconds; limit is the allowed number of requests in that window. This uses the default client-address key. standardHeaders returns rate limit information, and legacyHeaders: false disables the older header format.
🚪 Rate-limit before protected operations
Attach the middleware to the test endpoint:
app.get('/limited', limiter, (req, res) => {
res.json({ allowed: true });
});
app.listen(3000, '127.0.0.1');
Run node rate-server.mjs and request /limited repeatedly within one window. The first five requests return 200; the sixth returns 429 with a message and Retry-After indicating how long to wait. Access resumes after the window resets.
On login or verification code endpoints, place limiter before password computation or email sending so over-limit requests never reach those expensive operations.
🗃 Check counter scope when deploying
The default counter store is process-local and suits local verification. Multiple instances need a shared store so switching servers does not grant another allowance.
Behind a reverse proxy, configure trusted proxies for the actual chain. Otherwise, all users may be counted under the proxy address, or forged client addresses may be trusted. Do not trust every proxy unconditionally just to make limiting work.
Address-only counting can affect several users on one network. Sensitive endpoints often also need account- and operation-based quotas, with limits chosen according to business risk.
🔁 Idempotency protects legitimate retries
If the connection drops after record creation, the client may retry without knowing whether it succeeded, creating a duplicate. Require a client-generated idempotency key for the same business operation:
POST /api/v1/reports HTTP/1.1
Idempotency-Key: 8bc47c4e-0d44-42ca-852f-8ad93984db99
Content-Type: application/json
{"title":"This week's notes"}
Here, idempotency means retries of one creation operation still create only one report. Idempotency-Key identifies that operation and must remain unchanged across retries.
The server stores the current user, endpoint, key, submitted content, and result. Suppose the first request creates report 12. Subsequent requests are handled as follows:
| Subsequent request | Server behavior |
|---|---|
| Same key and title | Return report 12 without creating another |
| Same key with a different title | Return 409: one key cannot represent two different operations |
| Original request is still running | Return the agreed in-progress response so the client can check or retry later |
The header alone does not prevent duplicates. The database must reject duplicate keys for the same user and endpoint, and report creation and result storage must succeed or fail together. These are the roles of unique constraints and transactions, respectively.
🛑 Replay prevention: Stop copied requests from executing again
Suppose a video processing platform notifies your endpoint when processing completes. Your server then creates an in-app “Video processing complete” message for the user.
If someone copies that request and sends it ten more times, creating a message on every receipt would produce duplicates. Sending a copied valid request again is replay; replay prevention stops those copies from executing the operation again.
First verify that the notification comes from the platform
Third-party notifications usually include a signature: verification data generated from the request content and an agreed key. Use the platform's library to verify the signature and establish trust in the sender and content. Reject verification failures.
A copied request includes the unchanged content and signature, so it may still verify successfully. A valid signature establishes trusted content, not that this is its first delivery.
Then check whether the notification was already processed
Platforms usually provide an event ID such as evt_123 to distinguish notifications. Store successfully processed event IDs in the database:
| Notification received | Server behavior |
|---|---|
First receipt of evt_123 | Create one in-app message and save the event processing record |
Another receipt of evt_123 | Create no further message; acknowledge success according to the platform protocol |
New event evt_124 | Process as a separate notification |
The database must allow each platform/event ID pair only once, and message creation and processing-record storage must succeed or fail together. Concurrent duplicates then cannot each create a message, while failed processing remains retryable.
Platforms may also retry because they did not receive your success response; duplicates do not necessarily mean an attack. Once an event succeeds, do not execute it again. This also uses the idempotent handling described above.
Reject stale requests when a sending timestamp is available
If the platform signs the sending timestamp, use its verification mechanism to check the time too. For example, a five-minute acceptance window rejects a request sent ten minutes ago. The timestamp must be signed; otherwise, someone replaying the request can change it to the current time.
Follow the platform's protocol for the actual window. Duplicates can still arrive within five minutes, so timestamp checks do not replace event ID checks.
🧭 These three protections serve different purposes
| Protection | Question answered | What it does not solve |
|---|---|---|
| Rate limiting | Are there too many requests within a time window? | Low-frequency duplicates can still execute repeatedly |
| Idempotency | How are repeated submissions of one business operation handled? | Does not prove the request comes from a trusted identity |
| Replay prevention | Is an old valid message being reused? | Does not replace field validation or authorization |
Every modification still requires identity, data scope, and field checks. An idempotency key is not an authentication credential and must not expose another user's results.
❓ Questions and Answers
Q1: Can every retry generate a new idempotency key?
No. Retries of the same business operation must reuse the original key, or the server will treat them as different operations.
Q2: Is adding a timestamp sufficient to prevent replay?
No. Requests can repeat within the valid time window. Verify the signature and check whether the event was already processed.
Q3: Can idempotency records be deleted immediately?
Do not delete them while clients may still retry. Retain them for the agreed retry window and manage expiration cleanup.
🧪 Practice
Choose rate limit keys and idempotency rules for “send a verification code” and “create a report.” Explain when duplicate requests should be rejected, wait, or receive the original result.
// Write your code or record your verification results here
