thiagomajesk

thiagomajesk

How to to insert multiple records asynchronously inside a transaction with Ecto

Hello, again folks!

I’ve been challenged by a problem this week and I’m not quite sure how to proceed to solve it. Also, I’ve spent a good amount of time today researching to better understand the said problem, however, I’m still kinda stuck with it. This is my drama…

I’m importing/ creating data using a CSV file, and I’m validating each line to see if the values are correctly filled/ formated and overall valid. Each row in this file has n columns, and they are not always part of the same schema (some of those columns are associations that should be created).

For example:

%Post{} that I want to create for each row:

schema "posts" do
  field :title, :string
  field :description, :string
  has_many :post_tags, PostTag
end

%Tag{} that exists beforehand:

schema "tags" do
  field :name, string
  # Let's say that we have to validate that the user 
  # has chosen from a value within a valid range
  field :max_possible_score, :integer
end

%PostTag{} relationship that will be inserted with the post:

schema "post_tags" do
  belongs_to :post, Post
  belongs_to :tag, Tag
  field :rating, :integer
end

And the file would look like this:

Title Description Taste Looks Popularity
how to cook lobster just lobster 5 10 100
how to cook beans just beans 4 8 70

So far, so good. I have a draft of the import logic in place and I was about to make some performance tests to start refactoring the code. The goal is to be able to import something like 20k rows with 100 columns.

The first thing that comes to mind is to chunk the rows that are being streamed from the file and process them asynchronously. But, I have to process everything in a transaction because If there’s even one invalid row, the whole operation should be invalid and not processed at all.

So what I’m doing right now is:

  • Getting all the rows from the CSV and generating a bunch of changesets
  • Filtering those changesets to see if they’re valid or not
  • If there’s at least one invalid changeset we abort the operation

In the end, I have a list of valid changesets for the %Post struct and the structure that I’m inserting is something similar to this (as a changeset, of course):

%Post{ 
  title: "how to cook lobster",
  description: "just lobster",
  post_tags: [
    %PostTag {
      tag_id: 1,
      rating: 5
    },
    %PostTag {
      tag_id: 2,
      rating: 10
    },
   %PostTag {
      tag_id: 1,
      post_id: nil,
      rating: 100
    }
  ]

Because I need to persist a struct with its association I’m having to use insert instead of insert_all (to keep the references). Looking to improve the code, I’ve wrapped the changesets in a transaction like this:

Repo.transaction(fn repo ->
  changesets
  |> Enum.chunk_every(10)
  |> Enum.map(fn chunk ->
     Task.async(fn -> 
        Enum.each(chunk, fn changeset ->
          repo.insert!(changeset)
        end
    end)
  end)
end)

I took inspiration from this comment and I thought this would work fine, but I got a series of errors ranging from database timeouts/ disconnects and problems with the test sandbox - It seems that there’s a problem with the processes sharing the same connection or something like this which I can’t quite put my finger on.

Besides that, I was trying to benchmark the code with benchee, and I got really confused about what exactly was going on. If the problem was in my test case or on the async routine and so on…

I’ve read multiple old replies of @michalmuskala talking about this not being supported and there are some old comments about it here too. I’m not sure if this is still true to this day or if I’m missing something here.

Could someone give me a hint on how to overcome this?

First Post!

al2o3cr

al2o3cr

First caveat from that post:

The parallel bulk inserts are not wrapped in a single transaction. You have to deal with individual chunk errors.

The transaction is going to force all of this to go through a single DB connection, so even if this worked it would still ultimately result in each SQL statement executing sequentially.

One option (I haven’t tried this at this scale) would be to build a giant Ecto.Multi with all the changesets and then pass that to Repo.transaction; that will check that all the changesets have valid set before doing any SQL.

Where Next?

Popular in Questions Top

openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
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
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
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
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
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
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
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

Other popular topics Top

pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
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
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
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
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

We're in Beta

About us Mission Statement