research/rate-limiting-a-contact-form

Rate-Limiting a Contact Form Endpoint: A Fixed Window Against a Token Bucket, Tested With a Burst

Engineering Note · November 24, 2026 · 10 minute read · Node.js · Rate limiting · Forms · Testing

For a contact form, a token bucket is the better rate limiter. We gave a fixed window and a token bucket the same budget, five messages a minute per visitor, and sent each the same traffic. Against a plain burst of 20 simultaneous requests they behaved the same: 5 accepted, 15 refused. The difference was at the edge of a window. Ten requests sent across the minute boundary, in under one second, all got through the fixed window; the token bucket let through 5. The token bucket also gave a more useful Retry-After: 12 seconds instead of 42. A person resubmitting every 20 seconds was never refused by either.

Everything below was run on Linux with Node.js 22.23.5, using node:http and the built-in fetch. No packages were installed. The outputs are the real ones from these runs.

Why rate-limit a contact form at all?

A contact form endpoint accepts text from anyone on the internet and usually does something with it: saves it, emails it, maybe sends it to a spam filter or a model. A script can call it thousands of times a minute. Even with a bot check in front, a rate limit is the cheap second line: it caps how much one sender can make the endpoint do.

It has to stay invisible to real people. Someone who types a message, sees a slow response and presses Send again must not be told to go away.

What are the two limiters?

Both take a key (here, the client’s IP address) and return whether the request may go ahead. Both take a now function so the tests can control the clock.

// limiters.mjs: two limiters with the same budget, 5 requests per 60 seconds per key.
export function fixedWindow({ limit, windowMs, now = Date.now }) {
  const counts = new Map(); // key -> { window, count }
  return (key) => {
    const window = Math.floor(now() / windowMs);
    const entry = counts.get(key);
    if (!entry || entry.window !== window) {
      counts.set(key, { window, count: 1 });
      return { ok: true, remaining: limit - 1 };
    }
    if (entry.count >= limit) {
      const retryMs = (window + 1) * windowMs - now();
      return { ok: false, retryAfter: Math.ceil(retryMs / 1000) };
    }
    entry.count++;
    return { ok: true, remaining: limit - entry.count };
  };
}

export function tokenBucket({ capacity, refillPerMs, now = Date.now }) {
  const buckets = new Map(); // key -> { tokens, at }
  return (key) => {
    const t = now();
    const b = buckets.get(key) ?? { tokens: capacity, at: t };
    b.tokens = Math.min(capacity, b.tokens + (t - b.at) * refillPerMs);
    b.at = t;
    buckets.set(key, b);
    if (b.tokens < 1) {
      return { ok: false, retryAfter: Math.ceil((1 - b.tokens) / refillPerMs / 1000) };
    }
    b.tokens -= 1;
    return { ok: true, remaining: Math.floor(b.tokens) };
  };
}

The fixed window divides time into one-minute blocks that start on the minute. It counts requests per key in the current block and refuses the sixth. When the next block starts, the count starts again.

The token bucket gives each key a bucket holding up to five tokens. Each request spends one. Tokens drip back at one every 12 seconds, which is five a minute, and the bucket never holds more than five. There is no reset moment: the allowance refills continuously.

Neither stores anything but a number and a time per key, and neither needs a timer.

What does the server look like?

A minimal endpoint that answers POST /contact, keyed by the client’s address. A refused request gets 429 Too Many Requests with a Retry-After header in seconds.

// server.mjs
import http from 'node:http';
import { fixedWindow, tokenBucket } from './limiters.mjs';

const kind = process.argv[2];
const limiter = kind === 'fixed'
  ? fixedWindow({ limit: 5, windowMs: 60_000 })
  : tokenBucket({ capacity: 5, refillPerMs: 1 / 12_000 });

const server = http.createServer((req, res) => {
  if (req.method !== 'POST' || req.url !== '/contact') {
    res.writeHead(404).end();
    return;
  }
  const key = req.socket.remoteAddress;
  const verdict = limiter(key);
  if (!verdict.ok) {
    res.writeHead(429, { 'Retry-After': String(verdict.retryAfter) });
    res.end('Too many messages. Please try again shortly.\n');
    return;
  }
  req.resume();
  req.on('end', () => res.writeHead(200).end('Thanks, we got your message.\n'));
});
server.listen(0, '127.0.0.1', () => console.log(server.address().port));

