“Design a coupon service” sounds like a CRUD table with a discount_percent column until you write down what actually breaks it. Marketing wants to print 10 million unique codes for a Diwali campaign, mail them out, and have each one usable exactly once. The rules are not simple: this code is 20% off, that one is flat 500 off orders over 2000, this batch is one-per-customer across the customer’s lifetime, that batch stacks with free shipping but not with other percentage coupons. And the whole thing has to answer POST /checkout in a few milliseconds during a flash sale when 200,000 people hit “apply code” in the same minute, because the coupon check sits directly on the critical path to revenue.

The interviewer is not testing whether you can store a discount. They are testing whether you can mint millions of unique single-use codes without collisions, validate a stack of business rules fast, and guarantee that a code redeems exactly once per the rules - even when the same customer double-taps checkout on three devices during a stampede - without adding latency to the one request that pays the bills. That last clause is the whole game. Correctness here is money: a code that redeems twice is margin you gave away for free; a lock that stalls is a cart you abandoned.

This overlaps with a flash-sale design, but the shape is different. A flash sale is one shared counter decremented 6M times - fungible inventory, one hot number. A coupon service is the opposite: millions of distinct keys, each with its own single-use state and its own rules, plus a per-customer usage ledger layered on top. The hard part is not one hot counter; it is unique-key generation at scale and per-key atomic redemption under contention. Let me build it the way I would in an interview: naive first, break it, evolve.

Functional Requirements (FR)

In scope:

  • Create a campaign. Marketing defines a promotion: discount type (percentage, flat amount, free shipping, BOGO), value, validity window, eligibility rules (min cart value, specific SKUs/categories, first-order-only, customer segment), redemption limits (total budget cap, per-customer cap), and stacking policy.
  • Issue codes. Two modes. Bulk unique codes: mint N unique single-use codes (e.g. 10M codes like DIWALI-7K2M-9QX4) tied to a campaign, to be distributed individually. Shared code: one public code (e.g. WELCOME20) that many customers use, each subject to per-customer and global limits.
  • Validate a code. Given (code, customer_id, cart), return whether it applies and the computed discount, or a precise rejection reason (expired, min-cart-not-met, already-used, not-eligible, budget-exhausted).
  • Redeem a code. At checkout, atomically mark the code consumed for this order, enforce single-use and one-per-customer, and apply the discount. Must be idempotent - a retried checkout for the same order must not double-consume.
  • Release/rollback. If the order fails after redemption (payment declined, cancellation), the code’s consumption is reversed so the customer can try again.
  • Reporting. How much budget a campaign has burned, redemption rate, remaining codes.

Explicitly out of scope (say it so you own the scope):

  • Pricing/tax engine. The coupon service returns a discount amount or rule; the cart/pricing service applies it to the final total. We do not re-implement tax math.
  • Payment processing. We interact with it (redeem on payment success, release on failure) but do not design the gateway.
  • Fraud/ML abuse detection. We do basic velocity limits and one-per-customer, and mention bot defense, but a full fraud model is its own system.
  • The campaign authoring UI. We design the API and engine, not the marketing console.

The single decision that drives the hardest part: when is a code “consumed” - at validate time, at redeem time, or somewhere in between? Consume too early and abandoned carts leak codes; consume too late and you oversell. The answer is a reservation with a TTL plus an idempotent commit, which I will build up to.

Non-Functional Requirements (NFR)

  • Scale: a large e-commerce platform. ~50M customers, ~2M orders/day steady state, with flash sales pushing 200k+ checkout attempts/minute and “apply code” traffic several times that (people try codes they do not have). Campaigns can hold 10M+ unique codes each.
  • Latency: validation and redemption sit on the checkout path. p99 under 20ms for validate, p99 under 50ms for redeem (it does a durable write). A slow coupon check directly lowers conversion, so this is a hard budget, not a nice-to-have.
  • Availability: 99.99% for validate/redeem. If the coupon service is down, checkout should degrade gracefully - either proceed without the discount (configurable) or fail the discount only, never block the whole order unless policy demands it.
  • Consistency: strong for the single-use and one-per-customer guarantees. Issuing one extra free unit per double-redeem is a real financial loss, so redemption is a linearizable operation on the code’s state. The remaining-count display and reporting can be eventually consistent.
  • Durability: redemption records are financial records. Once we tell the customer “applied” and charge them the discounted price, that redemption must survive crashes. No lost or phantom redemptions.
  • Idempotency: retries are guaranteed (mobile networks, payment retries, load-balancer re-dispatch). Every mutating call carries an idempotency key and is safe to replay.

