MySQL atomic operations and table locking

亡梦爱人 提交于 2019-12-03 13:44:05

You are very close on your design, but not quite there.

First of all, your event table needs to hold the number of tickets still available for your event (in addition to whatever else you want there).

Second, your escrow table needs to have a DATETIME column indicating when the escrow expires. You need to set that value whenever tickets go into escrow.

Third, the transaction of putting tickets in escrow needs to

  1. lock the event row.
  2. read the available tickets column. (abort if not enough are available)
  3. insert a row in the escrow table
  4. update the event row to decrement the available tickets column.
  5. unlock the event row.

Fourth, the action of completing the sale needs to delete the escrow row and insert a sold-ticket row. This isn't hard.

Fifth, you need an escrow cleanup operation. This needs to look for all escrow rows that have expired (that have an expiration date in the past) and, for each one:

  1. lock the corresponding event row.
  2. read the number of escrowed tickets from the escrow table
  3. delete the escrow table row.
  4. update the event row to increment the available tickets column.
  5. unlock the event row.

The trick is to have the number of available tickets maintained in a way that is interlocked correctly, so race conditions between users don't oversell your event.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!