Z
Z
zzox42016-08-02 15:31:26
Database design
zzox4, 2016-08-02 15:31:26

How to "holistically" call an external API in a transaction?

* there is a process of buying a product, it is executed in a transaction
* a process (function) calls different modules (functions) which, in turn, call other modules, and somewhere an external API can be called, sending events, letters, etc.
* API call: can be sending a request over the network or adding a task to the database (in the same transaction / or a separate one?) and launching an external worker to perform this task.
How to make the integrity of the entire process with an API call, etc., if the transaction breaks at some point?
The API itself can also throw an exception.
Event broadcasting can be removed at the end when a commit occurs, because they do not affect the process.
Letters and tasks can be kept in the same transaction, and they will be rolled back on rollback. But workers will be started for tasks that don't exist, apparently they have to wait for some time, or be daemons (running all the time).
If there were any external calls, this information needs to be saved somewhere, and if an error occurs, after the rollback, pull the code that will roll back the external call, etc.
Total: for this you need to do everything in one transaction, and the ability to add triggers to the commit / rollback of the current transaction. (reasoning in the course of writing)
This is without taking into account that the server may fall.
What if some module threw an exception, but this is expected (except), then some fragments from the work of the module may be preserved. Use nested transactions?, which databases support it?
What other ways are there, how do you solve this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew, 2016-08-02
@zzox4

The simplest example, in C# pseudocode:

using(var txn = new TransactionScope(...))
{
    try
    {
        DoStuffWithDatabase();
        DoStuffWithApi();
        
        txn.Commit();
    }
    catch(Exception ex)
    {
        txn.Rollback();
        ex.Handle();
    }
}

Thus, if an error occurs in the API, the transaction in the database will be rolled back.
This approach does not take into account the possibility that the server will crash hard between making a request to the external API and applying the transaction - in this case, data may be lost, but this situation is negligibly unlikely.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question