The limiter runs before the body is read, so a refused request costs almost nothing.

What happened with a burst of 20 requests?

The burst script fires 20 POSTs at once with Promise.all and tallies the status codes:

// burst.mjs
const [port, n] = [process.argv[2], Number(process.argv[3] ?? 20)];
const started = performance.now();
const results = await Promise.all(
  Array.from({ length: n }, () =>
    fetch(`http://127.0.0.1:${port}/contact`, { method: 'POST', body: 'name=Test&message=Hi' })
      .then(async (r) => ({ status: r.status, retry: r.headers.get('retry-after') }))
  )
);
const ms = (performance.now() - started).toFixed(0);
const tally = {};
for (const r of results) tally[r.status] = (tally[r.status] ?? 0) + 1;
console.log(`${n} requests in ${ms} ms:`, tally,
  'Retry-After values:', [...new Set(results.filter(r => r.retry).map(r => r.retry))].join(', '));

Run against each server in turn:

== fixed
20 requests in 55 ms: { '200': 5, '429': 15 } Retry-After values: 42
== bucket
20 requests in 70 ms: { '200': 5, '429': 15 } Retry-After values: 12

The same five got through each time. The Retry-After values differ. The fixed window can only say “wait until the next minute starts,” which happened to be 42 seconds away on this run; it could have been anything from 1 to 60. The token bucket says “wait until you have earned one more token,” which is 12 seconds whenever the bucket is empty.

For a form, 12 seconds is a message a person can live with. 42, or 59, reads as being blocked.

What happens at the edge of a window?

A plain burst does not show the fixed window’s weakness. Timing does. The next script swaps the real clock for a variable and replays four kinds of traffic through both limiters side by side:

// boundary.mjs
import { fixedWindow, tokenBucket } from './limiters.mjs';

let clock = 0;
const now = () => clock;
const make = () => ({
  fixed: fixedWindow({ limit: 5, windowMs: 60_000, now }),
  bucket: tokenBucket({ capacity: 5, refillPerMs: 1 / 12_000, now }),
});

// Scenario 1: 10 requests straddling a window edge, 0.1 s apart,
// from 59.5 s to 60.4 s.
let l = make();
const edge = { fixed: 0, bucket: 0 };
for (let i = 0; i < 10; i++) {
  clock = 59_500 + i * 100;
  for (const k of ['fixed', 'bucket']) if (l[k]('ip').ok) edge[k]++;
}
console.log('10 requests from 59.5 s to 60.4 s, accepted:', edge);

// Scenario 2: a bot that sends 10 at the end of every window for 5 minutes.
clock = 0; l = make();
const bot = { fixed: 0, bucket: 0 };
for (let w = 0; w < 5; w++) {
  for (let i = 0; i < 10; i++) {
    clock = w * 60_000 + 59_500 + i * 100;
    for (const k of ['fixed', 'bucket']) if (l[k]('ip').ok) bot[k]++;
  }
}
console.log('bot, 50 requests at window edges over 5 min, accepted:', bot);

// Scenario 3: a person who submits, sees an error, and resubmits
// every 20 seconds, 8 times.
clock = 0; l = make();
const person = { fixed: [], bucket: [] };
for (let i = 0; i < 8; i++) {
  clock = 10_000 + i * 20_000;
  for (const k of ['fixed', 'bucket']) person[k].push(l[k]('ip').ok ? 'ok' : '429');
}
console.log('person every 20 s:', person);

// Scenario 4: steady flood of 1 request per second for 10 minutes.
clock = 0; l = make();
const flood = { fixed: 0, bucket: 0 };
for (let s = 0; s < 600; s++) {
  clock = s * 1000;
  for (const k of ['fixed', 'bucket']) if (l[k]('ip').ok) flood[k]++;
}
console.log('1 req/s for 10 min (600 requests), accepted:', flood);

The output:

10 requests from 59.5 s to 60.4 s, accepted: { fixed: 10, bucket: 5 }
bot, 50 requests at window edges over 5 min, accepted: { fixed: 30, bucket: 25 }
person every 20 s: {
  fixed: [
    'ok', 'ok', 'ok',
    'ok', 'ok', 'ok',
    'ok', 'ok'
  ],
  bucket: [
    'ok', 'ok', 'ok',
    'ok', 'ok', 'ok',
    'ok', 'ok'
  ]
}
1 req/s for 10 min (600 requests), accepted: { fixed: 50, bucket: 54 }