Back-of-the-Envelope Estimation (BoE)

Grounding the design in numbers so the storage and QPS decisions are not guesses.

Traffic:

Customers                 ~50M
Orders/day (steady)       ~2M       -> ~23 orders/sec average
Peak order rate (sale)    ~200k/min -> ~3,300 orders/sec
Apply-code attempts       ~3x redeems (people try codes that fail)
  steady validate QPS     ~70/sec
  peak validate QPS       ~10,000/sec
Redeem QPS (peak)         ~3,300/sec   (orders that actually use a code)

Read/write split: validate is a read (plus a cheap reservation), redeem is a durable write. Reads dominate - the hot path is “does this code apply,” answered mostly from cache. The durable writes are bounded by the order rate (~3,300/sec peak), which a sharded store handles comfortably.

Storage - codes:

Assume 20 active campaigns, 10M codes each      = 200M codes
Per-code row: code(16B) + campaign_id(8B) +
  status(1B) + customer_id(8B) + order_id(8B) +
  timestamps + flags  ~ 120 bytes
200M codes * 120B                               ~ 24 GB
With indexes (code is PK, +campaign index)      ~ 60 GB

Tens of GB of code data - not huge, but it is 200M+ rows with a strict uniqueness requirement and point-lookup access by code. That shape (huge key space, point reads/writes by key, no cross-row joins on the hot path) points at a sharded KV / wide-column store for the code ledger, with the campaign metadata (a few thousand rows) in a small relational DB.

Storage - redemption ledger (per-customer usage):

Redemptions/year  ~2M/day * 365      ~ 730M rows/year
Per row ~ 80 bytes                   ~ 58 GB/year
Keep hot 1-2 years, archive older    manageable

Cache:

Hot codes in flight during a sale: a campaign's codes
being validated. Cache is keyed by code.
Shared codes (WELCOME20): a handful, extremely hot
  -> cache the campaign rules, counter in Redis.
Unique codes: cache on first touch (read-through),
  TTL a few minutes.
Campaign metadata (rules): tiny, ~thousands of rows,
  cache the entire set in memory on every app node.

The key insight from the numbers: campaign rules are tiny and cacheable everywhere; code state is large but point-access; the only genuinely hot shared number is a shared code’s global counter. That shapes which problems get which tool.

High-Level Design (HLD)

                         ┌───────────────────────────────┐
  Checkout / Cart  ─────▶│         API Gateway           │
  service (caller)       │  (auth, rate limit per user)  │
                         └───────────────┬───────────────┘
                                         │  validate / redeem / release
                         ┌───────────────▼───────────────┐
                         │      Coupon Service (stateless) │
                         │  - rule engine (eval in memory) │
                         │  - idempotency guard            │
                         └───┬───────────┬────────────┬────┘
                             │           │            │
              rules/metadata │   code    │  per-user  │  global counter
              (read-through) │   state   │  usage     │  (shared codes)
                             │           │            │
                   ┌─────────▼──┐ ┌──────▼──────┐ ┌───▼──────────┐
                   │ Campaign DB│ │  Code Store │ │    Redis     │
                   │  (Postgres)│ │  (sharded   │ │ (atomic DECR,│
                   │  + in-proc │ │   KV, by    │ │  reservations│
                   │   cache    │ │   code hash)│ │  TTL, idemp.)│
                   └────────────┘ └──────┬──────┘ └──────────────┘
                                         │
                                  ┌──────▼──────┐
                                  │  Usage DB   │  (per-customer
                                  │  (sharded,  │   redemption ledger,
                                  │  by cust_id)│   unique constraint)
                                  └─────────────┘
                                         │
                      events ──▶ ┌───────▼────────┐ ──▶ reporting /
                                 │ Kafka (async)  │     budget rollups
                                 └────────────────┘     (eventual)

Code generation runs offline as a separate batch pipeline (not on the request path):

Campaign created ──▶ Code Generator (batch job) ──▶ writes 10M codes
                     (Feistel/offset-based,          into Code Store,
                      collision-free by design)       status = ISSUED
                                               ──▶ hands code list to
                                                    distribution (email/CSV)

