MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

NodeJS Program to In-Memory Rate Limiter with Explanation

NodeJS Hard HTTP & APIs 31 views
This problem helps you practice core NodeJS fundamentals in a practical way. It builds intuition around in-memory, rate, limiter. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Limit to 3 requests per minute per key (demo counter).

Input Format

No input.

Output Format

Start server code.

Constraints

Use Map for counts.

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
const http = require('http'); const hits = new Map(); function allow(key) { const now = Date.now(); const win = 60 * 1000; const rec = hits.get(key) || { count: 0, start: now }; if (now - rec.start > win) { rec.count = 0; rec.start = now; } rec.count += 1; hits.set(key, rec); return rec.count <= 3; } const server = http.createServer((req, res) => { const key = (req.socket.remoteAddress || 'local') + '|meetcode'; if (!allow(key)) { res.writeHead(429, { 'Content-Type': 'text/plain' }); return res.end('Too many'); } res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('OK'); }); server.listen(3006, () => console.log('http://localhost:3006'));

Output Example

No sample I/O is provided for this question.

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next