title: PostgreSQL row read lock
body: <p>Let’s say I have a table called Withdrawals (id, amount, user_id, status).</p>
  
  <p>Whenever I a withdrawal is initiated this is the flow:</p>
  
  <ul>
  <li>Verify if user has sufficient balance (which is calculated as sum of amount received - sum of withdrawals amount)</li>
  <li>Insert row with amount, user_id and status=‘pending’</li>
  <li>Call 3rd party software through gRPC to initiate a withdrawal (actually send money), wait for a response</li>
  <li>Update row with status = ‘completed’ as soon we a positive response or delete the entry if the withdrawal failed.</li>
  </ul>
  
  <p>However, I have a concurrency problem in this flow.
  Let’s say the user makes 2 full balance withdrawal requests within ~50 ms difference:</p>
  
  <p>Request 1   </p>
  
  <ul>
  <li>User has enough balance</li>
  <li>Create Withdrawal (balance = 0)</li>
  <li>Update withdrawal status</li>
  </ul>
  
  <p>Request 2 (after ~50ms)</p>
  
  <ul>
  <li>User has enough balance (which is not true, the other insert didn’t got stored yet)</li>
  <li>Create Withdrawal (balance = negative )</li>
  <li>Update withdrawal status</li>
  </ul>
  
  <p>Right now, we are using redis to lock withdrawals to specific user if they are within x ms, to avoid this situation, however this is not the most robust solution. As we are developing an API for businesses right now, with our current solution, we would be blocking possible withdrawals that could be requested at the same time.
  Is there any way to lock and make sure consequent insert queries wait based on the user_id of the Withdrawals table ?</p>