Request flow - validate (read-heavy, no durable write):

  1. Checkout calls POST /coupons/validate with (code, customer_id, cart).
  2. Coupon service looks up the campaign rules (in-process cache, near-free) and the code state (read-through cache -> Code Store).
  3. It runs the rule engine in memory: window valid? min cart met? eligible SKUs? code status ISSUED (not yet REDEEMED)? per-customer cap not already hit (check Usage DB / cache)? budget remaining (Redis counter for shared codes)?
  4. Returns {applicable: true, discount: {...}} or {applicable: false, reason: "..."}. No state mutated. This is the millisecond path the flash sale hammers, and it is almost entirely cache reads.

Request flow - redeem (durable, atomic, idempotent):

  1. On order placement, checkout calls POST /coupons/redeem with (code, customer_id, order_id, idempotency_key).
  2. Idempotency guard: if this idempotency_key was already processed, return the stored prior result. No double work.
  3. Atomically transition the code ISSUED -> REDEEMED bound to order_id (compare-and-set on the code row), AND insert a per-customer usage row with a unique constraint on (campaign_id, customer_id) if the campaign is one-per-customer, AND decrement the global budget counter.
  4. If all succeed, persist the redemption and return the discount. If any fails (code already redeemed, customer already used it, budget gone), return a precise rejection and mutate nothing.
  5. Emit a redeemed event to Kafka for reporting/budget rollups (async, off the hot path).

Release flow: if the order is later cancelled or payment fails, checkout calls POST /coupons/release with the same order_id; the service flips the code back to ISSUED, deletes the usage row, and increments the counter - itself idempotent.

The separation of validate (cheap, cached, no lock) from redeem (durable, atomic, idempotent) is the backbone. 90%+ of coupon traffic never redeems - it is people checking codes - so you keep that path lock-free and serve it from cache, and you pay the coordination cost only on the ~3,300/sec that actually commit.

Component Deep Dive

Four hard parts: (1) generating millions of unique single-use codes without collisions or a central bottleneck; (2) enforcing single-use + one-per-customer atomically under contention without adding checkout latency; (3) making redemption idempotent so retries during a stampede are safe; (4) handling the hot shared-code counter and budget cap. I will walk each naive-to-correct.

1. Generating Millions of Unique Single-Use Codes

Marketing wants 10M codes, each short enough to type (DIWALI-7K2M-9QX4), each globally unique, none guessable from another, generated fast.

Naive: random generate, check DB for collision, retry

def make_code():
    while True:
        code = random_base32(12)       # e.g. "7K2M9QX4RT3P"
        if not db.exists(code):        # <-- the problem
            db.insert(code)
            return code

Where it breaks:

  • A DB round trip per code, with retries. 10M codes is 10M+ existence checks plus inserts. As the keyspace fills, the birthday problem bites: collisions rise, retries multiply, and the last few percent of codes take disproportionately long. Generation of one campaign can run for hours.
  • The uniqueness check is a race. Two workers can both see “not exists” and both insert. You need a unique index to catch it, and then you are handling duplicate-key exceptions as control flow at scale.
  • Does not parallelize cleanly. Every worker contends on the same table and index for the existence check.

This is the same trap as checking a DB before every insert - it turns an offline batch into a coordination nightmare.

Better: partition the space, generate collision-free, no checks

Make collisions impossible by construction instead of checking for them. Assign each code a unique integer index 0 .. N-1 (trivially unique - it is a counter), then turn that index into an opaque, non-sequential, human-typable string with a reversible, bijective transform. Because the transform is a bijection over the index space, distinct indices always produce distinct codes. Zero lookups.

# 1. Each code gets a dense integer id, globally unique by construction:
#    campaign 42, index i  ->  code_id = (42 << 40) | i

# 2. Scramble the id so codes are NOT sequential/guessable,
#    using a Feistel network (a reversible block cipher on a small domain):
def encode(code_id):
    scrambled = feistel_encrypt(code_id, key=CAMPAIGN_KEY)  # bijection
    body = base32_crockford(scrambled)      # "7K2M9QX4"
    return f"DIWALI-{body[:4]}-{body[4:]}"   # typable, grouped

# Feistel is reversible, so validating a code is O(1) math, no scan:
def decode(code):
    scrambled = base32_decode(strip(code))
    code_id   = feistel_decrypt(scrambled, key=CAMPAIGN_KEY)
    return code_id   # -> campaign_id + index, then point-lookup state

