Full answer
text
coupons(id, code UNIQUE, discount, valid_from, valid_to, max_redemptions, redeemed_count DEFAULT 0)
coupon_redemptions(coupon_id, customer_id, order_id, redeemed_at,
PRIMARY KEY (coupon_id, customer_id))Redemption transaction:
INSERT INTO coupon_redemptions ...fails with a unique violation if the customer already used it.UPDATE coupons SET redeemed_count = redeemed_count + 1 WHERE id = :c AND redeemed_count < max_redemptions AND now() BETWEEN valid_from AND valid_to;- If step 2 changed zero rows, roll back: the coupon is exhausted or expired.
The conditional update makes the limit safe under concurrency, because the row lock serialises competing increments and each re-checks the condition. Counting redemptions with SELECT COUNT(*) and then inserting would let the 101st customer through. If an order is cancelled, delete the redemption and decrement the counter in one transaction, according to the business rule.
Key points
- Unique key for once per customer
- Conditional increment for the global limit
- Both in one transaction
- Count-then-insert races
Common mistakes
- Checking the limit with COUNT(*) before inserting
- Case-sensitive code lookups that confuse users
Follow-ups
- How would you generate a million unique single-use codes?
- How would you restore a redemption on refund?
Tips
- Show why the conditional update is safe