Question

I have a need to maintain global state on the server across different browser / user sessions.

My assumption here is that all atoms etc created when a request comes in is specific to that request. Once the response is returned all that state is destroyed and memory freed. Please correct me if I am wrong.

State across requests for a specific session can be maintained in memory by using the session middleware.

However how do I maintain the state across multiple user sessions and requests. If possible I would like to avoid the usage of memcached / redis etc for storing it externally. Is it possible to achieve it in memory itself?

Was it helpful?

Solution

Do you mean that you want global state that is shared across all sessions?

If so than that is easy, just declare an atom or ref in any namespace you like and it will be shared across all sessions, e.g.:

(def my-state (atom {:foo 1 :bar 2}))

This works because the Clojure environment persists for as long as the application server keeps running, and any future requests will be able to observe / modify the global state.

Having said all that - it is worth remembering that global state is often a design smell. You should think about whether you really need this, or if you should consider some other alternative (e.g. pushing the shared state out into a database).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top