Why this wins:

  • No collisions, ever. Distinct indices map to distinct codes because the transform is a bijection. No existence check, no retry, no unique-constraint fights.
  • Embarrassingly parallel. Split the index range [0, N) across M workers (worker k does i ≡ k mod M); each writes its slice independently. 10M codes is a short batch job, not an hours-long grind.
  • Non-sequential and hard to guess. The Feistel scramble means DIWALI-7K2M-9QX4 and the next index do not produce adjacent codes, so an attacker cannot enumerate code+1. Add a short checksum/HMAC character so most forged codes fail a cheap math check before any DB touch - this alone absorbs a flood of garbage codes during a sale without hitting storage.
  • Validation is math-first. Decode the code to (campaign_id, index) with arithmetic, verify the checksum, and only then do a single point-lookup for its state. Invalid codes are rejected without touching the Code Store.

The alternative for truly random codes (where you do not want even an encrypted ordering) is to generate from a CSPRNG into a large enough space that collisions are astronomically unlikely (e.g. 10 base32 chars = 2^50 ≈ 10^15 space for 10^7 codes gives a collision probability low enough to accept, and you still catch the rare one with a unique index). Both are fine; the Feistel approach gives you O(1) validation and guaranteed uniqueness, which I prefer for bulk single-use codes.

ApproachCollisionsDB checks at genParallelizableGuessableVerdict
Random + checkPossible, retried1+ per codeContendsNoSlow, racy
CSPRNG, big spaceAstronomically rareNone (unique index catches)YesNoFine
Index + FeistelImpossible by designNoneYes, cleanNo (scrambled + HMAC)Best for bulk

2. Single-Use and One-Per-Customer, Atomically, Without a Checkout Lock

This is the money part. Two guarantees: a single-use code redeems once total; a one-per-customer code redeems once per customer across their lifetime (or per the campaign window). Both must hold when the same customer fires three concurrent checkouts during a sale, and neither may add meaningful latency.

Naive: SELECT then UPDATE (read-modify-write)

def redeem(code, customer_id, order_id):
    row = db.get(code)                     # status check
    if row.status != "ISSUED":
        return "already used"
    if campaign.one_per_customer and used_before(customer_id, campaign):
        return "already redeemed by you"
    db.update(code, status="REDEEMED", order_id=order_id)   # <-- race window
    record_usage(customer_id, campaign)

Where it breaks: the gap between the SELECT and the UPDATE is a race. Two concurrent redeems of the same code both read ISSUED, both pass the check, both update - the code redeems twice. Same for one-per-customer: two devices both see “not used before,” both insert a usage row. Under a flash sale with retries, this is not a rare race; it is constant. You just gave away double the discount budget.

Naive fix: pessimistic lock (SELECT … FOR UPDATE)

Wrap it in a transaction that locks the code row:

BEGIN;
SELECT status FROM codes WHERE code = ? FOR UPDATE;   -- row lock
-- check, then UPDATE, then insert usage
COMMIT;

This is correct - the row lock serializes concurrent redeems. But it has real costs on the checkout path:

  • Lock held across a multi-step transaction (code update + usage insert + counter), including any network latency inside it. During a sale, held locks + a distributed transaction across the code store and usage store means contention and tail latency exactly when you cannot afford it.
  • A distributed lock (e.g. Redis SETNX/Redlock) per redeem adds a network round trip and a whole failure-mode surface (lock expiry, clock skew, the lock service as a new dependency on the hot path). It works, but it is latency and a new SPOF added to the one request that must be fast.

Locking is the honest first answer, and for low-contention cases it is fine. But “add a distributed lock to checkout” is precisely the latency we were told to avoid. We can usually avoid the explicit lock entirely.

Better: atomic compare-and-set + a unique constraint (lock-free on the common path)

Replace the read-modify-write with a single conditional write that only succeeds from the expected state. The database does the atomicity for you; no application-held lock.

For single-use, a conditional update (compare-and-set) on the code row:

-- Succeeds exactly once; the row lock is internal, held for one statement.
UPDATE codes
   SET status = 'REDEEMED', order_id = :order_id, redeemed_at = now()
 WHERE code = :code
   AND status = 'ISSUED';          -- the guard
-- rows_affected == 1  -> we won, this code is now ours
-- rows_affected == 0  -> someone else already redeemed it; reject

