gmile

gmile

Design puzzle when using Ecto.Multi

In my application I need to perform multiple things during transaction:

  1. call HTTP and load some data form a microservice,
  2. update some DB records,
  3. add a new record DB record,
  4. send an SMS verification code.

Ecto.Multi suites this purpose very well, but it looks like I’m facing some roadblocks with it. I need someone else’s opinion on my design.

Currently the code for process above looks like this:

# declaration_controller.ex
def create(conn, %{declaration: declaration_attrs} do
  case DeclarationAPI.create(declaration_attrs) do
    {:ok, %{declaration: declaration} = result} ->
      render(conn, "show.json", result)
    {:error, key, reason, _}
      render(conn, "error.json", %{key => reason})
  end
end

# declaration_api.ex
def create_declaration(declaration_attrs) do
  Repo.transaction(new_declaration_request(declaration_attrs))
end

def new_declaration(declaration_attrs) do
  settings = SettingsMicroserviceAPI.get()

  Multi.new
  |> Multi.update_all(:pending_declarations, pending_declarations_query(declaration_attrs), set: [status: "CANCELLED"])
  |> Multi.insert(:declaration, changeset(declaration_attrs, settings))
  |> Multi.run(:verification_code, Verification, :send_verification_code, [declaration_attrs])
end

There’s a problem with this design. Sometimes SettingsMicroserviceAPI.get() HTTP call will not return expected data: it may stumble upon 404 or even time out. In this case transaction has to be rolled back gracefully, and an error saying something along the lines SettingsMicroserviceAPI has timed out
should be returned to user who requested the initial create action.

So I thought: why don’t I add this HTTP call as a Multi step like this?:

Multi.new
|> Multi.run(:fetch_settings, fn _ -> SettingsMicroserviceAPI.get() end)
|> Multi.update_all(:pending_declarations, pending_declarations_query(declaration_attrs), set: [status: "CANCELLED"])
# ...

However in this case there’s no way I can access the settings in the changeset.

So I see two ways to go from here:

  1. Keep the microservice call where it is now, but add a validation to the Ecto.Multi chain,
  2. Push the microservice call directly to changeset.

I tried both approaches and here’s what learned.

1. Keep the microservice call where it is now, but add a validation to the Ecto.Multi chain

The microservice call will always return {:ok, data} or {:error, :data}. This suites Ecto.Multi.run requirement for function’s return value so my code becomes this:

def new_declaration(declaration_attrs, user_id) do
  settings = SettingsMicroserviceAPI.get()

  Multi.new
  |> Multi.run(:fetch_settings, fn _ -> settings end)
  |> Multi.update_all(:pending_declarations, pending_declarations_query(declaration_attrs), set: [status: "CANCELLED"])
  |> Multi.insert(:declaration, changeset(pending_declaration_attrs, settings))
  |> Multi.run(:verification_code, Verification, :send_verification_code, [declaration_attrs])
end

Now, Ecto.Multi will validate the settings: in case of {:error, _} = settings the transaction will be rolled back, and a nice error will be returned to controller.

There are two problems with this, however:

  1. I have to update the signature of changeset from this:

    def changeset(attrs, settings)
      # ...
    end
    

    to this:

    def changeset(attrs, %{:ok, settings})
      # ...
    end
    

    which looks a little ugly.

  2. In case of {:error, _} = settings, I need to add another changeset function clause, as otherwise the code will raise a no matched function error.

2. Push the microservice call directly to changeset

I can do this (the actual code was reduced for brevity):

def create_changeset(attrs) do
  %Declaration{}
  |> cast(attrs, @required_fields)
  |> fetch_settings()
end

def fetch_settings(changeset) do
  result = SettingsMicroserviceAPI.get()

  case result do
    {:ok, settings} ->
      put_change(changeset, :_settings, settings)
    {:error, reason}
      add_error(changeset, :_settings, reason)
  end
end

This works, but with two caveats:

  1. In case I need to use settings across multi steps, inside verification code step for example, I’d have to rewrite the verification step to something like this:

    # ...
    |> Multi.run(:verification_code, fn multi ->
         settings = multi.declaration.get_change(:_settings)
    
         Verification.send_verification_code(declaration_attrs, settings))
       end)
    
  2. I’m not aware of a standard mechanism for storing arbitrary data alongside the changeset, so I have to use a temporal private _settings key.
    This works right now, but there’s no guarantee changeset becomes more strict in future, to disallow fields not described in the schema?


I’m sticking to the second solution right now as it seems to work (at least on the paper;
I’m yet to implement it). But I wonder how everyone handle HTTP interaction with 3rd parties
during transactions?

Maybe this design is inherently wrong, and there’s an “official way” to deal with these kinds
of situations.

Marked As Solved

wojtekmach

wojtekmach

Hex Core Team

Since the 3rd party call does not depend on any data within Multi I’d definitely keep it out. Seems like a good use case for with which will simply propagate the error from API:

with {:ok, settings} <- settings_api.get() do
  Ecto.Multi.new
  |> Multi.update_all(...)
  |> ...
  |> Repo.transaction
end

Where Next?

Popular in Questions Top

gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
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
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
Exadra37
Sometimes I want to check if the input into a function is not a blank string. My first approach: defmodule Example do def do_stuff(s...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
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

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
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
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
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
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
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
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
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New

We're in Beta

About us Mission Statement