The word "cache" comes up very often in conversations about software, and it is quite interesting. Not only because it carries a promise of better performance, but also because it... rarely says anything specific about how that will be achieved and what consequences come with it. It is more of a catch-all word. Most often you hear "if things get bad, we'll cache something", but that is rather vague for the client, and it is not a remedy for everything either. Which does not change the fact that it is a very useful technique when used properly.
So let's think about what actually hides behind this term and at which levels you can use it. It is a fairly wide spectrum of similar measures that can be applied in many places in the software, and usually independently of one another. And it may not be used at all because of its downsides. Which ones? Read on.
What is a cache, anyway?
It is a storage area where information that has already been calculated or fetched once is saved, so it can be used again later without repeating time-consuming operations a second (and every following) time. In addition, such a store involves not the server (so there is no need for an expensive request to a remote machine), but the disk, which is "on site". This can even increase the throughput of the server, which is used only when necessary.
For example, imagine that you often display a list of documents that takes 10 seconds to load. That would be tolerable if you needed the list once a day, but the wait becomes a ball and chain when you work in the system regularly and have to refresh that screen almost every minute to react as quickly as possible when a new contract appears. A cache can help here: the system fetches the list the traditional way only the first time, and then for a while (say 5 minutes) it uses that response on every refresh. As a result, only the first display of the documents takes 10 seconds, and the following ones take a second or two, or even a fraction of a second.
Of course, the advantage is easy to see: the app gets faster, on many levels, since the document list is just an example. But the biggest drawback is visible too. If a new contract appears within those 5 minutes, the system will not show it. What is more, the data in the system may become inconsistent, because a user can get an email notification that a new document has appeared in the system, but it will not be on the list. In some cases this is perfectly harmless (for example the number of likes on our tweet on Twitter), but in others, like the contract example above, it can already be an inconvenience.
That is why, as with the optimization we have already discussed, the use of caching should be well thought out and should hit the business side of the system as little as possible. A cache also does not replace speeding up the app in the usual way, that is by shortening the original execution time of certain operations. It can, however, be useful for shared, rarely changing data sets or in very popular services. Not to mention that every one of us actually uses a cache without knowing it, but more on that in a moment.
What can be cached?
The example above is only a taste of what can be stored in a cache and later restored. As I mentioned, a cache can work at many levels. Here is a simplified diagram of how a user uses a web application.
It should show fairly well the places where caching can work if the developer makes good use of it.
Browser
Users do not always realize it, but loading a web page almost never comes down to a single file. CSS and JS files, images and other media are downloaded separately. And browsers usually try, on their own, to save all these files in a cache and use them later. That is why the first visit to a page usually takes a bit longer than the next one. Even though the content (for example the news on the home page) may change, the browser can on its own retrieve the files that define the look of the site and insert them without asking the server, which shortens the page load time.
A developer can take advantage of this, although the truth is that most often there is nothing extra to do beyond splitting the page into files properly. On the contrary, there are situations where browser caching is actually too strong, especially on sites built on JavaScript frontend frameworks. So just as caching tricks are used, there are tricks to prevent it, for example suitable headers in HTTP responses, META tags or adding parameters to scripts.
Frontend application
Closely related to the previous point is the client application itself, meaning one whose files are downloaded and often cached by the browser (as opposed to the server application, which stays on the side of the server, you will never guess). Apart from the "automatic" techniques described above, you can also bring in mechanisms such as cookies, local storage and session storage. This may not quite count as caching in the strict sense, but it is how, for example, the filters set on lists are usually saved, so they can be restored later and the user does not waste time configuring all the options again. Still, it is easy to imagine using these mechanisms as a cache too. If the frontend application fetches some data that we want to "keep", we can use a local store for it, and when the user comes back to the given subpage, use the saved information instead of sending another request to the server. It all depends on the situation and needs.
HTTP server
When a request reaches the server, it passes through the HTTP server, which manages the applications on the machine. Here too we can configure things so that, for example, NGINX uses its own cache instead of reading the site's files. Remember also that both Apache and NGINX can automatically add certain headers to responses, including those related to caching. One sign of a good system for restoring locally saved data is that it happens as automatically as possible, without extra operations, which also take time.
And as if that were not enough, there are solutions like Varnish Cache, which can be very helpful on heavily loaded sites, but they require more work to introduce skillfully into the application environment.
Backend application and database
That is the server application mentioned many times already. I combined this section with the database, because this is where developers probably have the most room to show their skill, and the two are closely tied together. You can:
- cache the application's own data, that is pregenerated page files, if it is a so-called monolith,
- manage calls both to the actual database and to a store where recently fetched data is kept (Memcached or Redis),
- store calculated intermediate data in the database (for example, if we call one subquery very often, it may be worth calling it from time to time and then using the saved result).
True, I have not listed many points, but each of them is "rich" and offers many possibilities. And it is caching the results of queries or calculations (which happen on the backend) that usually gains the most. It does not always pay off or is even welcome, but it is worth at least thinking about how to prepare individual parts of the code for this form of optimization in the future.
When to use caching?
We have already touched on this, but it is worth collecting it in one place. First of all, caching is worth considering for:
- operations whose result rarely changes,
- parts of the code that give the same result for every user,
- long-running calculations,
- operations that are called very often,
- data whose freshness is not critical,
- files that are rarely modified.
This is certainly not a complete list, but a signpost that can help at least partly analyze our software in this respect. It is also worth keeping in mind that caching has consequences and most often leads to inconsistent or delayed information. That is why it is so important to think through what may be restored from the cache, how, and over what period of time. Remember that a cache is not eternal: we can control after how long the application again runs the "full" processing of an operation whose result was cached earlier. It is also worth mentioning that using a cache means a greater need for disk space (both on the user's side and on the server), but these days that cost is negligible. A bigger concern is that a cache is one more area that can fall victim to cyberattacks.
Summary
Caching is certainly one of the more reliable ways to improve an application's performance, and usually an easier one than "real" optimization. But is it always better? That depends on the situation and on what is to be treated this way. Introducing this concept into software always involves a certain trade-off between speed and data consistency, so it should not be done thoughtlessly. Which does not change the fact that in many cases it "just works" automatically and gives exceptionally good results, without which we cannot imagine spending time on the Internet today.
Best regards and thank you, Jakub Rojek.


