Question

I am writing a rather large application that allows people to send text messages and emails. I will charge 7c per SMS and 2c per email sent. I will allow people to "recharge" their account. So, the end result is likely to be a database table with a few small entries like +100 and many, many entries like -0.02 and -0.07.

I need to check a person's balance immediately when they are trying to send an email or a message.

The obvious answer is to have cached "total" somewhere, and update it whenever something is added or taken out. However, as always in programming, there is more to it: what about monthly statements, where the balance needs to be carried forward from the previous month? My "intuitive" solution is to have two levels of cache: one for the current month, and one entry for each month (or billing period) with three entries:

  • The total added
  • The total taken out
  • The balance to that point

Are there better, established ways to deal with this problem?

Was it helpful?

Solution

Largely depends on the RDBMS.

If it were SQL Server, one solution is to create an Indexed view (or views) to automatically incrementally calculate and hold the aggregated values.

Another solution is to use triggers to aggregate whenever a row is inserted at the finest granularity of detail.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top