Monday, August 19, 2013

Server Side Sessions vs Client Cookie Sessions

If we were to strictly follow the REST model, we should not store client state on the server, including sessions.  Since I am starting a new project, I thought I would take a moment to evaluate the pros and cons of server side sessions vs client cookie sessions.

1) Scalability
One the major arguments against server side sessions is that it does not scale.  Using the traditional Java model, session are stored in memory.  Thus, with lots of users and large sessions, one can run out of  memory.    On the other hand, in the PHP world, server side sessions are typically stored in a  file. While this will not run into a memory problem, this will require frequent disk read and writes at each request.    Both of these server side session models (Java and PHP) are thought to not scale well.  Lets take a closer look...

How much memory does a Java session take?  

This is a crucial question.  If Java sessions take lots of memory, then we know this will not scale.  However, as it turns out a Java session takes very little memory, in fact on my machine, a single session only takes 1.67 KB (of course filled with more data, that number will be higher).  That means that we can store sessions for 10K users in a mere 16.3 MB.  If we keep the information in our sessions small, memory is really not too much of an issue.  

But what if we have lots of sessions or larger sessions? 

To solve this problem, Tomcat has a configuration that allows a hybrid appraoch between memory sessions and disk based sessions.  Using this model, sessions are stored in memory, but then serialized to disk after a configurable timeout.  If needed again, the sessions are brought back into memory. This option provides rather good scalability.  The sessions  are released from memory after a period of inactivity, and do not need to be read from disk each time. Using this model, I do not see most web apps suffering from a scalability issue stemming from high memory or frequent disk access.  

2) Security
Using server side sessions, all session data is stored on the server side.  While it is possible to secure sessions in the cookie, it is harder to get right.  Having the session information on server makes it harder for users to manually change data.

3) Performance
Server side sessions are simply faster: not only is there less network traffic, there is also less server side computation.   However, if one were to place session in the cookie,  extra server side computation is required to de-serialize the session, validate the session, and then re-serialize back into the cookie.  Granted, this computation could be considered negligible, it is worth pointing out that expensive cookie encryption could create overhead.

4) Flexibility
Using client cookie sessions, you have strict limitations: only 4K of string data.  In most situations, this will work fine.  In fact, if one is putting more than 4K in a session, they are likely abusing their sessions (which is all to common in many Java frameworks).  However, occasionally you do need to add more than 4K of data, and at times it is convenient to store non string data.  Server side sessions provide the flexibility to do so.

5) Load Balancing
Perhaps the greatest feature of client cookie sessions is that load balancing is a breeze.  Since no state is stored on the server, it does not matter which server handles the request.  

On the other hand, using server side sessions, once a session is created the same server must handle each subsequent request.  However, in most situations, this is really a non issue since every load balancer supports a mechanism to forward requests in a sticky manner, either via an ip table or cookie.  Things do get more tricky when you need to take a server off line, as you might need to "drain" a server of its sessions.  Yes, this is annoying, but should only need to occur occasionally.  (and this annoyance will be only be one small component  within a larger and more complex process of updating apps on the fly, a complication which exists regardless of the type of session).

Conclusion
In this post we briefly looked at some of the pros and cons of storing session data on the server or in client cookies.  While cookies do provide some excellent benefits, particularly in load balancing, I think that server session will still work fine in most types of apps.  To each their own!

For my current project, I am going to continue using the tomcat's hybrid memory-disk option.  It provides a scalable, flexible, and secure solution for sever side sessions.

Tuesday, July 30, 2013

Digital Ocean announces new data center

Digital Ocean just accouned a new data center in NYC.  You can read about it here.

They say that "this new datacenter brings DigitalOcean even closer to rolling out private networking for our customers, which will premiere in NY2!"  

Does this mean that Digital Ocean will soon have free transfer between private IPs?  If so this, is great and will add a feature that is currently missing from Digital Ocean's stack.

Digital Ocean vs Linode

Over the past few years I have ran a number of web apps out of Linode's VPS.  I truly could not be more happy with Linode: great product, great service, fair pricing, excellent features, etc.

However, I am not building my new project on Linode, but on a newer VPS: Digital Ocean.   Here are some thoughts on the two VPSs.

Pro Digital Ocean

1) Price:  You can just can't beat Digital Ocean's price .  You can spin up their cheapest droplet for only $5, with 512 Ram, 20GB SSD, 1TB transfer.  Nice!   On the other hand, the cheapest Linode server is $20.  Clearly the $20 Llnode is better than the $5 Digital Ocean.  But with Digital Ocean you can get up and running for less money.  You can check out their price comparison chart.

2) Billing per hour:  Unlike Linode, at Digital Ocean you are only billed per hour that the droplet is running.  This model makes it easier (and less risk) to try out  different setups.   However, at Linode, you are charged for a full month.  If you then cancel mid month, you are given a prorated credit.  So, the situation at Linode is not too bad either, but does not lead as much to developer experimentation.

3) Transfer Speed:  A number of people in the past have complained about Digital Ocean's transfer speed.   However, in my simple tests, Digital Ocean actually transferred slightly faster than Linode.  I tested this each day for over 2 weeks, and Digital Ocean was always better.  I know there could be other mitigating factors, but this is a nod towards Digital Ocean!


Pro Linode

1) Great Reputation - Linode has been around for years and they will stick around.  They will not go belly up any time soon.  On the other hand, Digital Ocean is a newcomer.  Can they compete in the long run?  Will I need to find another VPS after Digital Ocean goes out of business?

2)  Web Interface - Linode's web interface is much better than Digital Ocean's.  Creating nodes and configuring DNS is much more feature rich on Linode.

3) Free Transfer on Private IPs - At Linode, when you transfer data between nodes, there is no transfer costs.   However, at Digital Ocean, you pay the same cost when you transfer between nodes.  So, with Digital Ocean, if you put a database on another server, you will have to pay for each data transfer.  The same goes with a load balancer.  Digital Ocean is great if your app is on a single server, but not so great if your app is spread among sever intercommunicating servers.  Big win for Linode! 

4) Node Balancer - Linode offers setup load balancer for $20 a month.  This is a great service and there is no Digital Ocean equivalent.  Again, Linode shines when you need to scale your app beyond one server.

5) Pooled Bandwith - At Linode, your transfer limits are placed in a pool and shared among all nodes.  Thus, if your image server goes over its limit, it will simply access the transfer limit of the entire pool.  However, at Digital Ocean, there is currently no pooled bandwidth, and it is at best confusing if they will ever offer pooled bandwidth.  Again, Linode offers better services for architectures that might use more than one server.

Summary

Both Digital Ocean and Linode are great VPSs.  If you do not anticpate your server neededing more than one server, Digital Ocean will work great.  However, if you anticpate an server that needs more than one coupled server, than Linode will likely be the better option.

As for me, I am going with Digital Ocean for my new project.  We will see how it pans out!

Saturday, March 16, 2013

Quercus PHP: interpreted vs compiled

The good folks at Caucho were nice enough to send me a trial key for Quercus PHP Professional, so I gave it a spin this morning.

Quercus PHP is an implementation of PHP that runs on the JVM.  The open source version runs in interpreted mode, while the Pro version compiles the PHP to Java byte code.  The Pro version is not free, but costs $99 a year for a license.

Three Ways to Run Quercus PHP:  As I see it, there are 3 ways to run Querucs, and your choice would depend on your use case and needs.

A) Compiled Mode -  Compiled mode is only available in Quercus Pro ($99), but this will give you the fastest speed.  The PHP script is compiled to Java classes, which yields not only fast PHP execution, but also leads to high performance integration with existing Java code.  The only downside of this mode is that static strings are stored in the PermGen space.  This is not necessarily a bad thing and this works the same way as JSPs, but it just something to be aware of when you are allocating space and re-deploying apps.

B) Interpreted Mode - In this mode, the PHP pages are interpreted at each request.  This is still very fast, and very similar in speed to mod_php without APC.  In this mode, the PHP file is cached, so there is no need to re-read the PHP from disk IO.  You can adjust the size of the PHP page cache.

C) Interpreted with No Page Cache - This mode is the same as the above, except it removes the page cache of the PHP file.  This mode is very similar to mod_php in that each PHP file is re-read from disk at each request.  Most people would want a PHP page cache, but there are times when you may not want it because it will consume extra memory to keep those pages in the cache.  On a memory restricted sites, with lots of different PHP pages in which each page (in of itself) is accessed rarely, you may want to disable the page cache.

Quick Performance Test

I ran a quick benchmark to see how the different Querucs modes perform.  I grabbed a PHP benchmark from this site.  This is a rather long running script, so it does not measure requests per second, but rather the time it takes to execute and entire script.  Tomcat 7 was used as the Java server.  I ran the scripts a number of times and averaged the results:

quercus compiled - 3247 ms
quercus interpreted  - 7540 ms
quercus interpreted no page-cache -7798 ms
apache mod_php - 9088 ms
apache apc  - 9159ms

As we can see Quercus in compiled mode is almost 3 times faster than Apache mod_php, and Quercus interpreted is a bit faster as well.

Since this is a long running script, the page cache did not really help the interpreted mode of Quercus.  Similarly APC did not help mod_php, because the compile time is a small fraction of the running time.

We should not conclude too much from this quick test, but it seems to be in line with some of the results found on the official Quercus page.

Saturday, March 9, 2013

MVC using Servlet with a Quercus PHP view

In this short post I will briefly explain how to create an MVC system that uses a Java servlet as the control and model, and a PHP page as the view.  We will use Quercus PHP, the great implementation of PHP that runs inside the JVM.  This tutorial will assume that you know how to setup and use both Java sevlets and Quercus (simply google them if you do not know, or send me a note).

This post will build off of the classic Servlet/JSP MVC examples, as seen in tutorials like this.  But instead of using a JSP to view the model, we will use PHP.  So, really this just boils down to how you can pass a Java object to PHP.

Lets start with a simple servlet that contains this code in the process request:
            request.setAttribute("message", "hello from java to php");
            request.setAttribute("number", 100);
            RequestDispatcher dispatcher;
            dispatcher=request.getRequestDispatcher("/view.php");
            dispatcher.forward(request, response);
Ok, this code should be familiar, we simply place two objects inside the request and the forward the request dispatcher to a PHP page called 'vew.php' (instead of a jsp page).  Now lets look at the PHP code.

The first thing we want to do in view.php is grab the Java request object, so we can grab the objects we placed in the request.  Quercus provides the PHP function quercus_servlet_request() to do just this.  Then I add a function to make it easier to get the object attributes out of the request.  It is a good idea to put this code in a global include:
        <?php
             $request = quercus_servlet_request();
             function getAttribute($key) {
                  global $request;
                  return $request->getAttribute($key);
             }

         ?>

Now, within PHP we can call the above function to get the Java objects, and use PHP as the view component of the MVC. Piece of cake!
       <?php
            $message = getAttribute("message");
            echo "message = ".$message."<br>";
           $number = getAttribute("number");
           echo "number = ".$number;
       ?>

Friday, March 8, 2013

Tips for Unity3D mobile development

There have been several articles written how to optimize Unity3d for mobile development.  Most of those articles focus on draw calls, polygon reduction, texture atlases, etc.  Those are all great topics, but I wanted to pass on a few more tips.  Enjoy!


1) Favor cookie-cut geometry over cookie-cut textures.

As it is well known, mobile devices are not optimized for handling textures with transparencies.  Instead of having a cookie-cut alpha channel on a textures, it is often possible to achieve similar results by simply increasing the geometry. 

