Skip to content

Instantly share code, notes, and snippets.

@analytically
Created December 15, 2012 11:11
Show Gist options
  • Save analytically/4293859 to your computer and use it in GitHub Desktop.
Save analytically/4293859 to your computer and use it in GitHub Desktop.
Rate limiting code using Spray 1.0-M2, needs migration.
def rateLimit(action: String, subject: String, maxRequests: Int) = {
val key = action + ":" + subject
add(redis, key)
val actionCount = count(redis, key, interval)
transformRequestContext {
ctx =>
ctx.withResponseTransformed {
response =>
response.copy(headers =
// Number of requests allowed for that IP address per interval
CustomHeader("X-FeatureRateLimit-Limit", maxRequests.toString)
// Number of seconds in the rate limit interval
:: CustomHeader("X-FeatureRateLimit-IntervalSecs", interval.toString)
// Number of requests remaining.
:: CustomHeader("X-FeatureRateLimit-Remaining", "" + (maxRequests - actionCount))
// Time at which your quota is reset, in Unix epoch time
:: CustomHeader("X-FeatureRateLimit-Reset", "" + (System.currentTimeMillis() + (redis.withClient(client => client.ttl(key).getOrElse(0l) * 1000))))
:: response.headers)
}
} & filter {
ctx =>
if (actionCount >= maxRequests) {
logger.warn("Rate limiting user '" + subject + "': exceeded max number of requests (" + maxRequests + ").")
Reject(AuthorizationFailedRejection)
}
else Pass
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment