Skip to content

feat: implement rateLimit() utility for function call throttling#80

Open
Rasagnika-GR wants to merge 1 commit into
moizycodes:mainfrom
Rasagnika-GR:issue-58-fix
Open

feat: implement rateLimit() utility for function call throttling#80
Rasagnika-GR wants to merge 1 commit into
moizycodes:mainfrom
Rasagnika-GR:issue-58-fix

Conversation

@Rasagnika-GR
Copy link
Copy Markdown
Contributor

🎯 Overview

Implements a reusable rateLimit() utility that restricts how many times a function can be called within a specified time interval. This is a common production pattern used to prevent API abuse, protect rate-limited endpoints, and control resource usage.

Closes #58

🔧 Changes Made

New File: utils/rateLimit.js

  • Implemented rateLimit(fn, config) using a counter + timestamp window approach
  • Resets call count automatically after the interval expires (lazy reset — no persistent timers)
  • Preserves function context and arguments via fn.apply(this, args)
  • Exported as a named ES6 export

Edge Cases Handled

  • Non-function input → throws TypeError
  • Missing or invalid config object → throws TypeError
  • limit <= 0 → throws RangeError
  • interval <= 0 → throws RangeError
  • Rapid consecutive calls exceeding limit → throws Error('Rate limit exceeded')

🧪 Testing

const limitedFn = rateLimit(apiCall, { limit: 3, interval: 1000 });

// Within limit — all resolve normally
limitedFn(); // ✅ allowed
limitedFn(); // ✅ allowed
limitedFn(); // ✅ allowed
limitedFn(); // ❌ throws Error('Rate limit exceeded')

// After 1000ms interval resets — allowed again
setTimeout(() => limitedFn(), 1000); // ✅ allowed

// Edge cases
rateLimit('not-a-function', { limit: 3, interval: 1000 }); // TypeError
rateLimit(apiCall, null);                                   // TypeError
rateLimit(apiCall, { limit: 0, interval: 1000 });          // RangeError
rateLimit(apiCall, { limit: 3, interval: -1 });            // RangeError

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature: Implement a rateLimit() Utility to Control Function Calls

1 participant