sezaru

sezaru

Handle multiple atomically operations with side-effects

Hello,

Sometimes in my system, I want to change something in the database and also do some other side-effect, for example, filling a cache or sending a message, etc.

Normally what I do is something like this:

alias Ecto.Multi

Multi.new()
|> Multi.insert(:insert_data_to_db, data)
|> Multi.run(:update_cache, fn _, _ -> :ok = MyCache.update(data) end)
|> Repo.transaction(timeout: :infinity)

This works great since if my cache update fails for some reason, my insertion will fail too, avoiding situations that I would have successfully inserted my data into the database and failed to update the cache leaving it into an inconsistent state.

Now, let’s say that I want to also send the data to another process that needs to be done atomically too (it can be another thing too, the process is just an example, but it can be anything that needs to be added atomically).

alias Ecto.Multi

Multi.new()
|> Multi.insert(:insert_data_to_db, data)
|> Multi.run(:update_cache, fn _, _ -> :ok = MyCache.update(data) end)
|> Multi.run(:send_data, fn _, _ -> :ok = SendData.send(data) end)
|> Repo.transaction(timeout: :infinity)

Now the approach above doesn’t work anymore since if send data fails, the database will rollback, but the cache will not.

My question is, how do you guys handle this type of situation that you need to do multiple things and it all needs to be in a “apply all or apply nothing if something fails” manner?

Also, this example I used Ecto, but it can be another database too, or even without a database at all.

Another example, I have one situation that I store the last ids of some data I receive in my node, and I also need to send this data to clients via notification. So I first send the notifications then add they ids to the mnesia database, but if the notifications are sent correctly but my mnesia write fails, then again I would have an inconsistent state.

These types of situations seem very common to me, so I’m really wondering if there is a better solution and how you guys handle it.

Marked As Solved

mindok

mindok

The Saga pattern is meant for this I believe. I haven’t used it myself, but you could try something like https://github.com/Nebo15/sage

Edit: a bit of a backgrounder here https://medium.com/nebo-15/introducing-sage-a-sagas-pattern-implementation-in-elixir-3ad499f236f6

Also Liked

sezaru

sezaru

That’s amazing! Basically what I wanted, thanks a lot of the suggestion!

Where Next?

Popular in Questions Top

itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
Fl4m3Ph03n1x
Background Let’s assume I have a typical GenServer that receives messages as requests, does some operation in a DB and returns responses....
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

Other popular topics Top

itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

We're in Beta

About us Mission Statement