jerry

jerry

Ecto postgres database simultaneous update

Hello All,

I have an issue I need your assistance on.

I have a table that contains unique account information on my customers.
Whenever there are simultaneous/concurrent updates on an account record, the resulting balance is wrong.

What is the best way to handle this in order to ensure that even when there are multiple update requests on an account in the table, the updates are performed one by one in a such a sequential manner to ensure the balances are correct in the account table?

I would be sincerely grateful for your assistance.

Thanks.

Jerry

Marked As Solved

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

To be clear update_all isn’t the thing that makes the difference here, it’s that you’re using inc to do the math in the database, and inc requires update_all.

For example this uses update_all but is still wrong

new_balance=current_balance + 5

Account |> where(id: ^account_id) |> update(set: [balance: new_balance]) |> Repo.update_all([])

The math is happening in Elixir, so it’s subject to race conditions. If you want to do the math in Elixir you need to use a lock like I showed you in option #2. That lock requires a transaction, it doesn’t matter whether that transaction is handled via Multi or via Repo.transaction with an anonymous function.

Also Liked

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Here are some options you can use to serialize access to rows. Regardless of which of these you use, I highly recommend also having a table that logs balance changes on each account, like a ledger. This allows you to audit the total in the future, and debug any issues.

Option 1: Avoid read, modify, write patterns.

Instead of doing:

account = Repo.get(Account, account_id)
account |> Account.changeset(%{balance: account.balance + 5}) |> Repo.update!

Do:

Account |> where(id: ^account_id) |> update(inc: [balance: 5]) |> Repo.update_all([])

In this approach, you change the balance in a single SQL query instead of two, avoiding race conditions. Postgres will ensure that the single update query runs atomicly.

Option 2: SELECT FOR UPDATE

If you can’t avoid read, modify, write, then take a lock on the row you wish to update:

Repo.transaction(fn ->
  account = Account |> lock("FOR UPDATE") |> Repo.get!(account_id)
  account |> Account.changeset(%{balance: account.balance + 5}) |> Repo.update!
end)

This locks access to the account row for the duration of the transaction, allowing your process to safely reason about it.

If conflict is rare, you can also try doing Ecto.Changeset — Ecto v3.14.0 instead.

15
Post #2
benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

You can find more information here: Ecto.Query — Ecto v3.14.0

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe
account_id=record.account_id
current_balance=record.balance

new_balance=current_balance + 5

Account |> where(id: ^account_id) |> update(set: [balance: new_balance]) |> Repo.update_all([])

This is still a read, modify, write. This will not work safely. You must use inc: so that the change happens in a single atomic operation, OR you have to explicilty lock.

Last Post!

jerry

jerry

Thanks very much @benwilson512.
I’ve been able to implement the solution as you guided me to do.

Thanks @hauleth for your inputs as well.

It required a total rewrite of that aspect of the application’s engine.
This has been a very good learning process for me.

I shall provide some more feedback after some time of monitoring the application under heavy traffic.

Jerry

Where Next?

Popular in Questions Top

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
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
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

Other popular topics Top

hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
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
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 49134 226
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New

We're in Beta

About us Mission Statement