Storing user session in servlet or session bean ?


EJB design: Storing user session in servlet or session bean ?

  1. Hello,

    I recently read a very interresting thread (HTTP Session Vs. Stateful Session Bean)on this site...the question was : "Where do I store user-session data : in the servlet (using HTTP Session) or in a Session EJB ?"

    The majority of us agreed to rather use a Session EJB since EJB servers tends to better support fail over and load balancing...

    Ok, so far so good. But we still need to store somewhere a reference to that Session EJB. Naturally, one first thinks to store that reference in the HTTP session on the servlet side.

    But what about load balancing and fail over. If the web server fails, how can we retrieve this reference ?

    I don't want to rely on the web server load balancing and fail over mechanisms.

    Does anybody has a good idea how to implement that ?



    Threaded Messages (52)

  2. See I dont agree. The problem is as you state that to use a Stateful session bean you need to still use the HtppSession object. So why not maintain the state in the session? This in most systems will scale better then a stateful bean.

    Some application servers do support failover of the HttpSession, like Sybase EAServer.

    Dave Wolf
    Internet Applications Division
  3. the best place to store ur user/session level data is he HttpSession. cause if u plan to uses stateful session bean su r putting to much load on the application. the overhead invloved in holding state of thousands of users and activation/passivation mechanism is i think too much for the app server to handle.

    so the better place is definitely HttpSession. u can always add hardware resources(more memory) to ur web/http layer to take care loads of HttpSessions.

  4. i would have to argue this point. the session bean is the best place to put the session data not least because it is easily located on any machine, it has a known activation and passivation stratedgy, and the load between storing a session in Http and a session in EJB must be identical.

    i fail to see why you suggest the load of a number of HttpSessions is less than the load of multiple ejb sessions?

    i would argue tha
  5. Session bean is the best place to store data if you are going to have multiple sources accessing it. that's right.

    But, the only concern is the remote method invocation.

    suppose you have a webserver (a separate physical server), and an appserver( a separate physical server).

    Here a request comes from a client, if the session has the data, request is served from the session, and it's always going to be fast.

    Supposing your sessionbean has the session data, there is a cost associated with a network method invocation.

    The call needs to be marshalled, unmarshalled, marshalled , unmarshalled, which definitely slows down the execution. This is the only problem that i have with using a stateful session bean.

    If you don't consider the rmi cost, storing session data in the stateful bean is the best thing to do.
  6. But storing session data with a stateful session bean is much of an object oriented approach. it's more organized, and data can be stored and retrieved in an organized fashion. whereas, storing data with HttpSession is like dumping all your data into a HttpSession, and it'd become more difficult for your application to be portable, and keeping track of what data is stored in session.
  7. well u can always create nice OO data structures to organize ur data and dump the references of those data structures in the HttpSession.

  8. Absolutely agreed. For instance if you are using a Proxy pattern store your proxy controllers in the session.

    Dave Wolf
    Internet Applications Division
  9. i agree that you can store you objects in httpSession.
    Suppose i'm modifying the object stored in HttpSession after a call to Object obj = getAttribute("myobject").

    now if make a change to obj's state.
    then i need to call setAttribute("myobject", obj)

    like this i need to make *n* number of calls whenever i modify the object stored in the HttpSession. doesn't this make your code look ugly.

    Moreover these objects can be accessed only by java based clients, but with session beans, any java / non-java client who knows how to get a serivce from a bean can make use of it.

  10. You could make n=1 by having a singe state object.

    The good point you make is in regards to non Java objects getting the state. However do you invision a web and non web client needint to share the same state at the same time?

    Dave Wolf
    Internet Applications Division
  11. Thanks for the n=1 clarification. I've seen non-java clients needing access to session data stored thru servlet. like PHP clients accessing the session data stored thru a servlet. In this case i can't read the java objects stored thru PHP. The only way is if it's stored as some string value. But storing in this manner makes life difficult to track eachs tate.
  12. Dave,

    Does Sybase has any documents/white papers to describe in detail how EAServer does manage the session objects on things like failover, advantages, etc. Any others "deep" technical articles ? Comparison between AppServers, etc...

    Can you provide us with URL link to access such documents ?


    -Victor J. DuLuc
  13. Victor,

    I have a white paper on the Sybase failover but it is in bad need of updating. Ill work on this next week sometime, and will try to repost it to our site. Ill leave a link here.

    In the meantime, I can answer any specific questions.

    Dave Wolf
    Internet Applications Division
  14. You can have your reference go out of scope, and you can still get back to the same session EJB with the handle that you have stored in the client side using some cookie mechanism.

     Again the handle will be valid only if the session bean hasn't timed out, and it's alive.
  15. And how do you intend to store that handle on the client side in a web app? I mean if you store it in the cookie why not just store the remtoe interface in the HttpSession?

    Dave Wolf
    Internet Applications Division
  16. The original question was, what if the webserver is restarted after a failure. In this case i'd not have a reference to my session bean in the webserver if the webserver itself is restarted.

    Imagine this scenario, a session handle is stored in the client side. he has done some work in the session and stored some state with the session bean. At this time the webserver goes down, and after some few minutes it's brought back, but if the request comes from the same client, i will refer the handle stored in the client to get back to the same session bean
  17. 1) A product like Sybase EAServer can recover an HttpSession after a web server failure so its not an issue

    2) How do you intend to "store" the handle on the client side of a web application?

    Dave Wolf
    Internet Applications Division
  18. In order to use the handle to get back to the same session bean i would use cookies to store the handle file name.

    In that first i would use the writeObject to write the handle to a file, then i would send the filename of the handle with cookies. when i get a request from the same client, i'll read the handlefilename, and get the handle from the same file thru readObject, then i can refer to the same session bean.
  19. I was browsing a few old messages and came across yours. Your suggestion is interesting. I have a couple of question.
    1. What do you mean by handle? Is it the Remote interface or is it the actual object itself?
    2. How is the performance doing write and read for every request?
    3. Will it be any faster if it is written into a DB with a binary column?

  20. For those of you who suggest storing the serialized handle in a file (ex: sessionid.ser), what do you suggest for a housekeeping mechanism that deletes the file when the session is over. Is there an event to listen for...similar to HttpSessionBindingEvent?

  21. What happens if the application is in a clustering environment.I mean when the remote reference is serialized and stored in the file and there is a way to access the file thru cookies,but when there is overload on one system the application server directs the request to a physical machine which has less load.does the remote reference of the session bean is still valid in this case.Please clarify if i am wrong and suggest me the best of storing the remote reference

  22. Is there a free eval download for EA server. If so, could you give me that link. I'd like to see how it manages the recreation of HttpSession, also i'd like to know which other webservers do handle the HttpSession failures.
  23. You can download a free version at

    Dave Wolf
    Internet Applications Division
  24. WebSphere supports this along with session affinity.
  25. please correct me if i'm wrong, but, when using HttpSession, doesn't the server state get stored by the servlet engine in the web container which resides on the application server(WebSphere in my case), so if the web server would go down, there would be no effect on the HttpSession object. If i'm wrong, and the servlet engine saves session state on the web server instead, please let me know.
  26. I just had the same problem: Where to store the Session EJB remote reference to support fail-over when one server in a cluster crashes.

    I'm wondering whether storing the remote reference using JNDI is possible, binding the session EJB name to the remote reference...? I guess this depends on whether application servers support fail-over of the JNDI registry. Any excperiences or comments?
  27. A good container should do this for you.

    Dave Wolf
    Internet Applications Division
  28. Dave,

    I don't see what you mean: A good container should to WHAT for me?
    * Support fail-over for the remote reference
    * Replicate the JNDI registry

    Please clarify... :)

  29. A good container should do both. It should

    1) Support transparent failover of both stateful and stateless session beans
    2) Support transparent failover of the HttpSession objects
    3) Support dynamic rebinding of the JNDI naming information

    Sybase EAServer does all 3 :)

    Dave Wolf
    Internet Applications Division
  30. OK. The conclusion is that the JNDI registry is a reasonable place to store the remote reference to support fail-over (provided that the appserver supports JNDI registiry replication):
    o The remote reference is available to clients in the web-layer, ejb-layer (and any other clients)
    o If a server in a cluster crashes, fail-over is provided by the remote reference in the JNDI registry (this requires that the appserver also supports fail-over for the bean :)

  31. Support failover for stateful bean also mean that the state have to duplicated in the failover server since the bean have stateful information. There is not reason to fail over to another server that doesn't contain the right state information. Does this mean Sybase does replication for stateful bean across different server? I'm am using Weblogic Cluster 5.1 w/sp8 currently doesn't(6 does). I end up using database to store the session. What I get is more database overhead but i eliminated the single point of failover of stateful bean in this case. However in the long term I wish to implement session without using database.

  32. Yes Sybase EAServer supports the failover of Stateful session beans including the in-memory state of the Stateful bean. We provide a persistance layer using the database in this release as well, and will provide a pure in-memory cache in the next release.

    Dave Wolf
    Internet Applications Division
  33. Guys,
        I have asituation where I need to fill the form which has 45 feilds. Instead of filling all the fields I am breaking up them in 8 different forms.
    All these form ( and every fields ) should be filled before storing it in Database. No other page will have save button other than the last page and all the page should be filled in linear fashion.

    how do I store the contents of all the previous pages till I reach last page.??

    Should I use HTTPSErvlet session or should I use session bean?


    Thanks in advance.


  34. I would store the data in the HTTPServlet session until they have been entered, and then transfer them to the DB.
    2 Reasons

    1> If you store them in the Session bean you have two timeouts to worry about, that of the Session bean, and that of the Http session that is holding the reference to the Session bean.

    2> If your web server and ejb server are on seperate machines then there will be more remote access if you are transfering the data in small lumps rather than one big one at the end.

    Hope this helps

  35. Hi Peter,
       Thanks for ur message.

    But I just wondering about relaibility and scalability here. Say tommarow ( and definielty) the number of fields are increased to 95 ( 105 max) and so more number of pages increases. If I store all these info(fields) in HTTPSession and assume around 1,000 people are filling this 8 - 10 pages form, then what happens to Webserver. Is it OK in these kind of cases.

  36. this is very interesting, as a decision whether to use HttpSession or a bean to collect session data, is one i currently have to make. What i'm really trying to understand is where the HttpSession object is stored in the case that an application server that contains both the servlet container and the ejb container is on a different machine from the web server. In my case, I have a iPlanet web server on one machine, and a Websphere app server(which holds both the servlet container, and the ejb container) on another machine. If the HttpSession is stored on the app server, than using it instead of a session bean wouldn't really provide a benefit in terms of network travel between the web server and the app server; on the other hand, if the HttpSession is stored on the web server, then the overhead of calls to the app. server is definately reduced... to decide though, i need to know, in a scenario such as described above, where does HttpSession reside?

    Thanks in advance,

  37. Hi Sanjeev,

    Let's find out first what the server memory requirement is in the case of 1000 people filling in all 105 fields. Suppose average size of the fields is 20, it makes the total size for each person 20100 e.g. 20.1k. So 1000 people need 1000 X 20.1K = 20M. For a Web server, this kind of extra space should be easy to come by.
    You may argue that your web site needs to support 10000 iteractive people in a certain period of time. As the result of that, you need 200M more memory. It's still an fairly easy job. Even you have a SUN E10K machine, it will cost you about 2-3 grand to add it.
    If you are still not satisfied, you can have another option, store the fields in a file or a database, save the reference in the HttpSession. Now you would say, it brings performance penalty. Yes, but nothing comes for free.
    My point is that, in your case, memory has little to do with it. If you had 10000 silmutaneous clients to one web server, your web server had crashed long before it ran out of memory!

    Best regards,

  38. I believe HttpSession is the right location to store temporary data when the form is split into several sub-forms. The logical unit is the data collected from all forms together, and it makes sense to handle this unit in one transaction.

    Consider the case when you want to create a Java application with the same functionality. In this case you could use a wizard; each wizard window would be similar to the web forms. The data would be stored locally to avoid the network traffic. The last wizard window would have a Save button, comitting the entire data structure directly to the EJB.
  39. i had a similar case where the user had to go through a series of HTML forms and only in the last submission i wanted to dump everything into the database.

    Well i decided not to use Session tracking at all because i would always have to check if the session had expired and if it expired forward to and error page etc.
    Why not pass the user's selections from one page to the next page via input hidden fields ? ?

    So in your last page you will end up with 45 form fields, most of them hidden holding the values from the previous 7 pages.
    It's pretty clean and there are not timeout complexities.

  40. Two reasons not to use hidden fields:
    o Network traffic is increased
    o Security and inconsistency concerns. The user can possibly change the values for each post (even though the fields are hidden). You may have to re-validate all fields after the final post, and then direct validation errors to the corresponding page etc.
  41. does anyone know if/how stateful session bean failover is implemented in WebSphere3.5 - 3.52?

    I would really appreciate any info.
  42. Hello,

    It is always advantage to store the session in your stateful session bean,because most of App servers having a common session manager(esspecially in iPlanet),so if your application get failover in one instance of ur app server,the session won't fail,the session manager will serve the session values provided the application is also running in other instance of ur app server(Cluster).

    Is my reply is a valid suggestion!!!!!

    Please clarify

    J2EE Developer in iPlanet
  43. How does one store the ref to a stateful
    session bean? I read somewhere that you can
    serialize an obj handle, but that handle can't be moved
    from one machine to another. Is this true or vendor dependent behavior? HTTPSession failover
    on our servlet engine uses serialization, moreover,
    if the ref can't move to another machine, it won't
    work anyway.

    Someone mentioned putting the stateful session bean
    in JNDI, but how does jndi know when the
    session is expired and remove the object?
    One possiblity I will try is
    to use a stateless session bean which reads/writes
    a block of session data to the dbms.
    This way we don't have to use
    "sticky ip" on our load balancer and any servlet
    engine will handle the request. However, it
    does hit the dbms performance-wise. Has anyone
    tried this configuration?
  44. If someone can explain the best practices for storing session data...

    Is it better to use HTTP Session or JNDI ? Even if you use stateful bean, we still need to store the EJB reference in HTTPSession.

    How do you handle invalid reference due to timeout ?
    How do you create an EJBHandle, wouldn't that be just the object reference ?
    How do you cleanup when user changes the context, e.g. selects another account ?

  45. You must take into consideration the concept of Load Balancing.

    In a high volume web site you will have multiple web servers running the same servlet. A load balancing mechanism is used to determine which server to invoke when a request comes in. In normal implementations session data in the HttpSession will reside in the same memory space as the JVM running the servlets. This is not an acceptable scenario while carrying out load balancing. Hence, in such cases session data can either be stored in a common data repository or in a session bean whose handle can be persisted to a common data repository.
  46. 1) There is no reason a Handle object is tied to a single machine
    2) There are servlet containers like Sybase EAServer which would allow for load balancing across multiple servers which all share the HttpSessions so this is not an issue either
    3) You can store the ref to the stateful bean in the HttpSession.

    Dave Wolf
    Internet Applications Division
  47. I agree with Dave. I would definitely recommend using shared Vendor BLOB Sessions.

    The only problem is that some servlet containers (e.g. Websphere's shared HttpSession) have performance issues when the HttpSession data grows over 32K. This is something to consider.

  48. Thanks dave. Your comments are helpful as always.

    Here is a quote from a book I was referring to:
    "Mastering EJB" from Wiley on page 143:

    "Unfortunately, EJB object handles have
    strong domain limitation: Handles cannot
    be saved in one environment and then re-stored
    in a different environment. This means handles
    are not portable across EJB Containers. It also
    means you cannot save a handle on one machine
    and the re-use it on a different machine".

    Is this book wrong or is it just that
    Sybase's product doesn't have this restriction??
    Can a handle be moved from one servlet container
    to another on a different machine?? In
    CORBA I could see how a central singleton object
    could easily pass session object references to
    any available servlet container on demand. Also,
    CORBA IOR are by definition movable
    across machines. This book tells me that EJB
    handles are serializable but not movable. If an
    EJB server were based on CORBA (e.g. an IOR is the handle)
    then it would work. But is this the case for
    all vendors?

    Besides understanding how a session object moves
    from one servlet container machine to another,
    I don't see any problem storing handles or
    references in HttpSession data except that
    using HttpSession forces a "sticky ip"
    configuration at the load balancer.
    Ideally, wouldn't it
    be better if an HTTP request can go
    to any web-server/servlet-container combo that
    is available and most responsive??

    We found that with the Microsoft web technologies
    that a non-sticky-ip configuration was many
    times more scalable and fault-tolerant in
    production than a sticky-ip configuration which
    glues all requests (by session) to the
    same server. In theory, it shouldn't have made
    much difference, but in practice it made a huge
    difference under heavy loads.

    Is this a good thing for Java too? If so, How would one
    best implement a non-sticky-ip session
    management subsystem?? Does anyone have any
    experience with a sticky-ip v.s. non-sticky-ip
    production configurations
    in Servlets/EJB that matches our Microsoft

  49. Hi Brian,

    I believe that quote is incorrect as it makes a pretty sweeping statement. Sybase EAServer would not and does not have such a restriction. Our Handles can indeed be moved from one machine to another. Our application server is very CORBA based and uses a CORBA IOR internally in the Handle to identify a possible endpoint (or array of endpoints) in an IOR Profile. The Handles can therefore be moved around. I did a prototype for someone where we moved the Handles around as elements in an XML file. You just have to be sure in the case of a stateful bean that no two clients try to access it concurrently as this would violate the spec in EJB 1.1

    As for sticky sessions, we also do not have this restriction. We allow you to mark an web application as distributeable so HttpSessions can be shared across containers this avoiding the need for sticky sessions and properly handling failover scenarios.

    Dave Wolf
    Internet Applications Division

  50. I can assure you, from bitter experience, that when using WebLogic 5.1.0, Handle objects are indeed server-specific.

    You cannot use a Handle from a server different from the one on which it was originally created. Stateful Session Bean failover is not possible.

    And while I'm whining...

    Also, on this server, you cannot rebind() or unbind() in one Context what you have bound, using bind(), in a different Context. This leads to a single point of failure.

    Addtionally, JMS is server-specific, not cluster-wide. You cannot subscribe to a Topic created using one Context which was created in another. This also leads to a single point
    of failure. We plan to use a third-party implementation of JMS.

    And no multi-phase commit.

    I really hope BEA has fixed these things in 6.0+.
  51. Well wait, yes a Handle would contain a profile to a specific server of course. Except in our (Sybase EAServer) case these Handles would contain multiple profiles for multiple servers contained within a cluster. My point was that this Handle could be passed from calling client to calling client.

    As for messaging system implementations, we do allow for "REPLICATED" messages and topics which can be shared across a cluster. I worked on a stock trading application for a major trading floor where the bids and asks could be matched across servers in the cluster.

    Dave Wolf
    Internet Applications Division
  52. The application server supports HttpSession replication and so even if the server fails the replicated session on the other server takes-over to maintain the session.
        One thing to note is that HttpSession replication helps for fail-over but what if the server running the session-bean fails ? and the session is lost !
         BEA's weblogic server in its future release is going to support replication of Session Bean's also.

  53. In the scenario of recovering from web server failures, one way could be to propagate the identifying details of your session EJB to the client. So client sends these identifying details along with each call to server. This detail should be sufficient to identify the Session EJB that contains its session.

    Also I would like to differ from your opinion that there is one universal best place to store session data. Replication of session related data should consider factors like proximity to processing resources, data visibility, network reliability and latency, distributed deployment scenario, etc.

    Himanshu Bhartee