Caching within a request

I stumbled upon this Lucee Recipe earlier.

At first I was baffled on why I’d want to cache a query within the current request. The only thing I can think of off the top of my head is if the query was inside a loop.

Are there oher scenarios where cachedWithin="request" would come in handy?

Cache a Query for the current request

Perhaps you’re familiar with the “cachedwithin” attribute of the tag [tag-query], which is normally used as follows:

<cfquery cachedWithin="#createTimeSpan(0,0,0,1)#"> select * from whatever where whatsoever='#whatsoever#' 
</cfquery>

This caches the query result for ALL users for one second. This is sometimes used to cache a query for the current request because usually most requests are completed in less than a second.

The problem is that this cache applies to all requests and that’s more complicated for Lucee, meaning unnecessary overhead on the system.

Request query caching is a simple solution to this problem. Replace the timespan defined in the “cachedWithin” attribute with the value “request”:

<cfquery cachedWithin="request"> select * from whatever where whatsoever='#whatsoever#' </cfquery>

Then the query is cached for only the current request, independent of how long the request takes!

Depends how complex your code base is, applications often have widgets or sub views that might render separately but also in an initial request, these might share data / queries, for performance it might make sense to only hit the database once for the same request

1 Like