Coupon Management System
Coupon validation kai rules ka chain hai: validity window, minimum order value, user eligibility, product/category applicability, per-user usage limit, aur GLOBAL redemption limit. Har rule ek alag check hai — inhe rule chain banao taaki naya rule add karna aasaan rahe.
Asli distributed problem hai GLOBAL LIMIT. "Pehle 1000 users" waale coupon par 5000 log ek saath aa sakte hain. DB counter par race condition ban jaayegi, isliye Redis mein atomic INCR use karo aur limit cross hone par reject. Per-user limit ke liye Redis SET mein userId rakho.
-- Redis: atomic redemption claim
local used = redis.call('INCR', 'coupon:' .. KEYS[1] .. ':count')
if used > tonumber(ARGV[1]) then
redis.call('DECR', 'coupon:' .. KEYS[1] .. ':count')
return 0 -- quota khatam
end
return 1 -- claim mil gaya- Validation ek rule chain hai — window, min value, eligibility, limits
- Global limit ke liye Redis atomic INCR, DB counter nahi
- Reserve with TTL → order confirm par redeem
Do tarah ke coupons hote hain. STATIC code (SALE50) — sab use karte hain, generation trivial hai, validation par limits lagti hain. UNIQUE codes (har user ka apna) — pre-generate karke store karne padte hain.
Crore unique codes generate karne ke liye random generate karke duplicate check karna slow hai. Behtar hai counter ko encode karna (base32) plus ek checksum character — isse codes unique bhi rehte hain aur typo turant pakda jaata hai bina DB hit kiye.
// Counter-based, collision-free
code = base32(counter) + checksum(base32(counter))
// "7KFQ2M9" — checksum galat to DB dekhe bina hi rejectCoupon systems attack hote hain — log multiple accounts banakar first-order discount baar-baar lete hain. Isliye eligibility sirf userId par nahi, device fingerprint, payment method aur address par bhi check honi chahiye.
Aur code enumeration se bachao: agar codes guessable hain to bot hazaaron try karega. Rate limiting per IP aur per account zaroori hai, aur codes mein enough entropy honi chahiye.