Coupon System Design: Single-Use Codes, Stacking Rules and Abuse
Saket Bhatnagar, Founder, SevyDevy, Last updated , 19 min read
Summary
- Coupon system design means building the service that creates discount codes, checks them at checkout and makes sure each one is used only as often as allowed.
- Codes must be unguessable. Build them from a cryptographically secure random source, which is a generator made for secrets. Store them under a unique constraint, a database rule that rejects duplicates.
- The classic bug is check-then-act: two requests both read "unused" before either writes "used". Fix it with one conditional database update that checks and changes the row together.
- Stacking rules decide which coupons can combine and in what order. Order changes the bill: 10 percent plus Rs 200 off a Rs 2,000 cart gives Rs 1,600 or Rs 1,620.
- Beginners can stop after the section on enforcing single-use coupons. Engineers get measured races on PostgreSQL 16 and Redis 7, including a counter that read 1 after 150 redemptions, plus reserve-then-confirm and anti-farming controls.
What goes wrong when a coupon system is built the obvious way?
In coupon system design, the obvious build reads the coupon, checks it is unused, then marks it used. Under real traffic, many requests read "unused" at the same moment, so one code gets spent many times.
Picture a common setup. An Indian shopping app runs a Diwali sale with a public code, DIWALI100, capped at 100 uses, and gives 10 lakh (1 million) single-use codes to a partner bank. The setup is made up, but every failure below is one we reproduced on real databases. On launch night three things break at once.
- Shoppers on two phones apply the same single-use code within a few milliseconds, and both orders get the discount.
- The 100-use cap is passed, because each request read the old count before adding one.
- A script tries random codes until one works, and one person signs up many times to claim the welcome offer again.
This guide fixes all three on one running example. It covers code generation, single-use and limited-use enforcement under concurrency, stacking rules and abuse controls.
Which words do you need before designing a coupon system?
You need about eight terms. Each one names a rule the system must enforce or a record it must keep.
| Term | Plain meaning | In the Diwali example |
|---|---|---|
| Campaign | The offer itself: discount, dates, limits and who may use it | The Diwali sale, valid for five days |
| Code | The string a shopper types or a link applies | DIWALI100, or a bank code like TPRSB3RZY4 |
| Single-use code | A code that may be redeemed once in total | Each of the 10 lakh bank codes |
| Limited-use code | A shared code with a total cap | DIWALI100, capped at 100 uses |
| Per-user limit | How many times one customer may use a campaign | Once per customer |
| Redemption | One recorded use of a code on one order | A row saying order 881 used DIWALI100 |
| Stacking | Using more than one coupon on one order | A store coupon plus a bank coupon |
| Coupon farming | Collecting offers meant for one person by faking many people | Fifty sign-ups that all claim the welcome code |
What is coupon system design?
Coupon system design is planning how a business creates, validates, redeems and protects discount codes at scale. It is less about storing codes and more about enforcing rules when thousands of requests arrive together.
A payment system moves money. A coupon system is a promotion state machine: a set of states a code moves through, with rules for each move. It also has its own fraud, from guessed codes to fake accounts. For the money side, see the SevyDevy guide on payment system design.
Parts of a coupon system
Drag to exploreNotice that every redemption goes through one coupon service, and only the database decides whether a use is granted.
Diagram connections:
- Campaign admin to Coupon service (create campaign)
- Shopping app to Rate limit and abuse checks (apply code)
- Rate limit and abuse checks to Coupon service (allowed requests)
- Coupon service to Redis (quick pre-check)
- Coupon service to PostgreSQL (conditional update)
- Payment service to Coupon service (paid or failed)
- Expiry sweeper to PostgreSQL (release expired holds)
- Campaign admin: Creates campaigns, limits and code batches
- Shopping app: Shopper applies a code at checkout
- Rate limit and abuse checks: Slows guessing and repeat sign-ups
- Coupon service: Validates, prices and reserves a use
- PostgreSQL: Coupons and redemptions; source of truth
- Redis: Optional fast gate for hot public codes
- Payment service: Says whether the order was paid
- Expiry sweeper: Releases holds whose time ran out
How do you generate coupon codes that nobody can guess?
Pick each character with a cryptographically secure random generator and make codes long enough that guessing is hopeless. Python's secrets module exists for this, and its docs say to prefer it over the random module.
The random module is built for modelling and simulation. Its docs warn it must not be used for security. Coupon codes are money, so treat them like passwords.
import math
import secrets
# 31 characters: no 0, O, 1, I or L, so codes are easy to read aloud
ALPHABET = "23456789ABCDEFGHJKMNPQRSTUVWXYZ"
def new_code(length=10):
return "".join(secrets.choice(ALPHABET) for _ in range(length))
space = len(ALPHABET) ** 10
live_codes = 1_000_000
print("sample code:", new_code())
print(f"possible codes: {space:,} (about {math.log2(space):.1f} bits)")
print(f"random guesses per lucky hit: {space // live_codes:,}")Run it and you get a code like TQXVAJ6TDC and about 819 lakh crore (819 trillion) possible codes. With 10 lakh codes live, a random guess hits one about once in 82 crore (820 million) tries.
The alphabet drops 0, O, 1, I and L. Shoppers read codes off posters and type them on phones, and those characters get mixed up.
Collisions and the unique constraint
Random codes can repeat, so store them in a column with a unique constraint and retry on conflict. We inserted 2 lakh (200,000) generated codes with ON CONFLICT DO NOTHING, which skips a row whose code already exists, and saw no collisions. The constraint is still the guarantee; the maths only says retries are rare.
Length alone does not stop guessing. OWASP lists coupon guessing as an automated threat named Token Cracking, OAT-002. Rate limits on the apply endpoint, covered later, do the rest.
Why does check-then-redeem let one coupon be used twice?
Because reading and writing are two separate steps. Between them, other requests read the same old value and all decide the code is free.
The naive version, labelled naive: read the coupon's status, and if it says active, update it to redeemed. Each line looks correct on its own.
| Approach | Setup | Result |
|---|---|---|
| Naive read then update, PostgreSQL | 10 parallel requests, 30 trials, no delay | All 30 trials had more than one winner; the worst had 10 |
| Naive read then update, PostgreSQL | 50 requests, 50 ms gap between check and write | 50 winners for one single-use code |
| Same naive code plus a CHECK constraint (used may never exceed max_uses) | 50 requests, 50 ms gap | 1 winner; 49 got a constraint error instead |
| Naive counter: read uses, write uses plus 1 | 150 shoppers, cap of 100 | 150 redemptions; the counter read 1 |
| Conditional update, read committed | 50 requests | 1 winner, 49 clean rejections |
| Naive GET then SET, Redis | 50 requests, nine runs | More than one winner in 11 of 12 runs, up to all 50 |
What just happened? Each winner read "active" before the first write committed. The counter row is worse: each request wrote its own stale count plus one, so 150 writes left it at 1. This is called a lost update.
Here is the everyday picture. One item sits on a shop shelf. Two shoppers glance at it (the read), walk to the till (the gap) and both expect to buy it (the write).
The fix is to grab the item itself in one move, so the second hand finds an empty shelf. Where the picture breaks: the database does not let two hands collide. It makes the second request wait, then look again.
How do you enforce single-use coupons under concurrency?
Put the check inside the write. One UPDATE whose WHERE clause, the condition part of the statement, says "only if a use is left" both checks and changes the row, and the database decides the race.
This works because of how PostgreSQL's default isolation level behaves. Isolation level means how much one transaction sees of others running at the same time. The default is read committed.
The PostgreSQL 16 docs describe it. When an UPDATE finds a row another transaction is changing, it waits for that transaction to finish. It then re-checks the WHERE clause against the new version of the row.
A single-use code has max_uses of 1. So the second request sees uses_left at zero and updates nothing. Here is the schema for the running example.
CREATE TABLE coupons (
code text PRIMARY KEY,
valid_from timestamptz NOT NULL,
valid_until timestamptz NOT NULL,
max_uses int NOT NULL,
uses_left int NOT NULL,
CHECK (uses_left BETWEEN 0 AND max_uses)
);
CREATE TABLE redemptions (
order_id text PRIMARY KEY,
code text NOT NULL REFERENCES coupons (code),
user_key text NOT NULL,
state text NOT NULL CHECK (state IN ('reserved', 'redeemed', 'released')),
hold_until timestamptz NOT NULL
);
-- one live use per user per code; released rows do not count
CREATE UNIQUE INDEX one_live_use_per_user
ON redemptions (code, user_key)
WHERE state IN ('reserved', 'redeemed');And here is the redemption, two statements in one transaction. A transaction is a group of statements that succeed or fail together. The dollar placeholders are query parameters, so user input never becomes SQL text.
-- $1 = code, $2 = order id, $3 = user key. Run both in ONE transaction.
-- 1. Take one use, only if the code is live and a use is left
UPDATE coupons
SET uses_left = uses_left - 1
WHERE code = $1
AND uses_left != 0
AND now() BETWEEN valid_from AND valid_until
RETURNING uses_left;
-- no row back: reject ("expired or used up") and roll back
-- 2. Record the use; the unique index blocks a second live use
INSERT INTO redemptions (order_id, code, user_key, state, hold_until)
VALUES ($2, $1, $3, 'reserved', now() + interval '15 minutes')
ON CONFLICT DO NOTHING
RETURNING order_id;
-- no row back: roll back, so step 1's use is given backTo check it worked, count outcomes and rows after a race. We ran 150 shoppers against 100 uses three times. Every run gave exactly 100 successes, 50 rejections, uses_left of 0 and 100 redemption rows.
One use per customer and safe retries
The partial unique index enforces one live use per customer. A partial index covers only rows that match its WHERE condition, here reserved or redeemed. Released rows stop counting, so a failed order frees the customer to try again.
We fired 20 parallel orders from one customer. One succeeded, 19 were rejected, and the rejected ones rolled back, so uses_left showed 4 of 5. The same order ID retried 20 times also gave one success.
When the insert returns no row, look up the order ID. If that order already has a redemption, this is a retry, so return the earlier result. If not, the customer has already used the offer. This is the idempotency idea: a repeated request gets the first answer instead of acting twice.
Two other ways that also work
Repeatable read, a stricter isolation level, also blocked the naive code. 49 of 50 requests failed with "could not serialize access due to concurrent update". The docs say you must then retry the whole transaction.
SELECT FOR UPDATE, which locks the row while you read it, is the third option. The conditional update is usually simplest. It needs no retry loop, unlike repeatable read, and no separate locking read.
For engineers
Beginners can stop here. You now know how to make unguessable codes and how to enforce one use safely. The rest is for engineers: reserve-then-confirm, Redis, stacking code and abuse controls.
Should a coupon be redeemed at checkout or after payment?
Reserve it at checkout and confirm it after payment. Redeeming at checkout wastes the code when payment fails, and waiting for payment lets two orders use one code in the meantime.
A reservation is a hold with a deadline, the hold_until column. If payment succeeds, the row moves to redeemed. If the hold expires, a sweeper job moves it to released and gives the use back.
The redemption state machine
Drag to exploreNotice that both exits from reserved are conditional updates, so the payment confirm and the sweeper can never both win.
Diagram connections:
- Code applied at checkout to Reserved (reserve)
- Reserved to Paid before hold ends? (wait)
- Paid before hold ends? to Redeemed (Yes: confirm wins)
- Paid before hold ends? to Released (No: sweeper wins)
- Code applied at checkout: Take one use and insert a reserved row
- Reserved: Hold for 15 minutes while the shopper pays
- Paid before hold ends?: Payment result vs expiry sweeper
- Redeemed: Final; counts toward every limit
- Released: Use given back; user may try again
Each exit is the same pattern as before: UPDATE redemptions SET state to redeemed WHERE order_id matches AND state is still reserved. The sweeper's update also checks the hold time has passed, then adds one back to uses_left.
We raced a payment confirm against the sweeper 200 times on one expired hold. In one run the confirm won 106 times and the sweeper 94; the split changes between runs. Never both, and uses_left always matched the final state.
The confirm can lose. Then the shopper has paid but the hold is gone, so the order needs a rule. Re-reserve if a use is left. Otherwise either honour the discount and log the extra use, or cancel and refund the order.
Can Redis 7.0 enforce single-use coupons on its own?
It can stop double use at that moment, if each check and change happens in one Redis command or one Lua script. But by default Redis is a weaker record than PostgreSQL, so it should not be the only record.
For a single-use code, SET with the NX option writes a key only if it does not exist. The key can hold the ID of the order that claimed the code. In our runs, 50 parallel requests produced exactly one success every time. A naive GET then SET gave 2 to 49 winners.
For a capped code with a per-user limit, use a Lua script, a small program Redis runs inside the server. It does several steps atomically, meaning nothing else runs in between. The Redis docs say all server activity is blocked while a script runs, so its effects happen all at once or not yet.
import redis
r = redis.Redis(port=6379, decode_responses=True)
# KEYS[1] = uses-left counter, KEYS[2] = set of user keys, ARGV[1] = this user
TAKE_ONE = """
if redis.call('SISMEMBER', KEYS[2], ARGV[1]) == 1 then return -1 end
local left = tonumber(redis.call('GET', KEYS[1]) or '0')
if left == 0 then return 0 end
redis.call('DECR', KEYS[1])
redis.call('SADD', KEYS[2], ARGV[1])
return 1
"""
take_one = r.register_script(TAKE_ONE)
r.set("coupon:DIWALI100:left", 100)
result = take_one(keys=["coupon:DIWALI100:left", "coupon:DIWALI100:users"], args=["user-42"])
print({1: "taken", 0: "used up", -1: "already used by this user"}[result])It prints "taken" the first time and "already used by this user" for the same user. In five races of 150 requests from 120 users against 100 uses, we always got 100 taken and a counter of exactly 0.
The DECR trap and the durability gap
A common shortcut is DECR, which subtracts one and returns the new value, then add one back if the result went negative. Our final counts were right, but the live counter went below zero in every run, once to minus 33. Anything showing "uses left" would have displayed nonsense.
Durability is the bigger issue. Redis 7.0.15 started with no config file uses periodic snapshots only, and its docs say snapshots can lose the latest minutes of writes. With the append-only file on, a log of every write, the default is to force it to disk once a second. That can still lose about a second.
Lost writes here can mean coupons granted twice. So a safer design uses Redis as a fast first gate, then still records the redemption in the database with the conditional update. If the database says no, give the Redis use back, and rebuild Redis counts from the database after a restart.
How do coupon stacking rules work?
Stacking rules say which coupons may combine on one order and in what order they apply. Good rules are data on each coupon, checked by one function, not if-statements scattered around checkout.
- Groups: at most one coupon per group, such as one store coupon and one bank coupon.
- Exclusive flag: an exclusive coupon cannot combine with anything.
- Fixed order: for example percentages first, then flat amounts.
- Caps and floors: a percentage may have a maximum discount, and the total never goes below zero.
- Money in paise: whole numbers avoid floating-point rounding errors.
def apply_coupons(cart_paise, coupons):
"""coupons: dicts with code, kind, value, group, exclusive, cap (paise or None)."""
if len(coupons) != 1 and any(c["exclusive"] for c in coupons):
raise ValueError("an exclusive coupon cannot be combined")
groups = [c["group"] for c in coupons]
if len(groups) != len(set(groups)):
raise ValueError("only one coupon per group")
total, lines = cart_paise, []
# fixed order: percentage coupons first, then flat ones
for c in sorted(coupons, key=lambda c: c["kind"] != "percent"):
if c["kind"] == "percent":
off = total * c["value"] // 100 # whole paise, rounded down
else:
off = c["value"]
if c["cap"] is not None:
off = min(off, c["cap"])
off = min(off, total) # never below zero
total -= off
lines.append((c["code"], off))
return total, lines
save10 = {"code": "SAVE10", "kind": "percent", "value": 10, "group": "store",
"exclusive": False, "cap": None}
bank200 = {"code": "BANK200", "kind": "flat", "value": 20_000, "group": "bank",
"exclusive": False, "cap": None}
total, lines = apply_coupons(200_000, [bank200, save10]) # Rs 2,000 cart
print(lines, "pay", total / 100)It prints SAVE10 and BANK200 at 20,000 paise each and a payable amount of 1600.0 rupees. The function sorts the coupons, so the result does not depend on the order the shopper applied them.
| Rule | Discount lines | Shopper pays |
|---|---|---|
| Percentage first | Rs 200 then Rs 200 | Rs 1,600 |
| Flat first | Rs 200 then Rs 180 | Rs 1,620 |
| Percentage first, 10 percent capped at Rs 150 | Rs 150 then Rs 200 | Rs 1,650 |
| Bank coupon needs Rs 1,900 cart, percentage first | Rejected: cart is Rs 1,800 when checked | No bank discount |
| Two coupons from the same group | Rejected | Only one applies |
The Rs 20 gap looks small, but over a big sale it becomes real money. Write the order into the campaign rules, show it in the cart and test it. Decide too whether a minimum cart value is checked before or after earlier discounts.
How do you stop coupon farming and code guessing?
Tie each offer to something costly to fake, and slow down anyone who tries many codes. No single signal is enough, so layer cheap checks before strict ones.
| Abuse | What it looks like | Controls |
|---|---|---|
| Code guessing | Many failed applies from one account, device or network | Long random codes, rate limits per account and IP, the same error for unknown and used-up codes |
| Multi-account farming | Many new accounts claiming a welcome offer | Limit per verified phone, normalised email and payment instrument |
| Code leaks | A private code suddenly used by strangers | Bind codes to a user or segment; alert on unusual use rates |
| Refund cycling | Order with a coupon, cancel, repeat | Count cancelled redemptions toward limits for a cool-off period |
Normalise identities before counting
Count per-user limits on a normalised key, not the raw email. Google's Gmail help says dots do not matter in personal Gmail addresses. RFC 5233 describes subaddressing, where mail to a name plus a tag can reach that name's mailbox. Support varies by provider.
So we lower-cased emails, dropped any plus tag and removed dots for gmail.com only. Then we hashed the result with a server-side secret, so the abuse table never stores raw emails. Three spellings of one personal Gmail address gave one key; two different example.in addresses stayed apart.
Do not strip dots for other domains. Gmail's help page says dots do change work and school addresses. Dropping plus tags can also merge two real people on a provider that allows plus in names, so treat the key as a signal, not proof.
Rate limits and honest errors
Rate-limit the apply endpoint per account, device and IP address. Consider one message for unknown and used-up codes, so a script cannot learn which codes exist. The SevyDevy rate limiter guide covers the token bucket method.
OWASP lists mass account sign-up as Account Creation, OAT-019. A dedicated bot detection layer helps when farming is organised.
In the interview
How do you explain coupon system design in a system design interview?
Lead with the rules and the race, then the data model, then abuse. Interviewers want to hear where the guarantee lives, not a list of boxes.
Clarify the offers
Ask about single-use, limited-use and per-user limits, stacking, expiry and expected peak, such as a sale opening at midnight.
Define the data
Coupons with uses left and validity dates; redemptions keyed by order ID with a state and a hold time.
Show the race
Explain check-then-act and the lost update, then fix it with a conditional update plus unique indexes.
Reserve, then confirm
Hold a use at checkout, confirm after payment, and let a sweeper release expired holds with a conditional update.
Scale the hot code
A single popular code is one hot row, and every redemption waits its turn on it. Add a Redis gate with a Lua script, keeping the database as the record.
Price with rules
Apply stacking rules from data: groups, exclusive flags, fixed order, caps, and money in paise.
Defend it
Secure random codes, rate limits, identical error messages, normalised identity keys and alerts on unusual use.
Questions people ask
How do you make a coupon code single-use?
Make the database check and change the coupon in one statement. An UPDATE with a WHERE clause such as uses_left != 0 only succeeds while a use is left. In PostgreSQL's default read committed level, a second request waits and then re-checks that condition, so only one wins. Add a unique index on redemptions as a second guard.
Are random coupon codes safe from guessing?
Only if they come from a secure random source and are long enough. A 10-character code from a 31-character alphabet has about 819 trillion possibilities, so random guesses rarely hit. Still rate-limit the apply endpoint and return the same error for unknown and used-up codes. OWASP lists coupon guessing as an automated threat, OAT-002.
Is Redis enough to stop double redemption?
Redis can stop double redemption at that moment if you use SET with NX or a Lua script. The risk is durability: with snapshots only, a crash can lose minutes of writes, and even the append-only file, at its default setting, can lose about a second. A safer design uses Redis as a fast first check and still records each redemption in a database with a conditional update.
Should a coupon be marked used before or after payment?
Reserve it before payment and confirm it after. The reservation holds one use for a short time, such as 15 minutes. Payment success moves it to redeemed; expiry moves it to released and returns the use. Both moves are conditional updates, so they cannot both happen.
Does the order of stacked coupons change the price?
Yes, when percentage and flat discounts combine. On a Rs 2,000 cart, 10 percent then Rs 200 off gives Rs 1,600. Rs 200 off then 10 percent gives Rs 1,620. Pick one order, store it as a campaign rule, show it in the cart and test it.
How do you stop people from making many accounts to reuse a welcome coupon?
Limit the offer per thing that is costly to fake, such as a verified phone number or payment instrument, not per account. Normalise emails before counting, for example by removing dots in personal Gmail addresses. Watch for bursts of new sign-ups that claim the same offer, and add bot checks at sign-up.
Keep learning
Practise it with Lala
A question on this guide, hints and a review.
Read next
Sources (12)
- PostgreSQL 16 docs: Transaction Isolation (read committed re-check, repeatable read errors)
- PostgreSQL 16 docs: INSERT and ON CONFLICT
- PostgreSQL 16 docs: Partial Indexes (partial unique index)
- Redis docs: SET command (NX option)
- Redis docs: Scripting with Lua (atomic execution)
- Redis docs: Persistence (RDB and AOF data loss)
- Python docs: secrets module
- Python docs: random module security warning
- OWASP Automated Threats: OAT-002 Token Cracking
- OWASP Automated Threats: OAT-019 Account Creation
- Gmail Help: Dots don't matter in Gmail addresses
- RFC 5233: Sieve Email Filtering, Subaddress Extension