Only one concurrent request gets rows_affected == 1; every other sees 0 and is cleanly rejected. No SELECT ... FOR UPDATE, no application lock, no held transaction across services. The atomic CAS is the whole concurrency control, and it is a single-statement, single-key operation - which is exactly what sharded KV stores and Postgres both do fast.

For one-per-customer, lean on a unique constraint as the race-proof guard:

-- Usage ledger, sharded by customer_id:
CREATE TABLE redemptions (
  customer_id  BIGINT,
  campaign_id  BIGINT,
  code         VARCHAR(24),
  order_id     BIGINT,
  redeemed_at  TIMESTAMP,
  PRIMARY KEY (customer_id, campaign_id)   -- <-- one row per (customer,campaign)
);
-- Two concurrent redeems by the same customer both try to insert;
-- the DB lets exactly one in and rejects the other with a
-- duplicate-key error. The constraint IS the mutual exclusion.
INSERT INTO redemptions (customer_id, campaign_id, code, order_id, redeemed_at)
VALUES (:cust, :camp, :code, :order, now());
-- success -> first use; duplicate-key -> they already used it, reject.

The unique constraint turns “has this customer used this campaign?” from a racy check-then-act into a single atomic insert the database adjudicates. No lock you manage, no distributed coordination you build - you borrow the database’s own concurrency control, which is battle-tested and local to one shard (because both the code CAS and the usage insert are keyed by a single partition key: the code, and the customer respectively).

Ordering the two writes: do the per-customer insert first (fast reject for repeat customers, the common abuse case), then the code CAS, then the counter. If a later step fails, roll back the earlier ones (or release). To keep the code-CAS and usage-insert consistent when they live in different stores, make the operation idempotent and reconcilable rather than a cross-store 2PC: the order_id ties them together, a background reconciler fixes any half-done redemption using the redeem event, and the idempotency key (next section) makes a retry converge to the same outcome. In practice, for one-per-customer-single-use codes you can co-locate the usage row and the code row on the same shard (shard both by code) and do it in one local transaction; cross-customer shared codes use the counter + per-customer insert path.

3. Idempotent Redemption

During a flash sale, retries are not an edge case - they are the norm. The mobile client times out and resends, the payment flow retries, the load balancer re-dispatches. Without idempotency, a retried redeem could consume a second code or burn a customer’s one-per-campaign slot on a duplicate order.

Naive: no key, rely on “it probably won’t retry”

It will retry. And a bare CAS protects the code from double-redeem, but a retry of the same order that arrives after a release, or a retry that targets a fresh code because the client re-picked one, still corrupts customer-facing state. You need the operation to be keyed by the client’s intent, not just the code.

Correct: idempotency key stored with the result

Every mutating call (redeem, release) carries a client-generated idempotency_key (typically order_id + operation). The service records the key with the outcome, and a replay returns the stored outcome instead of re-executing.

def redeem(code, customer_id, order_id, idem_key):
    # 1. Claim the key atomically (Redis SET NX, or a unique row).
    prior = idem_store.get(idem_key)
    if prior and prior.state == "DONE":
        return prior.result                 # replay: return same answer
    if not idem_store.claim(idem_key, ttl=24h):  # SET NX
        return wait_or_return_inflight(idem_key)  # concurrent dup in flight

    # 2. Do the real work (CAS + usage insert + counter) exactly once.
    result = do_atomic_redeem(code, customer_id, order_id)

    # 3. Persist the result against the key, then expose it.
    idem_store.complete(idem_key, result)
    return result
  • Claim-before-work with SET NX means a concurrent duplicate cannot both execute; one claims, the other waits or reads the stored result.
  • Store the full result, not just “done,” so a replay returns the exact same discount and the exact same code, keeping the client consistent.
  • TTL the keys (e.g. 24h) - long enough to cover all realistic retries, short enough to bound storage.
  • The idempotency guard sits in front of the atomic CAS, so the two layers compose: idempotency collapses duplicate intents, the CAS/unique-constraint protects against distinct intents racing for the same resource.

This is what lets the stampede retry freely. A client can send the same redeem ten times; exactly one executes, the other nine get the identical stored answer, and nothing double-consumes.

4. The Hot Shared Code and the Budget Cap

