Skip to content

Instantly share code, notes, and snippets.

@nmische
Last active September 25, 2015 06:58
Show Gist options
  • Save nmische/881766 to your computer and use it in GitHub Desktop.
Save nmische/881766 to your computer and use it in GitHub Desktop.
Simple time based limiter
<!--- set up app --->
<cfapplication name="ratelimit"/>
<cfif not StructKeyExists(application,"limiter") or StructKeyExists(url,"reset")>
<cfset application.limiter = CreateObject("component","TimeBasedRateLimiter")/>
</cfif>
<!--- check our limiter --->
<cfif application.limiter.requestsRemaining() gt 0>
<cfset application.limiter.push() />
<p>Request was successful.</p>
<cfelse>
<p>Request was not successful.</p>
</cfif>
<!--- show how many requests we have left --->
<cfoutput>
<p>You have #application.limiter.requestsRemaining()# requests remaining.</p>
</cfoutput>
component {
variables.stack = [];
variables.requestLimit = 100;
variables.timeLimitInSeconds = 60;
public function push() {
lock name="timeBasedRateLimiter" type="exclusive" timeout="30" {
ArrayAppend(variables.stack,Now());
}
}
public function requestsRemaining() {
return variables.requestLimit - size();
}
private function size() {
lock name="timeBasedRateLimiter" type="exclusive" timeout="30" {
while ((ArrayLen(variables.stack) gt 0) and (DateDiff('s',variables.stack[1],Now()) gt variables.timeLimitInSeconds)) {
ArrayDeleteAt(variables.stack,1);
}
}
return ArrayLen(variables.stack);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment