Build a feature from a spec

Skill
Building with AI
Time
About 45 min
Access
Full track

Your API is being hammered by one client. Build a small in-memory rate limiter to this spec. Use AI to write as much of it as you like, but you’re responsible for it matching the spec exactly.

Spec

createRateLimiter({ limit, windowMs, now }) returns an object with one method, check(key).

  • limit is the number of requests allowed per key within any rolling window of windowMs milliseconds (a sliding window, not fixed one-minute buckets).
  • now is optional: a function returning the current time in ms. It defaults to Date.now. Tests use it to control time.
  • check(key) records the request if it’s allowed and returns { allowed, remaining, retryAfterMs }:
    • allowed: whether this request is within the limit
    • remaining: how many more requests this key can make right now
    • retryAfterMs: 0 if allowed; otherwise the ms until the next request would be allowed
  • Blocked requests are not counted against the limit.
  • Different keys are independent.
  • Memory must not grow forever as new keys come and go.
  • Throw a RangeError if limit or windowMs is not a positive integer.

Submit

Your implementation and your tests. The tests should control time through now rather than waiting.

rate-limiter.js
// rate-limiter.jsfunction createRateLimiter({ limit, windowMs, now = Date.now }) {  // TODO} module.exports = { createRateLimiter }; // Example:// const limiter = createRateLimiter({ limit: 2, windowMs: 1000 });// limiter.check('ip-1'); // { allowed: true,  remaining: 1, retryAfterMs: 0 }// limiter.check('ip-1'); // { allowed: true,  remaining: 0, retryAfterMs: 0 }// limiter.check('ip-1'); // { allowed: false, remaining: 0, retryAfterMs: <ms until the first request expires> }

This task is in the full track

You can read the brief above. To submit it, unlock all 10 tasks for $9, once. Unlimited resubmissions, and a full refund within 7 days if it isn’t useful.

Create a free account to get your review

Your answer stays here. Reviews are saved to your account so you can come back to them.

or with email

At least 8 characters, with a number and both upper and lower case letters.

Already have an account?