Monday, January 2, 2012

[Play!] keep the model stateless

Keep the model stateless

Play is designed to operate in a ‘share nothing’ architecture. The idea is to keep the application completely stateless. By doing this you will allow your application to run on as many server nodes as needed at the same time.

What are the common traps you should avoid to keep the model stateless? Do not store any object on the Java heap for multiple requests

When you want to keep data across multiple requests you have several choices:

  1. If data is small and simple enough, store it into the flash or the session scope. However these scopes are limited to about 4 KB each, and allow only String data.
  2. Save the data permanently into persistent storage (like a database). For example if you need to create an object with a “wizard” that spans multiple requests:
    • Initialize and persist the object into the database at the first request.
    • Save the newly-created object’s ID into the flash scope.
    • During successive requests, retrieve the object from the database using the object ID, update it, and save it again.
  3. Save the data temporarily into a transient storage (such as the Cache). For example if you need to create an object with a “wizard” that spans multiple requests:
    • Initialize the object and save it into the Cache at the first request.
    • Save the newly-created object’s key into the flash scope
    • During successive requests, retrieve the object from the cache (with the correct key), update it, and save it into the cache again.
    • At the end of the last request in the chain, save the object permanently (into the database for example)

The Cache is not a reliable storage but if you put an object in the cache you should be able to retrieve it. Depending on your requirements, the Cache can be a very good choice and a good replacement for the Java Servlet session.

http://www.playframework.org/documentation/1.2.4/model

No comments: