Search code examples
restweb-servicessynchronization

Add Subtract API synchronisation


I have a balance stored on a server in a database. I would like to have two API's

  1. addToBalance(amountToAdd)
  2. subtractFromBalance(amountToSubtract)

My problem is as follows If a user is on a mobile and calls one of these then loses connection we have no way of telling if the balance was updated. So we do not know whether or not to retry.

A solution I came up with was to give the current balance as the client knows it to verify whether there has already been an update, the update should fail if the balance provided does not match the actual current balance. The problem with this solution is, if the balance is updated from elsewhere then the call will fail. We will not know whether to differentiate between the two failures so still do not know whether or not to retry.

Does anyone have a possible solution to ensure that the same call does not get made multiple times to avoid multiple additions and subtractions?


Solution

  • That's a common problem, and HTTP itself has the solution for you, which is to make the request conditional.

    When the user retrieves that resource with a GET, you should return the Last-Modified header with a timestamp of the last time the resource was changed. Then you require the user to send the If-Unmodified-Since header with that value when changing it.

    If someone else changed it in between, the resource timestamp will be greater than the value sent in the If-Unmodified-Since, and you should fail the request with 412 Precondition Failed. If the user failed to include the If-Unmodified-Since header, you should fail with 428 Precondition Required