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).
limitis the number of requests allowed perkeywithin any rolling window ofwindowMsmilliseconds (a sliding window, not fixed one-minute buckets).nowis optional: a function returning the current time in ms. It defaults toDate.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 limitremaining: how many more requests this key can make right nowretryAfterMs:0if 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
RangeErroriflimitorwindowMsis 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
Already have an account?