Appearance
PromoCodeRegistry
Global singleton Durable Object (id: "global") for unified promo and referral code management with atomic validation.
Purpose
PromoCodeRegistry is the single source of truth for all discount codes in the system. It unifies campaign codes (admin-created) and referral codes (user-generated) into one table, providing atomic validate-and-record operations that prevent race conditions.
- Single global instance (
id: "global") - Atomic validate + record eliminates TOCTOU races (single-threaded DO guarantee)
- Snapshot system freezes discount terms at first use — renewals are immune to code changes
- Calculated status at read-time — no stale state
High-Level Design
Core Responsibilities
┌─────────────────────────────────────────────────────┐
│ PromoCodeRegistry │
│ │
│ ┌─────────────────────┐ ┌──────────────────────┐ │
│ │ PromoCodeStorage │ │ PromoCodeValidation │ │
│ │ Manager │ │ Manager │ │
│ │ │ │ │ │
│ │ • CRUD operations │ │ • 11 validation │ │
│ │ • Snapshot system │ │ rules │ │
│ │ • Referral code gen │ │ • Atomic validate + │ │
│ │ • Usage tracking │ │ record │ │
│ │ • Renewal cycles │ │ • Referrer │ │
│ └─────────────────────┘ │ eligibility │ │
│ └──────────────────────┘ │
│ ┌─────────────────────┐ ┌──────────────────────┐ │
│ │ SystemSubscription │ │ RebateProgram │ │
│ │ DiscountManager │ │ Manager │ │
│ │ │ │ │ │
│ │ • Admin-granted │ │ • Tiered rebate │ │
│ │ one-off discounts │ │ programs │ │
│ │ • Per-subscription │ │ • Global + Custom │ │
│ │ lifecycle │ │ KOL tiers │ │
│ └─────────────────────┘ │ • Monthly referral │ │
│ │ count → rebate $ │ │
│ └──────────────────────┘ │
└─────────────────────────────────────────────────────┘Managers
| Manager | Role |
|---|---|
| PromoCodeStorageManager | CRUD, snapshot creation, referral code generation, usage tracking, renewal cycles |
| PromoCodeValidationManager | 11-rule validation pipeline, atomic validate-and-record, referrer eligibility check |
| SystemSubscriptionDiscountManager | Admin-granted per-subscription discounts with race-safe lifecycle |
| RebateProgramManager | Tiered rebate programs (Global + Custom KOL), monthly referral count resolution |
Unified Code Model
Campaign and referral codes share the same promo_codes table, distinguished by referralWalletUserId:
| Type | referralWalletUserId | isSystemGenerated | Created By |
|---|---|---|---|
| Campaign code | null | not set | Admin |
| System referral | set | true | Auto from wallet (ACE-{FIRST5}-{LAST3}) |
| Custom referral | set | false | User-chosen |
All codes are uppercase, case-insensitive (3-30 chars, [A-Z0-9-]).
Atomic Validate-and-Record
The central operation is validateAndRecordUsage() — a single-threaded DO method that validates and records in one call, eliminating TOCTOU races:
validateAndRecordUsage(code, userId, plan, ...)
│
├─ "subscription" flow (first use)
│ ├─ Run 11 validation rules
│ ├─ transactionSync {
│ │ Create snapshot (freeze discount config at point-in-time)
│ │ Increment usage count
│ │ Insert usage record (UNIQUE constraint = second defense)
│ │ }
│ └─ Return discount amount + final price
│
└─ "renewal" flow (subsequent billing cycles)
├─ Look up existing usage → snapshot
├─ Validate discountCycles not exhausted
├─ Increment totalBillingCyclesApplied
└─ Return discount from snapshot (not current code)Snapshot system: On first use, a snapshot captures the code's discount configuration (discount type, value, applicable plans, cycles). All future renewals use this snapshot, so admin changes to the code don't retroactively affect existing subscriptions.
A separate read-only verifyPromoCode() method runs the same validation without recording — used for UI discount preview before payment.
Validation Rules (in order)
- Code exists
- Code is active (not disabled)
- Not before
validFrom(CODE_NOT_YET_VALID) - Not after
validUntil(CODE_EXPIRED) - Global usage limit not exceeded
- Cannot use own referral code (wallet match)
- User hasn't already used this code
- Per-user usage limit (enforced by UNIQUE index on
(user_id, promo_code_id)) - Plan applicability (empty = all plans)
- User type applicability (
newvsreturning) - Payment method applicability
Referral Code Flow
User wallet → generateReferralCode()
│
├─ Check existing (idempotent)
├─ Generate ACE-0X12345-ABC format
├─ Handle collision (append -1, -2, ...)
└─ Create with defaults:
10% off, 1 cycle, STANDARD/PRO only, new users only
Referee subscribes with code
│
├─ validateAndRecordUsage() in PromoCodeRegistry
└─ recordReferral() in referrer's ReferralManager
├─ Check referrer eligibility (active subscription — verified upstream by caller)
├─ Calculate rebate via PromoCodeRegistry.calculateRebateAmounts()
└─ Record with status eligible/ineligibleRebate Priority Resolution
When calculating referral rebates, the system resolves which program applies:
Custom KOL program (per-user) → highest priority
↓ (if none)
Global tiered program → mid priority
↓ (if none)
Legacy defaults ($4/$40/$68) → fallbackTier selection is based on last calendar month's referral count. Tiers must be contiguous (no gaps), and only the last tier may be unbounded.
System Subscription Discounts
Separate from promo codes — admin-granted one-off discounts attached to a specific subscription:
- One active discount per subscription (UNIQUE partial index)
- Lifecycle:
active→exhausted(auto when cycles hit limit) orcancelled(manual) - Race-safe mutations via
WHERE status = 'active'+rowsWrittencheck - Not idempotent:
incrementCyclesAppliedhas no dedup guard — caller must ensure single invocation per renewal
Edge Cases & Design Decisions
- Status is calculated, not stored:
calculatePromoCodeStatus()derives status at read-time fromisActive, usage limits, and time window — avoids stale status data. - Delete restriction: Only "scheduled" codes (future
validFrom) can be hard-deleted; active/expired codes persist for audit. - Custom-to-system discount sync: Updating a custom referral code's
discountValuesyncs to the system-generated code for the same wallet, keeping discount offers consistent. OnlydiscountValueis synced — other fields are independent. - Renewal idempotency:
incrementRenewalCycleguards withWHERE last_discounted_renewal_at < ?to prevent double-counting the same renewal. - Self-referral prevention:
CANNOT_USE_OWN_CODEerror if referral code's wallet matches the user (case-insensitive).
See Also
- UserPaperTradePortfolio —
SubscriptionManagercalls validate/record;ReferralManagercalls generate/lookup/rebate