Alex
Alex

Reputation: 1849

Dealing with multiple non-reversible operations within transactions?

As an example user performs some update action and three actions need to be performed together: update database, send email and perform network request to other service. Sending email and performing network request are non-transactional and if one fails and other succeeds we end up in the incorrect state. Are there common patterns for dealing with this?

Upvotes: 0

Views: 103

Answers (1)

Khanh TO
Khanh TO

Reputation: 48982

A common pattern that works for me is to create an Email table as a queue of emails, inserts to this table can be easily included in transactions.

There is another process reading this Email table and sending requests to external processes (smtp server, sendgrid,...) and marking the email as "sent" if we get a success response from external processes. In case there is a failure, the email is not marked as "sent" and could be retried. There could be a situation that an email was sent successfully but there was an error in the network causing a failure response, retrying could send duplicate emails, but that would be rare and should not cause issues.

You can also have a look at database email which is a similar pattern: https://learn.microsoft.com/en-us/sql/relational-databases/database-mail/database-mail?view=sql-server-ver15

We can extend this pattern further with sending network requests with the same idea. You can have a look at this https://microservices.io/patterns/data/transactional-outbox.html

Upvotes: 1

Related Questions