Skip to content

Commit

Permalink
Merge pull request #61 from realgenekim/master
Browse files Browse the repository at this point in the history
allow :rate-limiter/rate to be floats, to have floating points rates (0.5 => 1 req every 2 seconds)
  • Loading branch information
sunng87 authored Feb 16, 2024
2 parents 77d1560 + 9be2e64 commit 379424f
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ execution if the open condition triggered.

A rate limiter protects your code block to run limited times per
second. It will block or throw exception depends on your
configuration.
configuration. (:rate is a floating point number, and can be less than 1.0.
Example: 0.5 is once every two seconds.)

```clojure
(require '[diehard.core :as dh])
Expand Down
4 changes: 3 additions & 1 deletion src/diehard/spec.clj
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,9 @@
:timeout/on-failure]))

;; rate limiter
(s/def :rate-limiter/rate int?)
; allow floating point numbers, so that we can pass numbers such as 0.5, to signify 1 req / 2 seconds
;(s/def :rate-limiter/rate int?)
(s/def :rate-limiter/rate number?)
(s/def :rate-limiter/max-cached-tokens int?)

(s/def :rate-limiter/rate-limiter-new
Expand Down
21 changes: 20 additions & 1 deletion test/diehard/rate_limiter_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,23 @@
(.shutdown pool)
(t/is (< (Math/abs (- @counter (* rate time-secs)))
;; error tolerance 3%
(* 0.03 (* rate time-secs)))))))
(* 0.03 (* rate time-secs))))))

(t/testing "rate limits less than 1.0"
(let [rate 0.5
threads 1
pool (Executors/newFixedThreadPool threads)
rl (r/rate-limiter {:rate rate})
counter (atom 0)
time-secs 5]
(doseq [_ (range threads)]
(.submit pool (cast Runnable (fn []
(while true
(r/acquire! rl)
(swap! counter inc))))))
(Thread/sleep (* time-secs 1000))
(.shutdown pool)
(let [variance (Math/abs (- @counter (* rate time-secs)))]
(t/is (<= variance
;; error tolerance: 0.5 -- larger, because we are dealing with slower ticks
0.5))))))

0 comments on commit 379424f

Please sign in to comment.