Last active
March 14, 2019 20:42
-
-
Save pebrc/498f5f4c25d45fa705d183b3a1560e03 to your computer and use it in GitHub Desktop.
Mob programming a simple rate limiter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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