Mid-Page ColdFusion Session Expiration Behavior

Posted December 10, 2007 at 9:31 AM by Ben Nadel

Tags: ColdFusion

I wanted to write a post about some session management strategies, but I realized that I didn't fully know how session behaviors interacted with page requests. Specifically, what would happen in the seemingly rare case that a ColdFusion session timed out in the middle of a page request? Normally, this is not a scenario that would naturally occur, but with ColdFusion 8's CFThread tag, forcing this is quite an easy task.

What we are going to do is create an application with a really short session timeout. Then, we are going to create a request who's processing time is explicitly greater than the defined duration of the session and see what kind of fall-out the mid-page request session expriation causes.

First, we need to set up the simple Application.cfc:

  • <cfcomponent
  • output="false"
  • hint="Handle the application configuration.">
  •  
  •  
  • <!---
  • Set the application settings. Notice that we
  • are creating sessions that only last for 2 seconds.
  • --->
  • <cfset THIS.Name = "TimeoutTest" />
  • <cfset THIS.ApplicationTimeout = CreateTimeSpan( 0, 0, 1, 0 ) />
  • <cfset THIS.SessionManagement = true />
  • <cfset THIS.SessionTimeout = CreateTimeSpan( 0, 0, 0, 2 ) />
  •  
  •  
  • <!--- Set the page request settings --->
  • <cfsetting
  • showdebugoutput="false"
  • />
  •  
  •  
  • <cffunction
  • name="OnSessionStart"
  • access="public"
  • returntype="boolean"
  • output="false"
  • hint="Fires when the user's session begins.">
  •  
  • <!--- Store the date created. --->
  • <cfset SESSION.DateCreated = Now() />
  •  
  • <!--- Return out. --->
  • <cfreturn true />
  • </cffunction>
  •  
  •  
  • <cffunction
  • name="OnSessionEnd"
  • access="public"
  • returntype="void"
  • output="false"
  • hint="Fires when the session is terminated.">
  •  
  • <!--- Define arguments. --->
  • <cfargument
  • name="Session"
  • type="struct"
  • required="true"
  • hint="The expired session scope."
  • />
  •  
  • <!--- Store the date destroyed. --->
  • <cfset ARGUMENTS.Session.DateEnded = Now() />
  •  
  • <!--- Return out. --->
  • <cfreturn />
  • </cffunction>
  •  
  • </cfcomponent>

A few things to notice in the above ColdFusion Application.cfc component. For starters, our SessionTimeout is set to only 2 seconds. In the OnSessionStart() application event method, we are storing the time that the session is created and in the OnSessionEnd() event method, we are storing the time that the session was ended. In the OnSessionEnd() event method, we have to store this date/time stamp directly into the passed-in argument since the SESSION scope no longer exists on its own.

Ok, now that we have that in place, let's create a long running page. Again, with ColdFusion 8's new CFThread tag, sleeping a thread becomes a no-brainer:

  • <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  • <html>
  • <head>
  • <title>ColdFusion Session Timeout Test</title>
  • </head>
  • <body>
  •  
  • <h1>
  • 2 Second ColdFusion Session Timeout Test
  • </h1>
  •  
  • <!---
  • Pause the thread for longer than the session
  • should run for. By doing this, it means that the
  • session should timeout during the process.
  • --->
  • <cfthread
  • action="sleep"
  • duration="#(10 * 1000)#"
  • />
  •  
  •  
  • <p>
  • Session Created:
  •  
  • #TimeFormat(
  • SESSION.DateCreated,
  • "hh:mm:ss"
  • )#
  • </p>
  •  
  • <!--- Check to see if the session has been ended. --->
  • <cfif StructKeyExists( SESSION, "DateEnded" )>
  •  
  • <p>
  • Session Ended:
  •  
  • #TimeFormat(
  • SESSION.DateEnded,
  • "hh:mm:ss"
  • )#
  • </p>
  •  
  • </cfif>
  •  
  • <p>
  • Page Ended:
  •  
  • #TimeFormat(
  • Now(),
  • "hh:mm:ss"
  • )#
  • </p>
  •  
  • </body>
  • </html>

Here, we sleep the thread for 10 seconds - 8 seconds longer than the allowable session timeout. Once the thread has stopped sleeping, we output the time the session was created. Then, we check to see if the DateEnded key has been added to the session. Remember, this key will ONLY exist if the OnSessionEnd() event method has been called. Then, I simply output the time the page finishes rendering.

Running the above page, we get the following output:

Session Created: 09:09:41

Session Ended: 09:09:45

Page Ended: 09:09:51

Notice that the session ended 6 seconds before the page request ended.

There's a couple of intersting things going on here. First off, the session DID timeout mid-page (just so we are clear on that point). And, even with a 2 second SESSION timeout, the OnSessionEnd() get's fired 4 seconds after the session began. This is really an insignificant detail, but clearly, OnSessionEnd() cannot be thought of or depended on as an instantaneous event listener. Not that that should matter to anyone, but just throwing it out there.

The second thing, which is hugely important, is that the page did not error out even when the session ended. This means that once a session is created or even available at the beginning of a page request, you never have to worry about it being available later in the same page request - it will most definitely be there.

The third thing, which is also very interesting, is that the session scope that was passed into the OnSessionEnd() application event method was the same structure that the page request was using for its SESSION scope. This seems quite obivous when you think about it - afterall, it IS the session scope being passed to OnSessionEnd(); but I just find it very interesting to see that "pass by reference" feature in action on a SESSION scope.

In summary, it seems that session timeout should never be a concern of the executing page since session timeout mid-page has no effect on the existence of the session within that page context. This will come more into play in my future posts.




Reader Comments

Dec 12, 2007 at 2:39 PM // reply »
153 Comments

Interesting. (As was the follow-up post.) I had long thought this would be the case, what with reference-counting working the way it does in Java, but had never thought to test it.

But, as a thought experiment ...

If I've got a bunch of cleanup code in onSessionEnd that destroys objects, but then a still-executing page counts on them being there ... what then? Even cfLock won't help me. It's almost an argument to not use onSessionEnd and just let Java sort everything out, eh?

(Note that I'm kidding. Mostly. Kindof.)


Dec 12, 2007 at 3:07 PM // reply »
10,640 Comments

@Rick,

Ooh, that's really interesting! I rarely use OnSessionEnd() to do any sort of clean up so this didn't occur to me. But, I think you are absolutely right. Of course, you have to take into account that this only happens when your session timeout is insanely small.

Then again, in a CFThread environment (the follow up post), this is much more likely to occur (in comparison to a standard page request). You have no control over how threads get queued and I am sure there is no guarantee as to what happens when. If you are in a standard environment where maybe there is a 2-thread limit (from what I have heard) and you have threads creating PDFs and logging and a bunch of other stuff that is processing intensive, it could be possible to have an asynchronous thread that doesn't fire for 20, 30, 40 minutes?!?

In that case, clearing the session would mess you up if you relied on it at all.... very interesting! Of course, it depends heavily on the scenario.


Mar 25, 2010 at 4:29 PM // reply »
11 Comments

Hey Ben, this is indeed interesting. Another place it could come into play is if one lowers the sessiontimeout on a page, such as for a bot, where one may set it to something really low (if detected as a bot), to like 1 or even 0 seconds. The session could "timeout" before the page ended.

That said, you say not to worry because the session scope will still exist at least as a scope on the page. That may be true as far as reading from it (during the page request), but I do wonder about writing to it. I wonder if CF might try to write to the session in memory (wherever it is, outside the page request) and perhaps have a hiccup. Did you ever test that? :-)

Either way, I hope that the thought in my first paragraph above may make this entry even more interesting to those dealing with sessions and spiders, as you've covered so well in many other entries. Thanks for them all.


Oct 5, 2011 at 10:51 AM // reply »
1 Comments

Sorry to comment on such an old post, but would it be possible to prevent the session from expiring mid-request?


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Feb 10, 2012 at 7:21 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
Update! Instead of $(eval(options.insertAfter)).after(data['insertData']); I now use: var ajaxNode = document.createElement('span'); var parent = $(eval(options.insertAfter))[0].parentNode; ... read »
Feb 10, 2012 at 6:18 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
encountered this same, what I consider, jQuery bug last week. I'm building a site in which I load some content via AJAX. This content contains Linkedin share button placeholders which Linkedin API ne ... read »
Feb 10, 2012 at 11:30 AM
Cross-Origin Resource Sharing (CORS) AJAX Requests Between jQuery And Node.js
After you understand the concepts here, this is an awesome cheatsheet for enabling CORS in just about anything http://enable-cors.org/ ... read »
JM
Feb 10, 2012 at 9:10 AM
My Safari Browser SQLite Database Hello World Example
@Amy, Here is a very good tutorial on how to use JOIN: http://www.sqltutorial.org/sqljoin-innerjoin.aspx ... read »
Feb 10, 2012 at 4:42 AM
Building A Twitter-Inspired RESTful API Architecture In ColdFusion
This is great, very useful Ben. I spotted a small typo in the api.cgm listing: <cfthrow type="Unauthroized" /> Cheers Stefan ... read »
Feb 9, 2012 at 10:35 PM
CFDirectory Filtering Uses Pipe Character For Multiple Filters (Thanks Steve Withington)
I was wondering if there would be a filter you could apply so that you got everything but what you included in the filter. As in show me all docs that are not a .pdf. ... read »
Feb 9, 2012 at 10:29 PM
Learning ColdFusion 9: Application-Specific Data Sources
@Ben, No offence, but if people were really wanting advanced features they would be using a platform like ASP.NET MVC. CFML is so structurally compromised as a tag-based scripting language that ... read »
Feb 9, 2012 at 10:03 PM
Subversion - Cleanup Failed To Process The Following Paths
@Leviaguirre, do you still have problems with this? ... read »