rstudio / plumber

Turn your R code into a web API.
https://www.rplumber.io
Other
1.39k stars 256 forks source link

Rate limit in plumber API #866

Open shahronak47 opened 2 years ago

shahronak47 commented 2 years ago

I want to implement rate limit for the plumber API. There are lot resources online describing how to implement it in a general way. Is there a resource/example which demonstrates how to implement it for R Plumber API and/or with Swagger?

meztez commented 11 months ago

@shahronak47

ratelimiter <- function(n, cycle = as.difftime(60, units = "secs")) {
  quota_use <- 0
  started <- Sys.time()
  reset <- function() {
    started <<- Sys.time()
    quota_use <<- 0
  }
  list(
    busted = function() {
      if ((Sys.time() - started) > cycle) reset()
      quota_use <<- quota_use + 1
      quota_use > n
    }
  )
}

limiter <- ratelimiter(3, 5)

#* @get /ratelimited
function(res) {
  if (limiter$busted()) {
    res$status <- 429
    res$serializer <- serializer_unboxed_json()
    return(list(error = "Too Many Requests"))
  }
  "Still under quota"
}