thiagopmac
I’m building a Phoenix server that handles financial transactions, It’s very simple it creates an account, creates a user, and processes transactions between users. The question that I have is related to concurrency, to give more context the code below creates a transaction:
def create_transaction(%{sender_id: sender_id, recipient_id: recipient_id, amount: amount}) do
sender_update_query =
from Account,
where: [id: ^sender_id],
update: [inc: [balance: ^(-amount)]]
recipient_update_query =
from Account,
where: [id: ^recipient_id],
update: [inc: [balance: ^(+amount)]]
Multi.new()
|> Multi.run(:retrieved_accounts, &retrieved_accounts(&1, &2, recipient_id, sender_id))
|> Multi.run(:check_sender_funds, &check_sender_funds(&1, &2, amount))
|> Multi.update_all(:recipient_update_query, recipient_update_query, [])
|> Multi.run(:check_recipient_update_query, &check_recipient_update_query(&1, &2))
|> Multi.update_all(:sender_update_query, sender_update_query, [])
|> Multi.run(:check_sender_update_query, &check_sender_update_query(&1, &2))
|> Multi.insert(:insert_transaction, %Transaction{
sender_id: sender_id,
recipient_id: recipient_id,
amount: amount
})
|> Repo.transaction()
|> handle_multi()
end
defp retrieved_accounts(_repo, _changes, recipient_id, sender_id) do
id_list = [sender_id, recipient_id]
Accounts.get_sender_and_recipient_accounts(id_list, sender_id, recipient_id)
end
defp check_sender_funds(_repo, %{retrieved_accounts: [sender_account, _]}, amount) do
if sender_account.balance - amount >= 0,
do: {:ok, nil},
else: {:error, :insufficient_funds}
end
defp check_recipient_update_query(
_repo,
%{recipient_update_query: {1, _}}
) do
{:ok, nil}
end
defp check_recipient_update_query(
_repo,
%{recipient_update_query: {_, _}}
) do
{:error, :failed_transfer}
end
defp check_sender_update_query(
_repo,
%{sender_update_query: {1, _}}
) do
{:ok, nil}
end
defp check_sender_update_query(_repo, %{sender_update_query: {_, _}}) do
{:error, :failed_transfer}
end
defp handle_multi({:ok, %{insert_transaction: transaction}}), do: {:ok, transaction}
defp handle_multi({:ok, %{update_transaction: transaction}}), do: {:ok, transaction}
defp handle_multi({:error, _id, error_or_changeset, _multi}), do: {:error, error_or_changeset}
My question is if this function will handle cases where multiple transactions can happen at the same time.
Another thing that I should mention is that I also have a function that charges back the transaction, which means that the balance can be modified by another function. I don’t know if Ecto can handle this kind of operation or if I should try to use something like a Genserver to orchestrate the transactions. Thoughts?
Trending in Questions
Hello!
Suppose you are building workflow (order / task / payment) processing system with the following requirements:
Each workflow con...
New
Hey guys,
I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly
Do you guys have any suggestions what is the best prac...
New
Kia ora,
We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
Hello!
Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app.
I creat...
New
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
Hello,
I’m developing a online persistent chat system (what’s app) like using elixir/dynamodb/aws for a mobile app(flutter).
The diffic...
New
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New
Other Trending Topics
Hobbes is a low-level distributed database for the Elixir programming language.
Hobbes provides a simple, safe, and scalable storage lay...
New
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve.
They are GUI (Emerge) and State management (S...
New
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
There are three potential reasons for members of this forum to have a look at https://vutuv.de
You are tired or annoyed of LinkedIn.
Yo...
New
ICal is a library for interacting with iCalendar data. It parses iCalendars into typed Elixir structs via ICal.from_ics, and can prepare ...
New
Latest Phoenix Threads
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #blog-post
- #ai
- #phoenix_html
- #elixirconf-us
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










Showing Posts 1 to 2- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
al2o3cr
This is mostly a general SQL question - Ecto provides some helpers, but the patterns are universal across a lot of ORMs.
There are two main strategies:
“pessimistic” locking: use the database’s locking mechanisms (
SELECT ... FOR UPDATEetc) to protect the rows before they are modified. Your code will need to deal with problems like deadlock - for instance, what should happen if Alice and Bob try to send money to each other simultaneously. Check outEcto.Query.lockand your DB"s docs (link is for PG) for more detail.“optimistic” locking: instead of using locks to ensure that nobody else writes to the rows, this adds a “version” to the rows and checks it on update. If something else has updated the row, the version won’t match and the update will need to be retried. See
Ecto.Changeset.optimistic_lockfor more detail.hubertlepicki
generally speaking, RDBMS systems have two mechanisms: transactions and locks. They can be used separately, but they can also be used together.
Transaction is a mechanism that ensures that all statements in the database will execute, and all records will be created/deleted/updated. If there’s an error, the whole transaction is rolled back.
Locks is another mechanism, where you can limit, or prevent altogether, many concurrent queries to happen at the same time.
In your example, you have transaction. It’s still possible that another transaction executes concurrently, and, for example: both transactions succeed because their
:check_sender_fundssteps will succeed, but at the end of the second transaction you’ll have some unexpected money missing somewhere.In order to prevent that, you can use locking. If you use PostgreSQL with Ecto, you can customize my code, that wraps code in transaction and lock. You could probably make it work with Ecto.Multi, by making the lock query set up lock as first statement in the transaction:
You can have multiple locks at the same time across the system, I am using “1” as the lock key just for this example, but this can be user ID, tenant ID or some other resource ID (like account ID) that you want to have the lock unique for.
This works in the way that if another transaction opens up that wants to set up the lock on the same resource, it will wait on the lock line until the other transaction finishes.
You can also use the locking mechanisms described above by @al2o3cr depending on what you think is best.