API Error Handling – Ensuring a Method is Called Only Once

apierror handling

In general, if I am using an API whose methods have side-effects that I only want to occur once, how can I guarantee that my own application only calls them once even if an error occurs before it can register a response?

For example, if I am calling a payment processing API once each month for a subscription service, how can I ensure that I don't double-bill if I create a new transaction and the application suffers a fatal error before I get the response from that? It seems like cooperation with the API would be a solution:

t = Transaction.new(user, price, etc);
if(t.persistToLocalDatabase()){ t.beginRemoteProcessing(); }

Is there a way to solve this for the case where I have no control over the API and it begins processing on transaction creation?

Best Answer

The first thing to do is to write a flag to disk before you start the transaction to indicate that this month's transaction has been attempted. That way you never accidentally call the API twice.

In the case of any kind of error, you need to make sure the system notifies a human (e.g. send an email) who can verify the transaction status and offers them a way to manually reprocess the transaction.

After a few months you'll discover either (a) The humans are bored of being contacted and you need to redesign the system (e.g find a way to automate the check/retry via the API) or (b) The system is running smoothly and everyone's happy. Hopefully (b).

Related Topic