When to use caching techniques in an API?
We all know caching helps to improve the performance of an API. But often it is a two way sword. Without proper understanding of the problem, invalidation of cache will become a nightmare.
Let's learn some of the common use cases of caching in an API.
Frequently accessed data that is not going to change frequently
If you have a data that is frequently accessed but not chaging often, then caching is the best option to go.
For example, if you have a list of countries in your database, it is a good idea to cache it. Because it is not going to change frequently. So you can cache it for a day or two.
Data that is expensive to compute
If you have a data that is expensive to compute, caching is a good option.
For example, if you have a data that is computed by joining multiple tables, it is a good idea to cache it. Because it is expensive to compute again and again for each request. So you can cache it for specific time.
A good examples are,
- Generating reports from a database that is expensive to compute
- Any export data that are huge and computation heavy
Endpoints that requires shorter response time
If you have an endpoint that requires shorter response time, caching is a good option.
For example, often mobile app users likes shorter response time for the UI to appear. So mobile app developers enable caching layer at various level. Also, most mobile apps show cached data when the device is offline.
So to summarize when to use caching techniques in an API,
- Heavy read endpoints that are not going to change frequently
- Heavy computation endpoints that are not going to change frequently
- Endpoints that requires performance improvement or shorter response time
In next article, we will learn how to invalidate caches and how to choose caching wisely based on the invalidation strategy.
If you have any questions, please ask me on twitter @learnwithparam š¤.