开发者

How to design a concurrent discount engine?

I was wondering if anyone could share any best practices around the design of a concurrent user e-commerce discount engine.

In my system, users can be allocated purchase credits that allow them to purchase things for free. So, for example, the user will select a basket of products that is passed to a discount engine where rules will be applied based on the credits assigned to the user's account. Say the user has 5 credits, how do I ensure that, a credit can be used once and only once? Will I need to introduce some form of database locking? Would I store a count of credits in a single table or maybe create distinct records to model each credit?

I suppose this is analogous to a ticket booking system where it is imperative that a single ticket can't be sold to mor开发者_StackOverflow社区e than one customer at a time. It seems to be about ensuring that, even in a highly concurrent environment, no purchase credit can be used twice.

Hopefully I'm making at least a little bit of sense!


Just us an SQL database that doesn't suck at transactions, stick the operation of using up a credit into a single transaction (possibly by having the DB constrain the number of credits to being non-negative or something) and it should not be possible for two concurrent transactions to use the same credit. Databases are REALLY good at that sort of thing, it's exactly what they are for.

Basically just shove everything shared in a database and wrap operations that go together in a transaction and your front end code can just pretend there's no concurrency at all. Which is of course the entire reason RDBMS's exist after all.

EDIT: Your schema won't affect the correctness of this approach (although where you begin/end transactions will), it will affect your performance, as will how the DB is implemented. I'm only bringing this up because you tagged the question with 'database-schema' and don't seem to be aware that an ACID DB will just make what you want happen if you write your queries correctly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