Skip to content

Instantly share code, notes, and snippets.

@mping
Created November 19, 2020 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mping/75cd4b050e7d70a4d9a0fefc4724748b to your computer and use it in GitHub Desktop.
Save mping/75cd4b050e7d70a4d9a0fefc4724748b to your computer and use it in GitHub Desktop.
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