Build an In-Memory Promo Code Service
Data Structure DesignModel answerLast updated
Design and implement a class that creates, validates, and redeems promotional discount codes with expiry, global and per-user limits, and idempotent retries.
Promo Code Service
You are building the backend logic for a promotions feature. Implement an in-memory service that manages discount codes from creation through redemption.
Interface to implement
class PromoService:
def register(self, code: str, discount: int, expires_at: int,
total_limit: int, per_user_limit: int) -> bool:
...
def apply(self, user_id, code: str, now: int,
idempotency_key: str | None = None) -> RedeemResult:
...
def remaining_uses(self, code: str, now: int) -> int:
...
register(code, discount, expires_at, total_limit, per_user_limit)
- Adds a new promo code to the service.
discountis the value in cents (e.g., 500 = $5.00 off).expires_atand all timestamps are UTC epoch seconds.total_limitis the maximum number of times the code can be redeemed across all users;per_user_limitcaps how many times a single user can redeem it.- Returns
Trueon success. ReturnsFalseif the code already exists (first registration wins). RaisesValueErrorfor invalid inputs.
apply(user_id, code, now, idempotency_key=None)
- Attempts to redeem the code for the given user at timestamp
now. - Returns a result object containing:
success: bool,discount_applied: int, and astatusindicating the outcome. - A code is considered expired when
now >= expires_at. - If an
idempotency_keyis provided, a second call with the same(user_id, idempotency_key)pair returns the cached result without consuming another use.
remaining_uses(code, now)
- Returns how many more times the code can still be redeemed globally.
- Returns
0for expired or unknown codes.
Constraints
- All timestamps are integers representing UTC epoch seconds. No need to handle timezone conversion inside the service — assume that happens upstream.
discount > 0,total_limit >= 1,per_user_limit >= 1.per_user_limitmay exceedtotal_limit; in that case the global limit binds first.user_idcan be any hashable value (int, str, etc.).
What is expected
- Choose data structures that give O(1) average time for
applyandremaining_uses. - Discuss the time and space complexity of each operation.
- Handle all edge cases: invalid inputs, duplicate codes, expired codes, both limit types, idempotent retries.
- Explain how you would handle concurrency if this service ran in a multi-threaded or distributed environment.
Follow-up questions (discuss, no need to implement fully)
- How would you add category restrictions (e.g., a code only applies to "electronics")?
- How would you support a minimum spend threshold (e.g., order must be ≥ $50)?
- How would you handle bulk registration from a JSON or CSV feed?
- How would you keep memory bounded as the number of expired codes grows?
Hints
Hint 1
Start by nailing down what state each promo code needs to carry: its configuration (discount, limits, expiry) and its runtime counters (global uses, per-user uses). A plain dict keyed on code gives you O(1) access to both.
Hint 2
Validation order in `apply` matters. Check idempotency first, then whether the code exists, then expiry, then the global limit, then the per-user limit — and only mutate state after all checks pass. This ensures a failed redemption never leaves partial state.
Hint 3
For memory cleanup, a min-heap ordered by expiry lets you evict expired codes without scanning the whole dict. But make expiry checks lazy (compare `now >= expires_at` on every read) so correctness never depends on cleanup having run first.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that every operation reduces to a keyed lookup, so hash maps are the right tool throughout. Each promo code stores its own configuration and two counters: a global used count and a per-user dict mapping user_id to their redemption count. All three operations are O(1) average.
Data structures
| Structure | Purpose |
|---|---|
promos: dict[code → Promo] | O(1) lookup for any operation |
Promo.used: int | global redemption counter |
Promo.per_user: dict[user_id → int] | per-user counter, O(1) read/write |
idem_cache: dict[(user_id, key) → Result] | replay cache for retries |
expiry_heap: [(expires_at, code)] | min-heap for background memory reclaim |
Expiry is always checked lazily on read by comparing now >= expires_at. The heap is an optimization for reclaiming memory, not for correctness — if you skip it, the service is still correct, just potentially wasteful.
Validation order in apply
Order matters because you want to avoid partial mutations on failure. The right sequence is:
- Check idempotency cache — return cached result immediately if hit.
- Code exists — return
INVALID_CODEif not. - Not expired — return
EXPIREDifnow >= expires_at. - Global limit not exhausted — return
GLOBAL_LIMITifused >= total_limit. - Per-user limit not exhausted — return
USER_LIMITif user's count>= per_user_limit. - Commit: increment both counters together, return success.
Because all checks happen before any mutation, a failed call leaves no trace. And because both counters are incremented in the same step, the invariant used == sum(per_user.values()) always holds.
Concurrency
In a single-threaded process this design is safe. In a multi-threaded context, the check-then-increment sequence on used and per_user is a race condition. The fix depends on the deployment:
- Single process, multiple threads: use a per-promo
threading.Lock. Lock before step 2 above, release after step 6. Per-promo locking is preferable to a global lock because unrelated codes don't contend. - Distributed service: the in-memory dict is no longer shared. Move state to Redis and use
HINCRBYwith a Lua script or a conditionalWATCH/MULTI/EXECblock to make the check-and-increment atomic. A SQL approach usesUPDATE ... WHERE used < total_limit RETURNING discountand checks affected rows.
Complexity
register: O(log n) due to the heap push; O(1) if you drop the heap.apply,remaining_uses: O(1) average.purge_expired: O(k log n) for k expired entries, amortized O(log n) per entry over its lifetime.- Space: O(C + R + I), where C = number of codes, R = distinct (code, user) redemption pairs, I = idempotency cache entries. Give the idempotency cache a TTL (e.g., 24 hours) so it stays bounded in production.
Follow-ups
Category restrictions: add a categories: set[str] field to Promo and a cart_categories: set[str] parameter to apply. Check that cart_categories & promo.categories is non-empty before proceeding. O(min(|cart|, |promo_cats|)) per call.
Minimum spend threshold: add min_spend: int to Promo and order_total: int to apply. Insert the check after expiry and before limit checks. Return a new BELOW_MIN_SPEND status on failure.
Bulk registration: accept a list or a JSON/CSV feed and call register in a loop, collecting per-code success/failure results. Return a summary dict rather than raising on the first bad entry, so a single malformed row doesn't abort the whole batch.
Memory bounds: purge_expired(now) pops the heap while the root's expiry is <= now, deletes the code from promos, and optionally clears its idempotency entries. Call it on a background timer or lazily at the start of any operation.
Common mistakes
- Mutating state before all checks pass. Incrementing
usedand then finding the per-user limit is exceeded means you have to roll back — messy and error-prone. Always validate first. - Using local time or naive datetimes. Near a DST boundary, a naive datetime can be ambiguous by an hour. Accepting only UTC epoch integers at the service boundary eliminates this entirely.
- Idempotency keys scoped globally instead of per user. Two different users could share a key (e.g., a client-generated UUID that collides or is reused). Scope the cache key as
(user_id, idempotency_key). - Assuming cleanup has run. Code that returns
INVALID_CODEinstead ofEXPIREDafter a purge is acceptable if documented, but code whose correctness depends on the purge having run is a bug.
Implementation
import heapq
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Dict, List, Optional, Tuple
class Status(Enum):
OK = "ok"
INVALID_CODE = "invalid_code"
EXPIRED = "expired"
GLOBAL_LIMIT = "global_limit_reached"
USER_LIMIT = "user_limit_reached"
@dataclass(frozen=True)
class RedeemResult:
success: bool
discount_applied: int # cents; 0 on failure
status: Status
@dataclass
class Promo:
code: str
discount: int
expires_at: int
total_limit: int
per_user_limit: int
used: int = 0
per_user: Dict[Any, int] = field(default_factory=dict)
class PromoService:
def __init__(self) -> None:
self._promos: Dict[str, Promo] = {}
self._expiry_heap: List[Tuple[int, str]] = []
self._idem: Dict[Tuple[Any, str], RedeemResult] = {}
# ---------- registration ----------
def register(
self,
code: str,
discount: int,
expires_at: int,
total_limit: int,
per_user_limit: int,
) -> bool:
if not isinstance(code, str) or not code.strip():
raise ValueError("code must be a non-empty string")
for name, v in [
("discount", discount),
("expires_at", expires_at),
("total_limit", total_limit),
("per_user_limit", per_user_limit),
]:
if not isinstance(v, int) or isinstance(v, bool):
raise ValueError(f"{name} must be an int")
if discount <= 0:
raise ValueError("discount must be > 0")
if total_limit < 1 or per_user_limit < 1:
raise ValueError("limits must be >= 1")
if code in self._promos:
return False # first registration wins
self._promos[code] = Promo(code, discount, expires_at,
total_limit, per_user_limit)
heapq.heappush(self._expiry_heap, (expires_at, code))
return True
# ---------- redemption ----------
def apply(
self,
user_id: Any,
code: str,
now: int,
idempotency_key: Optional[str] = None,
) -> RedeemResult:
# Idempotency: replay cached result for retries.
idem_id = (user_id, idempotency_key) if idempotency_key else None
if idem_id is not None and idem_id in self._idem:
return self._idem[idem_id]
result = self._attempt(user_id, code, now)
if idem_id is not None:
self._idem[idem_id] = result
return result
def _attempt(self, user_id: Any, code: str, now: int) -> RedeemResult:
p = self._promos.get(code)
if p is None:
return RedeemResult(False, 0, Status.INVALID_CODE)
if now >= p.expires_at:
return RedeemResult(False, 0, Status.EXPIRED)
if p.used >= p.total_limit:
return RedeemResult(False, 0, Status.GLOBAL_LIMIT)
user_used = p.per_user.get(user_id, 0)
if user_used >= p.per_user_limit:
return RedeemResult(False, 0, Status.USER_LIMIT)
# All checks passed — commit both counters together.
p.used += 1
p.per_user[user_id] = user_used + 1
return RedeemResult(True, p.discount, Status.OK)
# ---------- query ----------
def remaining_uses(self, code: str, now: int) -> int:
p = self._promos.get(code)
if p is None or now >= p.expires_at:
return 0
return p.total_limit - p.used
# ---------- maintenance ----------
def purge_expired(self, now: int) -> int:
"""Remove expired promos to reclaim memory. Returns count purged."""
count = 0
while self._expiry_heap and self._expiry_heap[0][0] <= now:
_, code = heapq.heappop(self._expiry_heap)
if code in self._promos and self._promos[code].expires_at <= now:
del self._promos[code]
count += 1
return count