Reading them in order:

TrafficFixed window acceptedToken bucket accepted
10 requests across one window edge, in 0.9 s105
50 requests at window edges over 5 minutes3025
A person resubmitting every 20 s, 8 times8 of 88 of 8
1 request a second for 10 minutes5054

The window edge is the fixed window’s known weakness. Five requests land in the last half-second of minute one, five more in the first half-second of minute two, and each window sees only five. Ten got through in under a second, twice the intended burst. The bucket started full, spent its five tokens, and had earned nothing more by 60.4 seconds.

The edge-timed bot shows the same thing over time. The fixed window let it through 30 times in five minutes instead of 25.

The person was never refused by either. Eight submissions 20 seconds apart is a steady rate of three a minute, under the budget.

The steady flood went the other way: the bucket accepted 54 to the fixed window’s 50. The bucket starts full, so it allowed the first five at once, then one every 12 seconds for the rest of the ten minutes. Over a long run both converge on the same average. The bucket’s advantage is the cap on how much arrives at once, not a lower total.

Which one should a contact form use?

The token bucket. The extra code is about four lines, and it buys:

  • A hard cap on bursts, with no edge to aim at.
  • A Retry-After that is short and predictable, which matters when a real person sees the message.
  • A natural fit for “a few quick resubmits are fine, a stream is not.”

A fixed window is still fine where the limit is a budget rather than a burst control. A daily cap on an expensive call, counted per calendar day, is a fixed window, and that is what we use in Rate-limiting an AI endpoint with a single D1 table. A few extra calls at midnight do not matter there.

What else does the endpoint need?

  • A cleanup. Both limiters keep one entry per address forever. Delete entries older than the window, or a full bucket, on a timer or when the map passes a size you choose.
  • The right key. Behind a proxy or CDN, req.socket.remoteAddress is the proxy’s address, so every visitor shares one bucket. Use the client address the proxy forwards, and only trust that header from your own proxy.
  • A friendly message. The form should show the 429 response’s text and keep what the person typed, so a refusal costs them nothing but a short wait.
  • A save before anything else can fail. A rate limit protects the endpoint; it does not protect the message. We cover that order in Isolating Failures in a Form Pipeline.

Limitations

  • Both limiters live in one process’s memory. On hosting that runs several copies of the code, or starts new copies on demand, each copy counts separately, and the effective limit is the per-copy limit times the number of copies. The counter then belongs in a shared store.
  • The window-edge, bot, person and flood scenarios ran against a simulated clock, calling the limiter functions directly. Only the burst of 20 went through a real HTTP server.
  • All requests came from 127.0.0.1, so every request in a test shared one key. We did not test many keys, memory growth or cleanup.
  • The budget of five a minute is an example for the test, not a recommendation for your form.

Frequently asked questions

What is the difference between a fixed window and a token bucket rate limiter?

A fixed window counts requests in clock-aligned blocks, such as each calendar minute, and resets the count when the next block starts. A token bucket gives each visitor a small allowance that refills at a steady rate, and each request spends one token. Both cap the average rate; the token bucket also caps how much can arrive at once.

Why does a fixed window let through twice the limit?

Because the count resets at the window edge. A sender can use the full allowance in the last moments of one window and again at the start of the next. In our test with a limit of 5 per minute, 10 requests sent between 59.5 and 60.4 seconds were all accepted by the fixed window, while the token bucket accepted 5.

What rate limit should a contact form use?

Low enough to stop a script and high enough never to bother a person. We tested five per minute per visitor with a bucket that refills one message every 12 seconds. A simulated person resubmitting every 20 seconds was never refused, while a burst of 20 had 15 refused. Pick a number from your own form's traffic, not ours.

What should a rate-limited form return?

An HTTP 429 Too Many Requests status, a Retry-After header saying how many seconds to wait, and a short human message the form can show. In our test the fixed window told the burst to wait 42 seconds, the time left in its minute, while the token bucket said 12 seconds, the time to earn one more token.

Is an in-memory rate limiter enough in production?

Only when one long-running process handles every request. On hosting that runs several copies of your code, or starts fresh copies on demand, each copy has its own memory and its own counts, so the real limit is multiplied. Keep the counter in a shared store, such as the database the form already writes to.

More from Research

← All research