Result caching vs continuous recalculation of the same?

The server gives the clients some data. For example, the statistics report of the store for the day. It contains rows with amounts purchases, including all taxes, etc and the last row is the sum of all categories (we want to sum many things and many rows). The total tax for all items, the total amount of purchases, etc. That is, when each query to the server you need to give this information to all who ask. How best to organize it - each time to recalculate the new amount for each request, or store the "amount" field in the database and adding new purchases to increase it?

P. S. If you constantly consider the same, theoretically, the process will work for nothing. Why infinite times to count the same thing, when you can just store the result and update it as new rows in a table?
June 5th 19 at 21:54
2 answers
June 5th 19 at 21:56
How long is this summation?
How many times a day you need to give this statistics?
How long is the return of the rest of the content?

Early optimization to no good result.
You can spend a lot of nerve and time to validate the cache, and not see a performance difference.
And if I find it easier to incrementing the amount field in the database, than writing complex algorithm for the summation, search and price collection in the subarrays and the sub, if it's about Mongo? - Ofelia72 commented on June 5th 19 at 21:59
have order more often is the status
Let's say it's open/completed/cancelled.
What will happen to your field, if the Manager will change unpredictably the number of times of status of order in different directions? Job plus: in doing so he diminishes or adds products that change the amount of the order. And this is a real case that I have ever encountered.

With the sprouting of the product sooner or later someone will add a new status and forget to add it to your cache.

One solution is to compute the value and cache for 5-10 minutes, many shops will be enough. The minus of the solution count can consume a lot of resources depending on the organization of the data and to be even longer than 5-10 minutes. - santiago commented on June 5th 19 at 22:02
June 5th 19 at 21:58
One of the great said. "In programming, there are only two really difficult things is coming up with names for variables and invalidating the cache."(C)

If capacity allows without caching, it is better not to use it.
Today is a great day - have a question about the name of the variables and about the cache. - Ofelia72 commented on June 5th 19 at 22:01
>>inventing names for variables and invalidating the cache.

And how scope and memory leak? - santiago commented on June 5th 19 at 22:04

Find more questions by tags Programming