Data Consistency
You also need to consider data consistency when designing a mobile app.
Unlike relational databases, the Kii Cloud APIs do not support atomic transactions because Kii Cloud is designed with particular focus on scalability. Therefore, you need to keep data consistency with the program logic of your mobile app.
For more information about transactions, see "Transactions" (Android, iOS).
In order to keep data consistency in the environment that does not support transactions, you need to carefully design the data structure and the update rules.
Kii Balance calculates the balance after it downloads all KiiObjects that store income and expense data instead of saving the balance in a KiiObject. Suppose if the balance were saved in a KiiObject. When an entry were updated, the balance should be updated as well. An error or updates from multiple clients would easily cause inconsistency.
The figure below is an example of saving the balance in a KiiObject. Inconsistency would occur if Update 2 failed after Update 1 succeeded. Unlike relational databases, Update 1 would not be rolled back.
The figure below is an example of updates from multiple devices. "Optimistic locking"(Android, iOS) would detect updates from other devices but it would not ensure consistency. For example, suppose if two devices read data and performed Update A1, Update A2, Update B1, and Update B2 in order. Optimistic locking would make Update B2 fail but successful Update B1 would not be rolled back and inconsistency would occur.
As with this example, inconsistency occurs when concurrent updates fail for data values that are calculated from or dependent on other data items.
It is very difficult to prevent inconsistency. You need to keep data consistency with the program logic if you need to store such dependent values, for instance, to improve performance.
For example with Kii Balance, when an income or expense entry is written to the balance_book
bucket, you may want to save the timestamp for the entry and the balance in a KiiObject dedicated to the balance. When the data listing screen opens, get a KiiObject with the latest timestamp and compare it with that stored in the KiiObject for the balance. If the timestamps are different, recalculate the balance.
For mobile apps like Kii Balance, you may also want to make use of the specification of your mobile app. It would be an idea to freeze the entries and set the monthly balance at every month end.