Making a Post request to a REST API from a WCF service in a transaction

Viewed 97

I am doing a series of work in a wcf service transaction.

1.Making a POST response to a rest api. 2.Processing POST req response and saving it in a db.

Above step 1 and step 2 are happening in a wcf transaction but as a result I have seen an issue where on having an exception step 2 doesn’t get committed but step 1 gets completed creating inconsistencies.

I have seen way out to achieve this through saga pattern or 2PC but couldn’t find any easy implementation or workaround.

PS : I NEED NOT TO ROLLBACK DATA FOR NOW JUST AVOID COMMITTING POST REQ TO REST API. Currently I am handling this by making another patch request to rest api to revert the response received in CATCH BLOCK.

1 Answers

The bad news:

There is no 2PC over rest apis. Rest is by definition stateless, does not include envelopes for metadata to be used in a two phase commit world, so you are out of luck here.

SOAP on the other hand supports the WS-Atomic Transaction protocols, though I would suggest that you use some technology like WCF where all this is implemented already. (net core does not support it, so it .net framework for this).

The somewhat good news:

Eventual consistency to the rescue. The SAGA Pattern is one way to achieve this in the microservices world. In it's simplest form, eventual consistency could be something as trivial as the following:

  1. Application 1 creates a DB row that described the action in Pending state
  2. Application 1 makes the post to a url
  3. The target api, creates an event with the result in a persistent way (on an event bus, a queue or even a database table that the Application 1 can access
  4. Some service or background thread of Application 1 constantly reads or listens to that event bus for the api's results
  5. Once it gets the result, it updates the row made on 1. It retries until possible. You can stop it at some point.

The negative of this approach, is that you need to manually intervene if 5 constantly fails. There are more complicated aspects involved (like compensating actions) but I'll leave this up to you for further study.

The other bad news

There is no out of the box implementation for eventual consistency :( If you can switch the REST Api to a SOAP with WSAT protocol enabled, then you can have out of box distributed transactions.

Related