Unique single-use codes have no hot key - each code is touched by one customer. But a shared code (WELCOME20) and a campaign budget cap (“stop after 500,000 redemptions” or “after 10,00,000 rupees of discount”) are single shared numbers that every redeem must touch. That is a hot key, the same shape as a flash-sale counter.

Naive: SELECT count(*) or a single DB row counter

Counting redemptions per redeem, or UPDATE campaign SET used = used + 1 WHERE used < cap, funnels every redeem through one row. At 3,300 redeems/sec on one campaign, that row is a contention hotspot and the single point that serializes the whole sale.

Better: atomic counter in Redis + async reconcile

Keep the live budget counter in Redis and use a single atomic operation as the gate:

# Reserve budget atomically; DECRBY returns the new value.
remaining = DECRBY budget:{campaign} 1
if remaining < 0:
    INCR budget:{campaign} 1      # give it back
    reject("budget exhausted")
else:
    proceed with redeem

DECRBY is atomic and single-threaded in Redis, so it never oversells, and it answers in well under a millisecond. The durable DB write still records each redemption (source of truth), but the real-time cap is enforced by the fast in-memory counter, and a background job periodically reconciles the Redis counter against the durable redemption count to correct any drift from crashes or releases.

For an extremely hot shared code, shard the counter into N sub-counters (budget:{campaign}:{0..N-1}), decrement a random shard, and reject only when a shard is empty and a cross-shard check confirms the total is gone. This spreads the hot key across N Redis slots at the cost of slightly fuzzier “last few units” behavior - acceptable, because being approximate about the final handful of a 500k budget is harmless, while being fast about the first 499,900 is essential. (Same trade-off as a flash-sale distributed counter.)

The per-customer limit on a shared code reuses the unique-constraint trick from part 2: PRIMARY KEY (customer_id, campaign_id) makes “this customer already used WELCOME20” a single atomic insert, no scan, no lock.

API Design & Data Schema

API

# --- Campaign / issuance (admin, off the hot path) ---
POST /campaigns
  body: { name, discount:{type, value}, window:{start,end},
          rules:{min_cart, eligible_skus[], first_order_only,
                 segment, stacking_policy},
          limits:{total_budget, per_customer_cap}, mode:"unique"|"shared" }
  201:  { campaign_id }

POST /campaigns/{id}/codes:generate
  body: { count: 10000000, prefix: "DIWALI" }
  202:  { job_id }                 # async batch; poll for completion
GET  /campaigns/{id}/codes:export?job_id=...   -> code list / CSV

# --- Validate (read, cached, no mutation) ---
POST /coupons/validate
  body: { code, customer_id, cart:{ total, items[], is_first_order } }
  200:  { applicable:true, discount:{type:"percent", value:20, amount:380},
          code_id }
  200:  { applicable:false, reason:"MIN_CART_NOT_MET", detail:"needs 2000" }

# --- Redeem (durable, atomic, idempotent) ---
POST /coupons/redeem
  headers: { Idempotency-Key: "<order_id>:redeem" }
  body:  { code, customer_id, order_id }
  200:   { redeemed:true, discount:{...}, redemption_id }
  409:   { redeemed:false, reason:"ALREADY_REDEEMED" }
  409:   { redeemed:false, reason:"PER_CUSTOMER_LIMIT" }
  409:   { redeemed:false, reason:"BUDGET_EXHAUSTED" }

# --- Release (compensating, idempotent) ---
POST /coupons/release
  headers: { Idempotency-Key: "<order_id>:release" }
  body:  { code, customer_id, order_id }
  200:   { released:true }

# --- Reporting (eventual) ---
GET  /campaigns/{id}/stats
  200:  { issued, redeemed, budget_used, budget_remaining, redemption_rate }

Note the split: validate has no idempotency key (it mutates nothing), redeem/release require one. The 409 rejections carry machine-readable reasons so the cart UI can show the right message.

Data schema

Campaign metadata - SQL (Postgres), small and relational. A few thousand rows, read constantly, needs transactional edits and rich rule fields. Cached in-process on every app node.

campaigns
  campaign_id    BIGINT   PK
  name           TEXT
  discount_type  ENUM(percent, flat, free_ship, bogo)
  discount_value NUMERIC
  starts_at      TIMESTAMP
  ends_at        TIMESTAMP
  min_cart       NUMERIC
  eligible_skus  JSONB            -- or a join table for large sets
  first_order_only BOOL
  segment        TEXT
  stacking_policy JSONB           -- which campaigns it combines with
  total_budget   NUMERIC
  per_customer_cap INT
  mode           ENUM(unique, shared)
  status         ENUM(draft, active, paused, ended)
  INDEX (status, starts_at, ends_at)

