Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

191
Visualizações
SQL banking race condition

I am building a banking system in NodeJS and an SQL database. The two main functionalities I need are deposit and withdraw. I want to make sure that there are no race conditions.

Ex: User has 100$ balance and withdraws 100$ twice quickly and ends up with -100$.

Can the following query have race conditions?

update account set balance = balance - x where balance > x

If this does not solve the problem:

If I use PostgreSQL, will a check constraint on my balance column suffice to eliminate all race conditions?

If I use MySQL, what are my options?

I am curious on what are the different ways to achieve this in both PostgreSQL and MySQL

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

So, you can do the following:

  • Set autocommit to false inside withdraw() function, i.e. start a new transaction.
  • Use SELECT .. FOR UPDATE to read the record
  • Perform checks on value (i.e. whether amount is sufficient enough to perform the operation)
  • UPDATE the value
  • End the transaction

Now, when user tries to withdraw twice quickly, one of the call will start the transaction and issue SELECT.. FOR UPDATE call, that will block the other thread from reading the data. It will be only unblocked once first thread will finishes, i.e. it will prevent race condition.

Here's MySQL's documentation about it.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda