I have a database where products are kept.
There is also a list of categories.
Each product belongs to a category.
When a list of products updates, I run a function updateProductsCategories()
that queries database, calculates a number of products in each category and returns a list like this:
Food: 20
Drinks: 74
Jackets: 15
I use this list in a web page sidebar to show categories as links with amount of products in it.
My assumption is that I should run updateProductsCategories()
as it is when products change, though not call it each time a page loads, but put its result in an in-memory object and get data from it to show on the page.
That way I will not make unnecessary db queries every time I show the page, but will use cached data and will have it always up-to-date as it's refreshed when products change.
As the object is not large, I don't think I need any additional solutions like Redis now.
Is it a correct and common way to optimize the app? Will it add speed to the app in real world?