For example, if you needed to create a "star" you could use a 2d plane textured map with a an alpha-blended or cut-out image of a star.  Alternatively, you could model the outline shape simple star (a few more polygons will do the trick) and then apply a non-transparent texture.  In this second way, the geometry provides the cookie-cut.  While this technique is not appropriate for all cases, it does often work well and leads to higher performance, because mobile devices are optimized for polygons not transparent textures.


2) Use a texture atlas for in game text.

Never use text GUI elements during gamlay, and try to avoid Text3D/Mesh (as they use transparencies).  Instead, when possible, using an opaque texture atlas.  For example, in our recent game we wanted to display the number of coins the user has collected.  So we created this texture atlas.

By dynamcailly moving the UV coridatnes on a set of rectangle polygons, we were able to achieve much faster frame rates than if we were using text3d or text meshes.  It is a bit of work to set this up, but it is worth it (assuming you do not need transparent text).   To change the UV coordinates:

        // Grab the mesh first
        Mesh mesh =gameObject.GetComponent<MeshFilter> ().mesh. 

       //Create an array of uvs... set them to be whatever you want
       Vector2[] uvs = new Vector2[4];
      
      // Apply the UVs to your mesh
      mesh.uv = uvs;


3) Avoid objects GameObjects with attached Behavior scripts

The easiest way to attached code to an GameObject is to attach a MonoBehavoir script.  However, this comes with a performance penalty.  Instead, I would recommend limiting the number game objects that have attached scripts.   In fact, in many cases you can almost do away with MonoBehavoir scripts, aside from a a few "main" scripts that load the objects and gets things initialized.

For example, consider creating a custom star field that has hundreds of stars.  To create this, you could have hundreds of GameObjects with attached behavior scripts.  But this would come with quite a performance penalty. 

Instead, you could have a single behavior script that contains an array of GameObject Transforms.  This single script simply moves the transforms of each star at each frame.  This approach saves memory and saves cpu cycles.  Coupled with a nice object orientated design, you can take this same approach and extend it to most objects in your scene.


4) Look for the "new" keyword and avoid it when possible

The "new" keyword allocates a new object on the heap (or stack if a struct).  This operation is a bit expensive, and if used frequently will force frequent garbage collection.  Clearly we need to use "new" to get new objects, but avoid creating new objects within functions that are called at each frame.  If it is being called each frame, there is no reason to construct a new object each time.  Create the object once, in the start() or constructor, and then re-use it.   Some might consider this over optimization, but I consider it smart game programming.  It is a simple paradigm to follow and will drastically improve game performance.


Monday, February 25, 2013

The Advnatages of Quercus PHP

While most everyone that uses PHP uses the Zend Engine, there are a few other PHP implementations.  One such interpreter is Quercus, a PHP interpreter written in Java and runs on the JVM within a servlet container.  Here are a few reasons to give Quercus a look.


1) Performance

So, is actually Quercus faster than Zend?  In some operations it is a bit faster, and in some operations it is a bit slower.  In general, I would say that Quercus PHP has about the same performace as Zend PHP for most PHP requests.  Quercus comes in 2 flavors, interpreted mode and compiled mode.  The interpreted mode is (in my epxierence) roughly comparable to not using a code cache with Zend, while the compiled mode is comparable to using a code cache with Zend.  See the following doc for an overview of Quercus performace.

While this does not seem like much of a "win" for Quercus, it is important to point out that Quercus is not slower for a standard PHP request.   If Quercus were slower, the following points would be rather moot.  However, Querucs is fast, and combinded with the following advantages, it is a platform to be considered for PHP devleopment.


2) PHP in the front, Java in the back

Different computer languages were written for different tasks.  PHP was written as a web app language and excels at formatting data for the presentation layer.  Java is great for creating data structures, algorithms, database connectivity, transactions, etc

The great thing about Quercus is it allows us to take advantage of both languages by using them seamlessly together: with PHP as the presentation of a Java based business tier.  With Quercus, you can write your data structures and business logic with Java, which then passes the results to PHP to be formatted and sent to the client.  This process is simple because Quercus PHP can seamlessly call Java objects/methods.   Using the best parts of both languages, one can do some really cool stuff.
  • Call Lucane, Hadoop, Cassandra (and more) directly from PHP.
  • Create complex and fast data structures in Java, which are then queried and displayed with PHP.
  • Application scope objects in PHP that are backed by Java objects.
  • Utilize the rich PHP web templating, with the vast array of Java middle-ware libraries.
  • Shared data structures between PHP and Java components of an application. 
  • Choose which parts of the application are best suited for PH P and/or Java
Quercus PHP is able to do the above because, of course, Quercus is ultimately Java.  For an introduction on using Java objects with Quercus, see this.


3) Database Connection Pooling.

One of the best features of Java  is database connection pooling.  Database connection pooling allows database connections to be managed by a pool that automatically grows and shrinks according to demand.  Connection pools save resources because database connections do not need to be constantly created/destroyed which has considerable overhead, particularly when done over remote connections.  Not only does this help the web layer, it also saves resources at the database layer because only a minimal amount of persistent connections need to be maintained.

Out of the box, Quercus allows the use of database pooling without having to change a line of php/mysql code!  Moreover, one can use PHP to Java integration (see point #2) to access Java objeccts backed by JDBC connection pooling.

4)  Scalable AJAX with PHP running on Java NIO

One of the problems with most setups of PHP is that there is one (thick) process attached to each request that blocks the process/thread until the response is sent.  On the other hand, Java has the option of using NIO (non-blocking IO) in the Servlet container.  This means that there is no longer a one to one ratio between requests and threads, but there can be many thousands of requests that are being severed by a small number of threads.  This is particularly good for AJAX, because many of those connections will be waiting for the next request within a keep alive.   By simply enabling an NIO connector, Quercus can scale to handle large number of non-blocking AJAX style requests in PHP.  No reason to turn down those keep alives!


5) Scalable COMET with PHP via Servlet 3.0 Async

 NIO's best friend is the Servlet 3.0 Asynchronous processing.  Putting this two technologies together allows a highly scalable COMET style app.  Servlet 3.0 Asychronous processing allows the requst thread to immedately return to the pool and allow another thread to handle the response.  This allows a single thread to efficiently pipe messages to many listeners.  Using this technology one can create scalable push notificaitons, chat rooms, and virtual worlds.  While the above point (#4) is seamless to the PHP developer, creating COMET with PHP will require extra coding, but nothing more than calling a few Java classes (see point #2).


6) Improved Session Management.

The standard PHP implementation places all session data on the disk, which can be quite slow.  Zend PHP does allow writing sessions to a database, however this requires quite a bit of work. One thing that Zend PHP cannot do is manage the sessions directly in memory.

On ther other hand, Java Servlet containers provide several configurable session options which can be easily taken advantage of with Quercus PHP, since sessions in Quercus are written on top of Java sessions.  The following options require only a change in the xml file.  Here are some options:
  • Memory - the defualt of most servlet containers is to store the session objects in memory.  This is very fast because it does not require disk access and serialization at every request.
  • Memory to Disk - this option access the sessions from memory, but then serialized them to disk after a period of inactivity
  • Memory to Database - smilar to above but backed by a database.  This is great for distributed sessions.    
  
7) Application Scope Objects

Because the standard implemenation of PHP is share nothing,  sharing objects between processes requires a external resource: APC object cache, Memcache, or writing the object to disk.  All these approaches share a common problems.  First, the objects need to be serialized/serialized frequently.  Second, there is no garnatee that two requests are referencing the same object.  This can occur if one process retreives the object, and starts processing while another process has updated the object.

For Java Servlets, Application scope objects objects are trivial.  Because they are kept in memory, cached objects do not need to be serialized and each servlet will always have a copy of the most recent object.  Using a Java backed object in Quercus PHP, application scoped objects are simple.  Ofcourse you could always serialize the object to disk/memccahe with Quercus just like you do with standard PHP, if that is what you desire.

Another option is to use the built in Quercus APC module.  This module works just like the normal APC and it is seamless to the PHP developer.