Going Stateless with JSF?

JSF 2.2 introduced a new feature called “stateless views”. In a stateless view the state of JSF components will not be saved and restored on every request. Statefulness in JSF has always been a point of criticism. So, since going stateless became very popular for web based applications, using stateless views in JSF applications sounds reasonable. This article is about statelessness and JSF.

What is state?

First of all it is important to distinguish between two types of state: Application state and view state.  To serve its purpose every application needs to maintain some sort of state. From a JSF developers perspective, application state is held in managed beans. These are associated with a certain scope, e.g. request or session scope. The scope defines the lifecycle of managed beans. Every bean requires a certain amount of system resources, namely memory, during its lifetime. However, application state may not be kept in memory at all times, e.g. a container may swap out the state of old user sessions to disk when more memory is required.

JSF comes with a well defined (UI-) component system. Views are built using a set of defined UI components. Components are configured by setting certain attributes, e.g. the value attribute on a text input component that binds the component to the model. These attributes are view-specific state and JSF needs to maintain this state on a per request basis.

In an MVC approach, managed beans carrying state represent the model component. When using JSF there is also state in the view component. JSF is stateful by design. These statefulness is a feature of JSF, though it is sometimes seen as a defect.

Why does JSF need to maintain view state?

HTTP is a stateless protocol but it is sometimes desirable to maintain view state between requests. Views are defined declaratively in a XHTML document. The component tree, a data structure representing the components in a view, is created from this document once a request gets handled. Every component in the tree carries its own state. Theoretically it is possible to recreate a view from its XHTML declaration on every request. But since it is possible to manipulate the component tree at runtime, it is important to keep track of the exact state that was used to create a view. The user may click on the browsers back button and then re-submit a form that was created earlier. In this case it is important to have access to the exact state of this particular view at the time it was created.

Think about a random number generator that fills numbers in input text fields. It is necessary to know which number was filled in each input field when the user hits the browsers back button a couple of times and resubmits the form.

Another example would be a table with a variable number of columns. The exact number of columns may depend on the users input. This information cannot be retrieved from the static XHTML definition. In case the user re-submits the form containing this dynamically created table, it is important to have access to the state that this view was based on.

JSF stores view state by default in the user session. That means a certain amount of server memory is used for this purpose. Setting the context parameter javax.faces.STATE_SAVING_METHOD to “client” allows to store view state on the client side. While this helps to preserve server memory it means also a slight penalty in performance and bandwidth: The state needs to be serialized at the end of the request processing lifecycle and it needs to be transmitted to the client. The state will be posted back to the server with every request and thus is transmitted again and deserialized at the beginning of the following request processing lifecycle. Bandwidth and processing power are the cost of saved memory.

What is a stateless application?

The term “stateless” may be a bit confusing since every non-trivial application has at least some kind of state, e.g. the value of variables during runtime. Running a “stateless” application means that the web-tier of an application does not hold any state for longer than the processing of a single request. This means that the use of classical web sessions (and hence the session scope) is completely abandoned. All state information that is required to process a request needs to be part of the very same request. While the term “stateless” refers to the web-tier, it is valid to store state in some kind of secondary store. The state information may be retrieved from the secondary store upon every request based on a state identifier which is sent with every request. Since this operation needs to be performed for every incoming request, accessing the secondary store needs to be very fast. This is why NOSQL datastores and in-memory-caches are typically prefered over classical relational databases for this purpose.

Why statelessness is cool

Using state in a web application typically means that user/client-specific state has to reside somewhere in the memory on the server side, e.g. session scoped data. This means that there is a somewhat tight coupling between a specific client and the server instance that holds the client-specific state. This is not a problem in a single-server environment, given the server never runs out of memory. Problems arise when the application is deployed on several machines, e.g. in a clustered environment. In this case measures must be taken to have the user specific state available on every node. Session replication and sticky sessions are common concepts to either share state information between nodes or to ensure that requests are routed to a node that holds the state information of the client. The downside is that running servers in a clustered environment is not trivial. Additionally, session replication can lead to an enormous waste of memory since state is also replicated to nodes that will never need it.

In contrast, running a stateless application means that the application is deployed to nodes that do not need to know each other. There is no need to share any state between nodes and it is possible that subsequent requests from a client are served from different nodes, since every request contains all the state that is needed. Elastic cloud architectures enable stateless applications to deal with large amounts of requests, since new nodes can easily be spawned on demand.

What statelessness in JSF means

Running JSF in stateless mode means that some or all views of an application are configured to not use state saving at all. This means that there is no guarantee that resubmitted forms will work correctly if the component tree was manipulated after creation. Furthermore, some components are designed to be stateful, so there is a good chance that some components won’t work as expected. Which ones? There is no  general valid statement on this subject. If a component works as expected in a stateless view depends on the context it was used in, so it is advisable to cover this issue with specific tests. Before defining a view as stateless one needs to reflect very carefully on the possible side effects.

As said before, statelessness means to eliminate all state from the web-tier. It is ok to move state to another location, e.g. a web cache, but the container the application was deployed to must be completely unaware of any sort of user specific state. That means to avoid any scope beyond request scope for all managed beans. This requirement implies almost certainly to redesign an application when switching to stateless views. Of course, it is technically possible to use session scoped beans within a stateless view, but this may obviously put the whole idea of going stateless in question.

It is possible to create a managed bean facility that maintains state on another location, e.g. keeping it in a NOSQL datastore between requests. Whether this approach is successful depends on the data that needs to be serialized, the efficiency of  the serialization mechanism and the access rate of the datastore. While there is no public available implementation for this that I am aware of, it might be worth to create such a facility on your own if needed.

When is statelessness in JSF desirable?

So, while stateless applications may be easier to scale, statelessness in JSF is not for free. Designing a JSF application to run in stateless mode may be desirable, though. If clustering is not an option, designing a stateless JSF application may be the right thing. One could enjoy the benefits offered by the statelessness like an elastic deployment model if it is possible to not rely on any state in the views and shift application state either to the client or to a secondary store on  the server side. Another scenario might be a complex view for that state management is overly expensive. Defining this particular view as stateless may be beneficial, but it is required to ensure that the view will work correctly when state saving is omitted. Scalability and performance issues may be valid scenarios to justify the effort that comes with a stateless approach in JSF.

How to do it?

Defining a view as stateless is very simple: Just add the “transient”-attribute on a . Usage of is not always necessary but its usage is required if a view should be defined as stateless. Setting the transient attribute to true effectively prevents state saving for that particular view. If not already present, JSF won’t create a session in this case as there is no view state that needs to be saved.

Stateless views are defined on a per-view basis. Currently there is no possibility to enable the feature for an entire application. The concept of stateless views is orthogonal to the state saving methods “client” and “server”. All views that are not defined as being stateless (the default) will use the state saving mechanism defined by the context param “javax.faces.STATE_SAVING_METHOD”.

Stateless views are supported by Mojarrastarting with version 2.1.19. The feature was introduced on specification level in JSF 2.2, so all upcoming implementations will support it.

Additional resources

The following resources contain further information on the topic:

[1] http://stackoverflow.com/questions/2910741/what-is-viewstate-in-jsf-and-how-is-it-used
[2] http://balusc.blogspot.de/2013/02/stateless-jsf.html
[3] http://jdevelopment.nl/category/java/jsf-java/#1055
[
4] http://jsfcorner.blogspot.de/2013/05/jsf-22-stateless-views-explained.html

Short URL for this post: http://blog.oio.de/PES8m
This entry was posted in Java EE, Java Runtimes - VM, Appserver & Cloud, Java Web Frameworks and tagged , , . Bookmark the permalink.

2 Responses to Going Stateless with JSF?

  1. Stephan Rauh says:

    According to the JSF 2.2 spec stateless JSF views are not required to work with @ViewScope (see section 7.8.1.1 of the spec). It also states components requiring state must not be used in stateless views. That’s bad news for me because @ViewScope and @FlowScope are my preferred scopes. In many cases restoring state from the database at every request is way to expensive, at least in my business applications.

    Is there a rule of thumb which JSF views do work without state? Are there components requiring state? I remember vaguely editable datatables don’t work with @RequestScope.

  2. Thomas Asel Thomas Asel says:

    Restoring state from an external source hast bo very quick as it needs to be done for every incoming request. Thats why one would prefer a fast non-transactional system over RDBMS, as mentioned in the article. A rule of thumb for views can not be given because every application consists of different views. Maybe in a near future component authors will label their components as “compatible with stateless views”. Apart from that, developers need a profound understanding of view state to work effectively with stateless views. Stateless views should not be used as a default otherwise bad things may happen.

    A login form is a usage example for stateless views. Problems may arise with Ajax based components.

    So the rule of thumb should be: Use stateless views only if you can assure that state saving is not required for the view at all.

Leave a Reply