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

294
Visualizações
Django reproduce concurrency example with select_for_update()

I'm reading over this article on handling concurrency in django

The post talk about the following example:

  • User A fetches the account — balance is 100$.
  • User B fetches the account — balance is 100$.
  • User B withdraws 30$ — balance is updated to 100$ — 30$ = 70$.
  • User A deposits 50$ — balance is updated to 100$ + 50$ = 150$.

I tried to reproduce with a UserBalance model with balance column that use IntegerField(), as the article said i need to use select_for_update() to avoid this issue

def test_con(id):
    with transaction.atomic():
        user_balance = UserBalance.objects.select_for_update().get(pk=int(id))
        sleep(60)
        user_balance.balance -= 30
        user_balance.save()

So this transaction is lock for 60 seconds

In the first shell i go into manage.py shell to call it

In another shell after i execute test_con(5) i ran the following :

>>> user_balance = UserBalance.objects.get(pk=5)
>>> user_balance.balance += 50
>>> user_balance.save()
>>> print(str(user_balance.balance))

the second shell wait till the first shell test_con(5) transaction is completed(as expected) and return the balance but it return 150 ? shouldn't it be 120 ?

I'm confused about why this locking mechanic doesn't work

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

0

After testing some more, thank to @CharanjitSingh for the suggestion of using F expression.

I decided to use it within my transaction, also create another function to reproduce a transaction happen at the same time (instead of using second shell and run pure ORM update):

def test_con(id):
    with transaction.atomic():
        user_balance = UserBalance.objects.select_for_update().get(pk=int(id))
        sleep(20)
        user_balance.balance = F('balance') - 30
        user_balance.save()

def run_con(id):
    with transaction.atomic():
        user_balance = UserBalance.objects.select_for_update().get(pk=int(id))
        user_balance.balance = F('balance') + 50
        user_balance.save()

I ran test_con(5) first and then run_con(5) on second shell, after 20 seconds i check my database and the calculation is now correct and it return 120 :)

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