Are Ecto Transactions concurrency safe

If you want to ensure unique sequential numbers, you should really be doing that at the database level, where it can actually be guaranteed, whether with a Postgres sequence or a MySQL autoincrement field.

I hit a related problem where I wanted to do a multi-stage, multi-process data import in a transaction, here’s a discussion and the solution I came up with: Using Ecto to run a long-running multi-process transaction

The TL;DR is that in Ecto, each process, when calling Repo commands, takes a connection from the pool and so any Repo calls within that process are serialised, including transactional ones. Other processes don’t know some other connection has a transaction open. As @benwilson512 said, the resultant semantics are dictated by the database itself.

According to this SO post (didn’t do more research), a Postgres sequence will simply increment each time it needs to, even if its value is not used (e.g. a transaction is rolled back). This can cause “gaps” in the numbering in that case but seems like the right solution.

If that’s unsatisfactory, perhaps some more information on your usecase would be good.

1 Like