Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

192
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda