title: Managing concurrency on store checkout process
body: <p>I have been reading all day searching the correct way to manage concurrency within a e-commerce checkout process, and I'm still not sure how to develop it.</p>
  
  <p><strong>Scenario</strong></p>
  
  <p>User selects <em>one</em> product from the store, go to checkout page and pays using his credit card. The site process the payment checking <strong>stock availability</strong> and using a webservice along with the user credit card data and. The webservice finally return the result and the site display a success page (or fail).</p>
  
  <p><strong>Final checkout  and payment validation flow</strong></p>
  
  <ul>
  <li>The user starts the final checkout step</li>
  <li>I check if product has stock</li>
  <li>If product has stock I call the payment webservice</li>
  <li>If webservice result is "OK", I display the success page</li>
  </ul>
  
  <p>It sounds very simple, but my problem is the way I get the stock of the product: I have to calculate it each time. I have two tables <em>product</em> and <em>sales</em> (example only tables), so each time a sale is completed, a <em>sale row</em> is added linking the product it belongs. On <em>product</em> table I have the maximum times that a product can be sold, like a initial stock. </p>
  
  <p>So, for example, I have product <strong>X</strong> with initial stock of 99 and two users starts the checkout process for the last available unit. I check the current sold units = 98. OK, both users can buy it, I call the webservice and finally both users buy and pay the product.</p>
  
  <p>Any idea of how to deal with concurrency in this case?</p>
  
  <p>BTW: I'm usingy MySQL with InnodB</p>