Designing Promotions and Coupon Systems for SaaS and Online Stores

Promotions drive growth—but only if your discount logic, eligibility rules, stacking, and abuse prevention are sound. This guide dives into data models, calculation order, UX, APIs, and testing for building a robust promotions and coupon system.

Promotions are a powerful lever for acquisition, conversion, and retention. They’re also deceptively complex. Simple “10OFF” codes quickly grow into stacked discounts, unique vouchers, free trials, first-order rules, partner campaigns, renewal incentives, proration for subscriptions, and regional tax quirks. If you don’t design it well up front, you’ll ship brittle logic that’s hard to debug and easy to abuse.

This guide walks through the architecture of a robust promotions and coupon system for SaaS and online stores. We’ll cover the data model, discount calculation pipeline, stacking rules, subscription nuances, security and abuse prevention, UX, APIs, analytics, and testing. You’ll also see practical prompts you can use with YeshBe—an AI-powered platform for building software with natural language—to accelerate implementation. YeshBe doesn’t give you a ready-made promos module; it helps you build one that fits your business.

Start with the promotion lifecycle, not the discount type

Most teams begin by encoding discount math (e.g., “take 20% off”) and figure out eligibility later. Flip it. First, define the full lifecycle of how promotions exist in your system:

  • Authoring: Marketers or admins create a promotion, set constraints, attach audiences, generate codes.
  • Discovery: Users learn about offers on landing pages, email, or in-app nudges.
  • Validation: A cart, checkout, or quote flow evaluates eligibility and computes a price.
  • Redemption: The offer is applied to an order, subscription, or invoice; limits decrement.
  • Measurement: Attribution and lift analysis tie redemptions back to the campaign.
  • Governance: Audits, change history, abuse flags, and controlled rollouts.

Design each step explicitly. Many “edge cases” aren’t edges—they’re missing lifecycle steps.

Core concepts and data model

A minimal, flexible model usually includes these entities:

  • Promotion: The parent campaign or offer definition (e.g., “Black Friday 2026”). Holds metadata, eligibility rules, discount actions, validity period, stacking policy, and usage limits.
  • Coupon (Code): Optional code that targets a single promotion. Can be public (e.g., “BF2026”), limited-use shared codes, or unique one-time codes per recipient. Do not embed all logic in the code.
  • Condition: Eligibility rules: customer-first-order, plan in [Pro, Team], country in [US, CA], min subtotal ≥ $100, channel = email, customer segment = students, etc.
  • Action (Discount): What happens when eligible: percentage off, fixed amount off, N days free, item-level discount, order-level discount, shipping discount (for ecommerce), free add-on, or credit balance.
  • Redemption: A record that this customer used that promotion/coupon against a chargeable entity (cart/order/subscription/invoice), including amounts, timestamp, and result.

Example relational sketch:

{ promotions: { id, name, status, starts_at, ends_at, channel_restrictions, stacking_policy, max_redemptions_global, max_redemptions_per_customer, priority, currency_scope, discount_scope, created_by, created_at, updated_at }, promotion_conditions: { id, promotion_id, type, operator, value_json // e.g., type=customer.is_first_purchase, operator=equals, value_json=true // e.g., type=order.subtotal, operator=gte, value_json=10000 (cents) }, promotion_actions: { id, promotion_id, type, value_json // e.g., type=percent_off, value_json={"percent":20, "max_amount_cents":5000} // e.g., type=fixed_amount_off, value_json={"amount_cents":2000} // e.g., type=trial_extension_days, value_json={"days":14} }, coupons: { id, promotion_id, code_hash, code_hint, is_unique, max_redemptions, expires_at, created_by }, redemptions: { id, promotion_id, coupon_id, customer_id, order_id, subscription_id, applied_amount_cents, currency, status, error_code, created_at, idempotency_key } }

Why store code_hash not the plaintext code? To mitigate insider leaks and avoid returning actual codes to logs or exports. Keep a code_hint (e.g., last 4 chars) for support lookup.

Common discount actions and where they apply

  • Order-level percentage/fixed discount: Applied to the subtotal (define pre- or post-tax in your business rules; regional requirements may vary).
  • Item-level discount: Only for eligible items (by SKU, plan, or tag). Useful for bundles or per-seat discounts.
  • Credit balance: Adds account credit that invoices draw down over time. Good for B2B agreements or goodwill.
  • Trial extension: Adds N free days to a subscription trial (ensure you guard against indefinite stacking).
  • Free add-on/feature unlock: Grants a metered or entitlement-based feature for a period.

Model scope clearly: order, line item, subscription, invoice, or account credit. It controls how you calculate, persist, and expire the benefit.

Eligibility and constraints: be explicit

Before you write any math, list the constraints marketers and finance will need:

  • Date windows and blackout periods
  • Channel restrictions (e.g., only apply if source=“email”) and allow-list referrers
  • Customer eligibility (first order, new to a plan, student, geography)
  • Order thresholds (min subtotal, min seats)
  • Product/plan inclusion and exclusion lists
  • Usage caps (global, per customer, per code)
  • Stacking rules (exclusive vs combinable, maximum total discount)

Represent conditions as structured rules so you can add, test, and deprecate without code changes. Store the raw inputs you use for evaluation (e.g., cart lines, customer attributes) for replay and audits.

Calculation order, stacking, and rounding

Discount order changes outcomes. Publish your rules so they’re predictable:

  1. Find candidate promotions: Filter by status, date window, channel, tenant, and currency.
  2. Validate conditions: Evaluate eligibility against the cart/subscription and customer context.
  3. Resolve conflicts and stacking: Sort by priority, exclusivity, and cap. Some patterns:
    • “Exclusive” promotions block all others.
    • “Stackable” promotions apply in priority order until a cap is met.
    • Apply item-level discounts before order-level discounts, or vice versa—choose one and document it.
  4. Compute discounts: For each applied action, calculate the discount amount; respect per-action max caps.
  5. Rounding and currency: Round at the smallest currency unit per item, then sum, or round at the end—pick one and be consistent. Handle multi-currency by scoping promotions to specific currencies or converting at a known rate for display only.
  6. Taxes and fees: Decide whether discounts apply pre- or post-tax and fees. Tax treatment can be jurisdiction-specific; consult your tax advisor.

Expose a breakdown in the UI so customers can understand what happened. This also helps support troubleshoot issues.

Subscriptions: trials, proration, and renewals

SaaS adds unique wrinkles:

  • Trial promotions: Extend the trial but cap the total duration. Prevent “trial hopping” by tracking per-customer limits across emails and accounts where appropriate and lawful.
  • First-cycle discounts: Apply only to the first invoice; ensure it doesn’t reappear on renewals.
  • Recurring discounts: Apply for N cycles (e.g., 3 months 30% off). Store remaining cycles in the subscription’s discount state.
  • Proration: Mid-cycle plan changes require recalculating the remaining benefit. Decide whether to re-apply percentages to the prorated amount or convert the benefit to credits.
  • Upgrades vs downgrades: Require clear rules: does a discount persist across plan changes? Under what conditions?

Security and abuse prevention

Popular promotions attract creative attempts to exploit them. Build guardrails early:

  • Code entropy and rate limiting: Use sufficiently long, mixed-character codes for unique vouchers. Rate-limit code validation attempts and block obvious brute-force patterns.
  • Hash stored codes: Store a hash (e.g., HMAC with a secret) rather than plaintext. Compare hashes at validation time.
  • Eligibility verification: If “new customer only,” ensure it’s not bypassed by trivial changes (e.g., plus addressing). Consider checking payment instrument fingerprints or prior billing history, with care for false positives and privacy.
  • Channel and domain restrictions: Require a signed link for certain promos or restrict to verified email domains for partnerships.
  • Idempotent redemptions: All apply/remove operations should use idempotency keys to avoid double application under retries.
  • Audit logs: Log who created/edited promotions, code exports, and changes to usage caps. Limit access via roles and permissions.
  • Refund policies: Clarify how discounts interact with refunds to prevent “discount arbitrage.”

APIs and integration points

Whether your front end is a checkout form, a self-serve subscription flow, or a sales-assisted quote tool, expose clear APIs:

  • POST /pricing/estimate: Accepts cart or subscription state, returns price breakdown with applied promotions (read-only, no side effects).
  • POST /promotions/validate: Validates a code and returns eligibility details and potential discount.
  • POST /orders/:id/apply-promotion: Applies a promotion to a specific pending order or quote, using an idempotency key.
  • DELETE /orders/:id/promotion: Removes applied promotions from an order (where allowed).
  • Webhooks:promotion.redeemed, promotion.exhausted, promotion.expired for downstream analytics and alerts.

Keep the estimation step side-effect free. Commit redemptions only when the order or invoice is actually created, and tie the redemption record to that entity.

Admin UI: empower marketers without risking production

Invest in a clear admin UI for non-engineers:

  • Templates: “First purchase 20% off,” “3 months 50% off,” “$100 credit.”
  • Condition builder: Segments, thresholds, plan lists, channels, geographies, and date windows.
  • Stacking policy controls: Exclusive, combinable, priority, and caps.
  • Preview and simulate: Paste a cart or subscription context and see the result before publishing.
  • Scheduled publishing: Start/end times and time zones; dry runs and staged rollouts.
  • Change history: Versioned promotion definitions with diffs.
  • Code generation: Bulk unique code generation, export with one-time signed URLs, and usage analytics.

UX details that reduce support tickets

  • Auto-apply best offer: If multiple promotions could apply, auto-apply the one with the greatest savings and explain it: “We applied the best available discount.”
  • Clear error states: “This code expired on Oct 3” beats “Invalid code.”
  • Breakdown and tooltips: Show how the discount was computed. Link to terms.
  • Remove/replace flow: One click to remove a promotion; warn if switching from a larger discount to a smaller one.
  • Read-only codes in receipts: Include only a hint of the code in receipts to reduce leakage.

Analytics and measurement

Measure effectiveness without conflating correlation and causation:

  • Attach promo metadata to orders/invoices: Promotion ID, coupon ID, and full discount breakdown.
  • Define success metrics per promotion: Conversions, incremental revenue, churn impact for recurring discounts.
  • Holdouts where feasible: If you can, run controlled experiments to estimate lift. At minimum, compare against relevant baselines.
  • Attribution fields: Capture channel, campaign, landing page, and referrer to understand sources of redemption.

Testing strategy: determinism beats surprises

  • Unit tests: For each action type and condition operator. Include rounding, caps, and edge thresholds.
  • Property-based tests: Generate random carts and ensure invariants (e.g., total ≥ 0, discount ≤ subtotal, caps honored).
  • Golden files: Store known inputs/outputs for complex stacking scenarios. Detect regressions via diffs.
  • Time travel: Test behavior around start/end times and time zones.
  • Concurrency and idempotency: Simulate retries and concurrent applies on the same order.

Edge cases you’ll regret skipping

  • Refunds and partial refunds: Decide whether discount amounts are proportionally reversed or remain as promotion cost.
  • Returns (commerce): How do you recompute discounts when an item is returned out of a bundle?
  • Invoice retries: Ensure a first-cycle discount isn’t re-applied after a payment failure and retry.
  • Code exposure: Prevent logs, analytics scripts, and URLs from unintentionally persisting plaintext codes.
  • Multi-tenant boundaries: If you operate a multi-tenant platform, keep promotions, codes, and redemptions tenant-scoped with strict permissions.

YeshBe prompts you can adapt

YeshBe is a platform for building software through natural language. Use it to scaffold your promotions engine, admin UI, and APIs—then iterate. Here are practical prompts to start:

Design a promotions data model for a SaaS app. Include promotions, conditions, actions, coupons, and redemptions. Support percent and fixed discounts, trial extensions, and order vs subscription scope. Add fields for stacking policy, priorities, and caps.

Build an API endpoint POST /pricing/estimate that accepts a cart or subscription JSON and returns a price breakdown with applied promotions. No side effects. Handle multiple currencies and rounding at the item level.

Create an admin UI to author promotions: condition builder, action selection, stacking controls, scheduling, preview with sample carts, and change history. Only Admins can publish. Log all changes.

Implement secure coupon code handling: generate unique codes with sufficient entropy, store only a hash, validate with rate limiting, and include an idempotency key for apply/remove operations.

Add analytics for promotions: track redemptions per promotion and per coupon, attach attribution metadata to orders, and produce a dashboard showing conversions, revenue impact, and top-performing channels.

Example: pricing estimate request/response

A predictable contract makes integration and debugging easier.

// Request { "currency": "USD", "customer": { "id": "cus_123", "is_first_purchase": true, "country": "US" }, "lines": [ { "sku": "plan_pro", "quantity": 5, "unit_price_cents": 3000 }, { "sku": "addon_storage", "quantity": 1, "unit_price_cents": 1000 } ], "entered_code": "PRO20", "channel": "email", "context": { "trial_days_remaining": 0 } } // Response { "subtotal_cents": 16000, "discounts": [ { "promotion_id": "promo_abc", "coupon_hint": "…RO20", "scope": "order", "type": "percent_off", "amount_cents": 3200, "explanation": "20% off first purchase" } ], "total_discount_cents": 3200, "tax_cents": 0, "total_cents": 12800, "currency": "USD", "applied_promotions": ["promo_abc"], "messages": ["Best available discount applied"] }

Performance considerations

  • Indexing: Index by status, date window, tenant, and currency so you can quickly fetch candidate promotions.
  • Condition evaluation: Compile common conditions to efficient predicates. Cache results per customer/session when safe.
  • Precomputation: For high-traffic campaigns, precompute eligible customer lists or segments, then sanity-check at runtime.
  • Bounded results: Set sane caps (e.g., max 5 promotions) for stacking to keep calculations fast and predictable.

Governance, versioning, and safety rails

  • Versioned definitions: Don’t edit live promotions in place. Create a new version with a new ID and sunset the old one.
  • Feature flags: Wrap rollout behind flags to allow quick disable if something goes wrong.
  • Backfills and replays: If you fix a calculation bug, decide whether and how to retroactively adjust invoices or grant credits.
  • Separation of duties: Require review or approval for high-impact promotions (e.g., >50% off).

Document decisions you’ll live with

Write down the choices your system makes so future teammates and support staff can explain outcomes:

  • We apply item-level discounts before order-level.
  • We round at the line level to the nearest cent, ties round half up.
  • Discounts apply pre-tax unless specified per-region.
  • Exclusive promotions override all others regardless of priority.
  • Recurring discounts persist through upgrades but not downgrades.

When a question arises, point to the document rather than debating ad hoc.

Practical build checklist

  • Data model with promotions, conditions, actions, coupons, redemptions.
  • Deterministic calculation pipeline with stacking policy and rounding rules.
  • Secure code generation, hashed storage, rate-limited validation.
  • Idempotent apply/remove APIs and side-effect-free estimation.
  • Admin UI with preview, scheduling, versioning, and audit logs.
  • UX that auto-applies best offers and explains outcomes.
  • Analytics with attribution and promotion-level performance.
  • Tests for edge cases, time windows, concurrency, and refunds.

Where to iterate next

  • Segment sync: Integrate with your CDP or CRM to target customer cohorts.
  • Unique-code campaigns: Generate and distribute signed, single-use codes via email.
  • Partner promos: Create per-partner promotions with domain verification and usage caps.
  • Self-serve deals in-app: Target nudge banners near upgrade moments based on usage signals.

Build it with AI, but keep your logic transparent

Vibe Coding with YeshBe can accelerate scaffolding and iteration, but promotions still demand precise rules, careful modeling, and explicit governance. Treat your discount engine like any other core subsystem: documented, tested, observable, and safe to evolve.

If you’re starting from scratch, begin with trial extensions and first-cycle fixed or percent discounts. Add stacking and item-level logic once you have confidence in your calculation pipeline. The best promotions system is the one that marketers can use confidently—and engineers can sleep on.

What will you build first?

Start with one sentence. You can change everything after you see it.

Free to start. No credit card.