mongodb - Given a list of unique discount codes, how to send each one only once -
i'm wondering best way solve problem: given pre-generated list of 500 unique discount codes e-commerce site, how ensure each of first 500 users receive discount code each receive unique one? e-commerce site making asynchronous request separate server list of discount codes stored in database. it's server's job make sure sends each discount code once, in chronological order requests received.
as seems rather primitive problem, wonder if there clever , elegant way relatively low level of effort.
if db has atomic transactions, no problem. make table discount
2 fields, code
(varchar wide enough hold code) , used
(boolean), indexed used
, code
. insert
500 rows, each used = false
of course. whenever request comes, select min(code) discount update not used
, , update discount set used = true not used , code = <that code>
, inside single db transaction. (the not used
part of update not necessary correctness, may speed things enabling index used.)
if contention problem (and don't see how 500 requests, maybe somehow be), add integer id
field containing unique integer between 1 , 500 table. on each request, pick random number r
between 1 , 500, , select min(code) discount update not used , (id >= <r> or id + 500 >= <r>)
. condition in parentheses ensures search "wrap around" lower-numbered discounts if (and if) discounts >= r
have been taken.
Comments
Post a Comment