Instructor: Our next technique is the caching.
Caching is used to store
frequently accessed data close to the API.
So if we have a data that the API access frequently
then it might be a good idea to store it somewhere close
to the API code instead of a database
that is usually stored on a different server
or sometimes even in a different data center.
Now, cache engines usually store the data in-memory
so the retrieval of the data
from the cache is extremely fast.
There is no IO operation, there is no network.
It simply goes to the memory and retrieve the data.
Now, when working with caching,
always make sure to set expiration and invalidation
so that the data in the cache will automatically expire
after a predefined interval.
And also the data will be invalidated,
which means deleted from the cache when something happened.
For example, if you store in the cache
the list of users of the system
then when this list is modified
and a new user is added,
then the data in the cache should be invalidated
because it's not relevant anymore.
This data is called stale data,
and you should always try your best
to avoid having stale data in the cache.
In this code example,
you see an implementation of ResponseCache in ASP.NET core.
And as you can see, this cache has a duration of 30 seconds.
Now, what this means is that the response
from this web API, the item web API,
is cached on the web server for 30 seconds.
So after the first request,
any subsequent request for 30 seconds will get the response
from the cache and not from the code.
And this way, the time of executing the code
and probably going to the database,
is saved and the performance vastly improve.