     (reset! log-msgs [])))
 ; messages
 (defonce all-msgs (ref [{:id (next-id) :time (now) :msg "Добро пожаловать в чат!" :author "system"}]))
+(defn clear-old-msgs []
+  (dosync
+    (let [total (count @all-msgs)]
+      (if (> total 4096)
+        (ref-set all-msgs (vec (drop (- total 4096) (sort-by :id < @all-msgs))))
+        (ref-set all-msgs @all-msgs)))))
 (defn add-msg-to-storage [msg]
-  (dosync (let [all-msgs* (conj @all-msgs msg)] (ref-set all-msgs all-msgs*))))
+  (dosync
+    (let [all-msgs* (conj @all-msgs msg)] (ref-set all-msgs all-msgs*))
+    (clear-old-msgs)))
 (defn min-msg-id []
   (apply min (map (fn [msg] (:id msg)) @all-msgs)))
-(defn clear-old-msgs []
-  (let [min-id (min-clients-last-id)]
-    (dosync
-      (ref-set all-msgs (filter (fn [msg] (>= (:id msg) (- min-id 10))) @all-msgs))
-      (let [total (count @all-msgs)]
-        (if (> total 4096)
-          (ref-set all-msgs (vec (drop (- total 4096) @all-msgs)))
-          (ref-set all-msgs @all-msgs))))))
+
 (def not-nil? (complement nil?))
 ; multi method, dispatch by command and version
 (defn dispatcher [packet channel] [(:command packet) (:version packet)])

        (do
          (send! channel
            (json-str {:status "ok" :data (sort-by :id < (filter (fn [msg] (>= (:id msg) last-id)) @all-msgs))}))
          (swap! clients-last-id assoc channel cur-id)
          (clear-old-msgs))))))
; perfomance dump version 1
(defmethod process-packet ["dump" "1"] [packet channel] (dump))
; default method - simple print packet

  (when (:data packet)
    (let [author (@clients channel) text (strip-html-tags (:data packet))]
      (do
        (add-msg-to-storage {:id (next-id) :time (now) :msg text :author author})
        (send! channel (json-str {:status "ok"}))))))
; fetch version 1
(defmethod process-packet ["fetch" "1"] [packet channel]
  (let [last-id (@clients-last-id channel) cur-id (+ @max-id 1)]
