Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sliding window example
(defn- new-window [counter prev ts]
(assoc counter :curr 0 :prev prev :last-ts ts))
(defn- increase-count [counter val ts]
(assoc counter :curr val :last-ts ts))
(defn- inc! [counter]
(swap! counter
(fn [{:keys [prev curr last-ts window-ms window-allow] :as atm}]
(let [now (new java.util.Date)
elapsed (- (.getTime now) (.getTime last-ts))]
(println "elapsed:" elapsed "window-ms" window-ms)
(if (> elapsed window-ms)
;; "reset" counter
(new-window atm curr now)
;; ELSE check if rate is OK
(let [ratio (/ (- window-ms elapsed) window-ms)
rate (+ (* prev ratio)
curr)]
(println "ratio: " (float ratio) "rate per $window: " (float rate) "max per $window: " window-allow)
(if (> rate window-allow)
(do (println "Blocked OR Queued!")
atm)
(increase-count atm (inc curr) now))))))))
(inc! gcounter) ;; call multiple times
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment