Skip to content

Instantly share code, notes, and snippets.

@pebrc
Last active March 14, 2019 20:42
Show Gist options
  • Save pebrc/498f5f4c25d45fa705d183b3a1560e03 to your computer and use it in GitHub Desktop.
Save pebrc/498f5f4c25d45fa705d183b3a1560e03 to your computer and use it in GitHub Desktop.
Mob programming a simple rate limiter
(ns rate-limiter
(:require [clojure.core.async :refer [go-loop] :as async]))
(def config {:num-mseconds 5000 :max-requests 10})
(def counter (atom 0))
(defn rate-limited? [counter]
(>= @counter (:max-requests config)))
(defn request []
(when-not (rate-limited? counter)
(swap! counter inc)))
(def stop (async/chan))
(defn start []
(go-loop []
(let [c (async/timeout (:num-mseconds config))
[_ chan] (async/alts! [c stop])]
(println "***" (= chan c))
(when (= chan c)
(reset! counter 0)
(recur)))))
(defn do-n-requests [count]
(dotimes [n count]
(println (request))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment