Fl4m3Ph03n1x

Fl4m3Ph03n1x

Is this usage of Repo.transact an anti-pattern?

Background

I am studying the Transaction Script pattern, namely from a book called “Learning Domain Driven Design”.

For those of you unfamiliar with this pattern, here is a small description:

The Transaction Script organizes business logic by procedures, where each procedure handles a single request from the Public Interface of the application, aka, the presentation layer.

In the book, the author explains that one of the limitations of this pattern is when you have to take an action that must be atomic across several different storage/communication mechanisms. Imagine updating the database and sending a message via a broker - for the system to remain consistent, both must be done atomically.

  @spec execute_v1(integer(), NaiveDateTime.t()) :: :ok | {:error, any()}
  def execute_v1(user_id, visited_on) do
    Repo.query!("UPDATE \"user\" SET last_visit=$1 WHERE id=$2", [visited_on, user_id])

    MessageBus.publish(%{user_id: user_id, visited_on: visited_on})
  end

Question

In most languages, ensuring this behaviour remains consistent and transactional would be impossible to do. In fact this is the main premise to introduce CQRS and the Outbox Pattern in later chapters.

However Elixir does have a workaround for this limitation, that can make sure this set of operations is atomic and consequently ensures the consistency of the system (or so I believe):

@spec execute_v2(integer(), NaiveDateTime.t()) :: {:ok, [Postgrex.Result.t()]}
  def execute_v2(user_id, visited_on) do
    Repo.transact(fn ->
      update_result =
        Repo.query!("UPDATE \"user\" SET last_visit=$1 WHERE id=$2", [visited_on, user_id])

      :ok = MessageBus.publish(%{user_id: user_id, visited_on: visited_on})

      {:ok, [update_result]}
    end)
  end

By using Repo.transact Elixir allows us to make sure this piece of code is atomic. If publishing of the message fails, the Database operation is rolled back. In this specific instance, because we only send 1 message, I believe this workaround would work just fine.

Even though I am using this workaround in this context, I would like to make it clear I have seen people use it with all sorts of things. A few come to my mind:

  • Sending HTTP messages after writing to the database
  • Doing database writes on multiple storage systems (usually relational DBs and non-relational DBs at the same time)

However, I always have the same questions.

  1. Is Repo.transact supposed to be used this way?
  2. Isn’t this considered an anti-pattern by the community?
  3. What are the alternatives to this workaround, if any?

I am also curious to know if anyone else reading the code thinks this can fail in a way I have not yet predicted. Please let me know!

Most Liked

LostKobrakai

LostKobrakai

That’s code example is not consistent. You could publish to the message bus but fail to commit the transaction. This becomes more obvious once you look at sql queries behind this:

BEGIN TRANSACTION;
UPDATE …;
-- publish to message bus;
-- consider a failure here
COMMIT;

This is no different in elixir than it is anywhere else. The problem stems from distributed computing, which doesn’t care at all about what language runs on individual actors.

al2o3cr

al2o3cr

This is something that Oban can help with. Extract the external side-effect code to a background job, and then enqueue the job inside the transaction.

If the transaction commits, the job is executed.

If the transaction rolls back, the job rolls back with it and is never executed.

One limitation of this approach is that it can’t handle the “roll back the transaction if the external request fails” scenario.

garrison

garrison

Lol you guys, this is not a matter of implementation details. What @LostKobrakai was trying to tell you is that solving this is literally impossible.

You can have at-most-once or at-least-once but you cannot have exactly-once in these situations.

You can make one side of the transaction idempotent and then guarantee at-least-once for that side. For example, you could commit the row to Postgres first and then repeatedly attempt to publish the message with some sort of idempotency id until it succeeds. There was actually a pretty good post about this on the Tigerbeetle blog recently.

As a side note, @dimitarvp and I had a discussion about something similar a while ago and I want to point out that this sort of thing is what I was talking about. Gluing multiple databases together can be messy and hard to understand, even if you’re knowledgeable in this area.

An alternative approach is to just have a really scalable multi-model database and use it for everything. The database can then worry about atomic commits for you. FoundationDB was a pioneer of this approach, and it’s one of the things I’m trying to do in Elixir with Hobbes.

garrison

garrison

Yeah, unless someone does the enormous (ask me how I know) amount of work needed to serve as a base for another approach there is really not much you can do.

Ideally you just shove everything into Postgres as long as you can get away with it, as @al2o3cr alluded above. Postgres may have garbage consistency guarantees out of the box but at least its developers actually care about free software and won’t rugpull you at the earliest opportunity. And also at least it has a serializable flag even if nobody uses it lol.

If you need to hit an external API then you’re cooked but this is why good external APIs (e.g. Stripe) have idempotency as a first-class feature.

LostKobrakai

LostKobrakai

E.g. the database connection could drop. Another part of the system could make your ecto supervision tree restart, … There could be any number of reasons for the commit to not reach your database.

You’re correct that the elixir process executing your query is not doing a whole lot, but there’s many external factors you cannot control, but can very much prevent that commit.

Where Next?

Popular in Questions Top

LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
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
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
gonzofish
I’m currently trying to understand how to join three tables using Ecto. All the examples I’ve seen use 2, so maybe I’m just missing somet...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New

Other popular topics Top

belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
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