philipbohun.com

Glojure by Example: Rate Limiting

time.Sleep between requests is the smallest limiter: each call starts only after the pause. The standard time package is available. A token bucket can be a buffered channel that a ticker refills.

(defn request [n]
  (println "request" n))

(doseq [n [1 2 3]]
  (request n)
  (time.Sleep (* 10 time.Millisecond)))
(println "paced")

A buffer of tokens allows a short burst, then further takes wait. This burst channel is filled twice and then consumed twice.

(require '[clojure.core.async :as async])

(def burst (async/chan 2))
(async/>! burst :token)
(async/>! burst :token)
(dotimes [i 2]
  (async/<! burst)
  (println "burst" i))

The paced requests print before the burst.

$ glj rate-limiting.glj
request 1
request 2
request 3
paced
burst 0
burst 1

Next example: Atomic Counters.