KatInterview

Build an In-Memory Promo Code Service

Data Structure DesignModel answer
MediumModel answerData Structure Designhash-mapexpirationidempotency

Last 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.
  • discount is the value in cents (e.g., 500 = $5.00 off).
  • expires_at and all timestamps are UTC epoch seconds.
  • total_limit is the maximum number of times the code can be redeemed across all users; per_user_limit caps how many times a single user can redeem it.
  • Returns True on success. Returns False if the code already exists (first registration wins). Raises ValueError for 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 a status indicating the outcome.
  • A code is considered expired when now >= expires_at.
  • If an idempotency_key is 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 0 for 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_limit may exceed total_limit; in that case the global limit binds first.
  • user_id can be any hashable value (int, str, etc.).

What is expected

  1. Choose data structures that give O(1) average time for apply and remaining_uses.
  2. Discuss the time and space complexity of each operation.
  3. Handle all edge cases: invalid inputs, duplicate codes, expired codes, both limit types, idempotent retries.
  4. 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.