Best practice for stateful plugs & initializing

Hello,

Even though many plugs are stateless, some need to keep state for latter use, such as plugs dealing with sessions or rate limiting.

Then it is in some cases needed to initialize a store (ETS, mnesia, setting up a pool for Memcached, Riak, …). I see three options to do that:

  • Checking if the store exists when calling the call() callback, and if it doesn’t, create it (seems costly in terms of performances)
  • Make the plug an application, and deal with store initialization in the Application.start() callback
  • Do nothing and expect the store to be already set up somewhere else. It seems that’s the approach with Plug.Session.ETS (but is that the rule ? This store is for dev purpose)

Shall plugs remain stateless? What’s the best practices? Any pointer is welcome :slight_smile:

Have a great day!

Where does the plug come from?

Is it part of your application? Then set up its state in your applications init phase.

Is it part of a library you write? Make that library a proper application, set up supervision and let some process take car of the state either GenServerish or in an ETS or whatever you prefer.

Is it part of a library not under your control? Well, file a bug report and tell them their design is missing something.

1 Like