Code ledger - sharded KV / wide-column (e.g. Cassandra/DynamoDB), huge and point-access. 200M+ rows, accessed only by code (point get + CAS), no joins on the hot path. Partition key = code (or its hash) so every lookup and every CAS hits exactly one partition - no cross-partition coordination.

codes                          -- partition key: code
  code           VARCHAR(24)  PK   -- "DIWALI-7K2M-9QX4"
  campaign_id    BIGINT
  index          BIGINT            -- the dense id behind the Feistel code
  status         ENUM(ISSUED, RESERVED, REDEEMED, VOID)
  reserved_until TIMESTAMP         -- for the reserve-then-commit flow
  customer_id    BIGINT    NULL    -- set on redeem
  order_id       BIGINT    NULL    -- binds code to the order (idempotency)
  redeemed_at    TIMESTAMP NULL
  -- CAS guard writes: UPDATE ... WHERE code=? AND status='ISSUED'
  GLOBAL INDEX (campaign_id)       -- for export/reporting only, not hot path

Why NoSQL here: the access pattern is pure keyed point-read/point-write at huge scale with a single-key atomic CAS - no relational queries - and it must shard linearly as campaigns grow. A single Postgres box would become the bottleneck and SPOF; a sharded KV spreads 200M keys across nodes with no hot partition (keys are uniformly distributed by the Feistel scramble + hash).

Redemption / usage ledger - sharded SQL, sharded by customer_id. The financial record and the one-per-customer guard.

redemptions                        -- shard key: customer_id
  customer_id    BIGINT
  campaign_id    BIGINT
  code           VARCHAR(24)
  order_id       BIGINT
  discount_amt   NUMERIC
  redeemed_at    TIMESTAMP
  status         ENUM(APPLIED, RELEASED)
  PRIMARY KEY (customer_id, campaign_id)   -- one-per-customer guard
  INDEX (order_id)                         -- for release by order

Sharded by customer_id so a given customer’s whole redemption history (and their one-per-campaign uniqueness check) lives on one shard - the insert that enforces one-per-customer is a single-shard, single-statement operation. SQL here because we want the unique constraint and transactional APPLIED/RELEASED transitions on a financial record.

Idempotency store - Redis (with durable backup).

idem:{key}  ->  { state: CLAIMED|DONE, result: {...}, expires: ttl 24h }

Live counters - Redis.

budget:{campaign}       ->  integer, DECRBY-gated
budget:{campaign}:{i}   ->  sharded sub-counters for very hot codes

Bottlenecks & Scaling

Where it breaks first, in order, and the fix.

1. The hot shared-code / budget counter (breaks first under a sale). Every redeem of WELCOME20 or any budget-capped campaign touches one number. Fix: atomic DECRBY in Redis instead of a DB row; shard the counter into N sub-counters for the hottest codes and reject only when the total is provably gone; reconcile against the durable ledger async. The display count is served from a cached, slightly-stale value, never a live COUNT(*).

2. Latency on the checkout path. Validate/redeem sit on the revenue request. Fix: keep validate lock-free and cache-served (campaign rules in-process, code state read-through); replace pessimistic locks with single-statement CAS and unique-constraint inserts so there is no app-held lock and no distributed lock round trip; reject invalid codes with cheap checksum math before any storage touch. The durable write on redeem is a single-key op on one shard, not a cross-service transaction.

3. Code generation as a synchronous bottleneck. Minting 10M codes with per-code DB checks takes hours and contends. Fix: offline batch, collision-free by construction (dense index + Feistel bijection), split the index range across M parallel workers, no existence checks at all. Generation becomes a short, parallel batch job decoupled from the request path.

4. Double redemption under concurrency. The core correctness risk. Fix: atomic compare-and-set on the code (WHERE status='ISSUED') so exactly one concurrent redeem wins; unique constraint (customer_id, campaign_id) so one-per-customer is adjudicated by the DB; idempotency key in front so retries collapse to one execution. Three layers, each covering a different duplication source (same resource racing, same customer racing, same intent retried).

