title: How to handle stateful OSGi services to maintain session state across bundle updates?
body: <p>We have a scenario with a webapp implemented as a number of <code>OSGi</code> bundles. We want to do bundle updates to transparently deploy bugfixes etc to the running system. Assuming an update cycle with refresh and bundle restarts, this will cause problems when objects, whose classes are being reloaded, have been stored on the <code>HttpSession</code> leading to <code>ClassCastException</code>s.</p>
  
  <p>We are looking at several different ways to make bundle updates possible without losing state in logged-in sessions. To simplify the session state access dependency graph we are thinking about setting the following restrictions:</p>
  
  <ul>
  <li>a bundle can only access its own session state, i e no direct access to state set by another bundle (forces to instead call bundle API to indirectly access its state)</li>
  <li>the Java classes of objects added to session state should come from the bundle itself (to avoid having our session state affected by updates of other bundles than ourselves)
  These restrictions are really only needed by some of the alternatives below.</li>
  </ul>
  
  <p>So, these are the alternatives we have come up with in some kind of least to greatest implication order:</p>
  
  <ol>
  <li>Store all state as <code>java.*</code> types (<code>String</code>, <code>List</code>, etc)<br>
  –> state classes are never subject to reloading.</li>
  <li>Lock sessions to the service versions its state was created with (by f ex using <a href="https://stackoverflow.com/questions/16341488/can-i-inject-proxies-in-front-of-blueprint-services-published-by-other-bundles">proxying solutions</a> that forward to the version used earlier by that session)<br>
  -> new sessions will pick up updated bundle versions while existing sessions will stay on the old versions.</li>
  <li>Serialize session state when updating a bundle and deserialize it back into the new bundle version (like appserver session serialization but on a more granular level)<br>
  -> all sessions will pick up the updated bundles but requires that serialized state is compatible.</li>
  <li>Avoid updating stateful services as long as there are active sessions, making use of traditional load balancer techniques to update one appserver at a time<br>
  -> longer deploy turnaround and may need more resources.</li>
  <li>Avoid stateful <code>OSGi</code> services altogether and keep state elsewhere<br>
  -> not handling the problem in <code>OSGi</code>...</li>
  </ol>
  
  <p>Did I miss any interesting alternatives?<br>
  What solutions do you recommend?</p>
  
  <p>[although this post explicitly talks about session state the same discussion could apply to other scopes such as conversation state, application state, etc]</p>