I have a php web application where certain data changes on a weekly basis but is read very frequently often.
The SQL queries that retrieve the data and the php code for html output are fairly complex. There are multiple table joins, and numerous calculations - but they result in a fairly basic html table. Users are grouped, and the table is the same for each group each week, but different for different groups. I could potentially have hundreds of tables for thousands of users.
For performance reasons, I'd like to cache this data. Rather than running these queries and calculations every time someone hits the page, I want to run a weekly process to generate the table for each group giving me a simple read when required.
I'd be interested to know what techniques you've used successfully or unsuccessfully to achieve something like this?
Options I can see include:
Any other suggestions would be welcome!
A cache-aside cache is the most common caching strategy available. The fundamental data retrieval logic can be summarized as follows: When your application needs to read data from the database, it checks the cache first to determine whether the data is available.
Write-through ensures that data is always fresh, but can fail with empty nodes and can populate the cache with superfluous data. By adding a time to live (TTL) value to each write, you can have the advantages of each strategy. At the same time, you can and largely avoid cluttering up the cache with extra data.
Caching is a technique of storing frequently used data/information in memory, so that, when the same data/information is needed next time, it could be directly retrieved from the memory instead of being generated by the application.
In the function to generate the table, make it store the result to a file on disk:
/cache/groups/1.txt
/cache/groups/2.txt
You don't necessarily have to run a weekly batch job for it, when calling the function to get the data, check if the cache is out of date (or non-existent). If so, generate and cache the results then. If not, just return the cached file.
function getGroupTable($groupId) {
if (cacheIsStale($groupId)) {
generateCache($groupId);
}
return file_get_contents($cacheFile);
}
The cacheIsStale()
function could just look at the file's timestamps to test for freshness.
There are indeed a few options:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With