5. Sharding and the shard key. 200M codes and 730M redemptions/year outgrow one node. Fix: shard the code ledger by code (hashed) - every access is a point op on one partition, and the Feistel scramble keeps keys uniformly distributed so no hot shard. Shard the redemption ledger by customer_id so a customer’s one-per-campaign check and history are co-located on one shard. Campaign metadata stays unsharded (tiny) and fully cached.

6. Abandoned carts leaking codes (consume-too-early). If you mark a code REDEEMED at validate time, every abandoned cart burns a code. Fix: do not consume at validate. Either consume only at redeem (order placed), or use a RESERVED status with a short reserved_until TTL between “apply” and “pay,” auto-expiring back to ISSUED if the order never completes. A background sweeper (or lazy check on next access) reclaims expired reservations.

7. Replication and read scaling. Validate QPS peaks ~10k/sec, mostly reads. Fix: read replicas for the code and usage stores feed the read-through cache; writes go to the primary/owning shard. Strong consistency is required only on the redeem CAS (routed to the primary), while validate tolerates a slightly stale read because redeem re-checks atomically anyway - a stale “looks available” at validate is harmless since the CAS at redeem is the real gate.

8. Single points of failure. Redis, a shard primary, the coupon service. Fix: Redis in a replicated/clustered setup with the durable ledger as source of truth (Redis is an accelerator, not the system of record - a Redis loss degrades to slower DB-backed counting, not to incorrect redemption); shard primaries with synchronous replicas and automatic failover; the coupon service is stateless and horizontally scaled behind the gateway. If the whole coupon service is unreachable, checkout degrades per policy - proceed without the discount rather than block the order (configurable, because for some campaigns blocking is correct).

9. Cross-store consistency between code CAS and usage insert. They can live in different stores. Fix: co-locate on the same shard where possible (shard both by code for unique single-use codes) to get one local transaction; otherwise make the pair idempotent and reconcilable - the order_id ties them, the redeem Kafka event drives a reconciler that completes or compensates any half-done redemption, and the idempotency key guarantees a retry converges rather than diverges. Avoid 2PC on the hot path; prefer idempotent compensation.

10. Budget overshoot from releases/crashes. Counter drift over a long sale. Fix: periodic reconciliation of the Redis counter against COUNT(status='APPLIED') in the ledger; cap enforcement treats the durable ledger as truth for final accounting, with the fast counter as the real-time gate. A small, bounded overshoot during reconciliation lag is acceptable for most budgets and tunable by how tightly you reconcile.

Wrap-Up

The trade-offs that define this design:

  • Collision-free generation over generate-and-check. A dense index plus a Feistel bijection makes 10M unique codes a short parallel batch with zero existence checks and O(1) math-first validation, instead of an hours-long, racy, DB-contending grind.
  • Atomic CAS and unique constraints over explicit locks. We push concurrency control into single-statement database operations - compare-and-set on the code, a unique constraint on (customer, campaign) - so the common path has no application-held lock and no distributed-lock round trip. That is how we keep single-use and one-per-customer strong while staying off the checkout latency budget. Pessimistic locking is the fallback for genuinely contended cases, not the default.
  • Idempotency in front of atomicity. An idempotency key collapses duplicate intents (the stampede’s retries), while CAS and the unique constraint handle distinct intents racing for the same resource. Two independent layers, so retries are free and double-consumption is impossible.
  • Split validate from redeem. The cheap, cached, lock-free validate absorbs the flash-sale flood (most traffic never redeems); the durable, atomic, idempotent redeem is paid only on the orders that actually commit.
  • Fast in-memory counter for the one genuinely hot number. The shared-code and budget cap go in a Redis atomic counter (sharded when very hot) with the durable ledger as source of truth and async reconciliation - real-time enforcement without serializing the sale through one DB row.
  • Right store for each shape. Tiny relational campaign metadata cached everywhere; a sharded KV code ledger sharded by code for uniform point access; a sharded SQL usage ledger sharded by customer for the one-per-customer guard.

One-line summary: a coupon service that mints millions of unique single-use codes collision-free via index+Feistel, validates them lock-free from cache on the hot path, and redeems them with an idempotency key in front of an atomic compare-and-set plus a (customer, campaign) unique constraint - enforcing single-use and one-per-customer strongly, with a Redis atomic counter for shared-code budgets, so checkout stays fast and correct even under a flash-sale stampede.