Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Optimal Coupon Combination: Bounded DFS, Four-Layer Pruning & DDD for Production Checkout

Optimal Coupon Combination: Bounded DFS, Four-Layer Pruning & DDD for Production Checkout

This article details a production-grade coupon optimization system for e-commerce checkout, replacing greedy algorithms with bounded DFS search, four-layer pruning, and DDD-modeled rule engine separation to handle complex heterogeneous constraints while ensuring stability via hard limits, timeout fallback, snapshots, and gradual rollout.

Problem: Greedy and DP Limitations

The article opens with a real incident from a major promotion: a greedy coupon selector that always picked the highest-face-value coupon produced suboptimal results. A concrete example shows an order of 200 yuan with three coupons — coupon A (store coupon, 200-50), coupons B and C (category coupons, 100-30 each, stackable with each other but mutually exclusive with A). Greedy picks A for 50 yuan discount, while B+C yields 60 yuan — the global optimum. The author emphasizes this is a strategy boundary, not a parameter-tuning issue.

Dynamic programming is rejected because coupon constraints are heterogeneous: mutex groups, product scopes, thresholds, stack limits, priorities, and gift constraints. Each new constraint multiplies the state space, making memory and compute infeasible online.

Core Architecture: Rule Control Plane + Search Compute Plane

The solution separates concerns: a rule engine encapsulates all business constraints (configuration), while the search algorithm operates only within the legal space. Domain-driven design (DDD) provides the modeling foundation for this control plane.

DDD Domain Modeling

Aggregates and Value Objects

CouponTemplate aggregate (static configuration entity) with three value objects: Condition: admission constraints — order threshold, user segment, product range, time window. Benefit: discount rights — amount-type (direct reduction, discount) or gift-type (excluded from amount calculation but introduces independent constraints). Constraint: core of the control plane — mutex group ID, cross-group stack switch, per-order usage limit, calculation priority.

UserCouponInstance aggregate (runtime entity) created when a user claims a coupon, binding user, template, redemption status, and lifecycle.

Six Tables with Explicit Domain Responsibilities

coupon_template

: stores template and full constraint contract; rule engine configuration source. coupon_exclude_group: maintains mutex group relationships; foundation of combination constraints. coupon_activity: marketing activity aggregate; controls issuance inventory, channels, activity period. coupon_user: coupon instance storage; input source for pre-discount optimization. coupon_use_log: redemption flow; used for reconciliation, anti-fraud, link audit. coupon_combination_snap: discount snapshot. The author stresses its primary value is consistency anchor for order pre-discount results — freezing the discount result at order submission to isolate calculation drift caused by concurrent redemption or state changes; speedup is a side benefit.

Three Bounded Contexts

Template Configuration Domain: template, mutex group, activity configuration management.

User Coupon Wallet Domain: issuance, state transition, instance query.

Discount Calculation Engine Domain: rule filtering, optimization solving, snapshot persistence, stability control.

Domains synchronize via domain events + RPC; template or mutex updates trigger engine local cache refresh. The red line: marketing configuration changes must not invade the calculation domain's search logic.

Layered Architecture: Decoupling Rule Engine from Algorithm

Model layer : unified domain object contract; all inputs/outputs follow same semantics.

Rule engine layer : dual responsibility — pre-filtering and path constraint validation.

Pre-filter: expires, threshold unmet, product scope mismatch, already redeemed — removed before recursion, reducing base cardinality.

Path validation: at each DFS step when a coupon is tentatively added, engine validates in real time — mutex group exclusivity, stack permission, quantity limit, calculation priority.

Key benefit: operations adjusting thresholds, mutex relations, or stack strategies only change configuration; search code remains untouched.

Algorithm layer : bounded DFS backtracking with four-layer pruning. Goal: optimize within legal space, reject brute-force enumeration.

Bounded DFS with Four-Layer Pruning

The article provides simplified pseudo-code for the core search (framework glue removed). Key elements:

// Global context, single-solve isolation
class SearchContext {
    OrderDTO order;
    List<Coupon> candidates;
    Map<Long, Integer> groupBitMap; // mutex groupId -> bit index, index strictly < 64
    long excludeMask;                // BitMask mutex marker
    BigDecimal bestFinalPay;         // current best final pay
    List<Coupon> bestCombo;          // best coupon combo
    int maxIter = 5000;              // search node visit upper bound, set after stress test
    int iterCnt = 0;
}

// Backtracking entry
void dfs(SearchContext ctx, int idx, List<Coupon> currentCombo, long mask) {
    // Fallback circuit breaker: return if node limit reached
    if (ctx.iterCnt++ >= ctx.maxIter) return;
    // Recursion termination: all candidates traversed
    if (idx >= ctx.candidates.size()) {
        BigDecimal pay = calcPay(ctx.order, currentCombo);
        if (pay.compareTo(ctx.bestFinalPay) < 0) {
            ctx.bestFinalPay = pay;
            ctx.bestCombo = new ArrayList<>(currentCombo);
        }
        return;
    }

    Coupon curr = ctx.candidates.get(idx);
    // Branch-and-bound lower bound estimate: even if all remaining coupons picked, can it beat current best?
    BigDecimal lowerBound = estimateLowerBound(ctx.order, currentCombo, ctx.candidates.subList(idx, ctx.candidates.size()));
    if (lowerBound.compareTo(ctx.bestFinalPay) >= 0) {
        return; // prune: no optimization space
    }

    // Branch 1: skip current coupon
    dfs(ctx, idx + 1, currentCombo, mask);

    // Branch 2: try select current coupon, rule engine validates constraints
    if (ruleEngine.check(ctx.order, currentCombo, curr, mask)) {
        int bitIndex = ctx.groupBitMap.get(curr.excludeGroupId);
        long newMask = mask | (1L << bitIndex);
        currentCombo.add(curr);
        dfs(ctx, idx + 1, currentCombo, newMask);
        currentCombo.remove(currentCombo.size()-1);
    }
}

Notes: business auto-increment groupId must not be used directly as bit offset; a pre-maintained groupId-to-bit-index mapping avoids 64-bit overflow. The pseudo-code shows only main search logic; ruleEngine.check encapsulates threshold, product scope, stack limit, gift constraint validation; estimateLowerBound implements threshold pruning + benefit lower bound.

Four-Layer Pruning System (ordered by ROI)

Preprocessing pruning (highest ROI) :

Dominance pruning: within same mutex group, if coupon A has lower threshold and higher discount than B, B is dominated and removed.

Connected component decomposition: when coupons bind disjoint product sets and no cross-product deduction, split into independent sub-problems. Fails for universal store-wide coupons.

Group dimension reduction: treat each mutex group as a unit, at most one coupon per group. Search space collapses from 2^N to product of per-group option counts.

Sorting pruning : candidates sorted by discount benefit descending. High-benefit branches explored first, establishing a good global baseline early, enabling more aggressive bound pruning later.

Threshold pruning : during recursion, continuously evaluate whether remaining order base can satisfy admission thresholds of all unselected coupons on the current path. If impossible, branch cannot yield better solution — backtrack immediately.

Branch-and-bound pruning (core online optimization) : maintain global best final pay. For current branch, compute theoretical lower bound: even if all remaining stackable coupons on this path are applied, what is the minimum possible final pay? If this lower bound >= current best, branch has no optimization space — prune and stop recursion.

Mutex Validation: BitMask Bitmap

Each mutex group maps to one bit. Selecting a coupon sets the bit; subsequent selections detect conflict via bitwise O(1) operation, replacing loop traversal. Hard limit: bitmap capacity caps at 64 groups. If groups proliferate, fallback to HashSet validation; two implementations switched on demand.

Stability Safeguards: Non-Negotiable Engineering Red Lines

Optimization algorithms inherently have compute uncertainty. Pre-discount calculation sits on the critical order path; business availability cannot depend on algorithm output. A complete protection system is built:

Hard limits : recursion depth and max search nodes threshold (online threshold 5000 nodes).

Timeout circuit breaker : exceed preset latency (200ms) → terminate recursion immediately.

Strategy fallback : on limit/timeout, abandon optimal solution, gracefully degrade to battle-tested greedy strategy, prioritizing order availability. Business side must tolerate discount amount changes before fallback to avoid secondary validation failures.

Observability instrumentation : candidate coupon count, per-layer pruning hit counts, search node traversals, fallback triggers, single-call latency — all on monitoring dashboard. Sudden fallback spike signals coupon rules or user coupon scale exceeding design waterline.

Request idempotency : pre-calculation requests carry unique serial number to prevent duplicate computation and snapshot writes from retries.

Full chain walkthrough: Order + user request → query user coupon instances → rule engine pre-filter → preprocessing pruning, connected component split, group convergence → bounded DFS backtracking with real-time rule engine validation and four-layer pruning → produce optimal combo, write snapshot, return → auto-fallback to greedy on limit/timeout.

Production Review Checklist & Incident Retrospectives

Gift coupons mixed with amount coupons cause objective conflicts .

Incident: a beauty promotion mixed gift-sample coupons with threshold discounts. Original logic only optimized amount, producing minimum pay combo, but two gift coupons belonged to mutually exclusive gift activities — fulfillment errored at order submission. Resolution: keep primary objective as minimum pay; gift constraints validated as hard checks post-search. When gift mutex exists, fold into Constraint as secondary constraint, not into main search objective, avoiding second search-space explosion. Multi-objective split is key to complexity control.

Snapshot lifecycle often ignored, causing storage bloat .Most designs focus only on snapshot consistency, lacking cleanup. Unpaid, cancelled, timeout-closed order snapshots retained permanently; major promotions accumulate massive invalid data. Strategy: snapshot bound to order state, TTL auto-expire; historical snapshots beyond reconciliation window async archived, cold-hot separation. Consistency and storage cost require trade-off.

Gradual rollout cadence must not be aggressive .Optimization CPU cost significantly higher than greedy; cannot full-cutover at once. Method: user-level gradual, dual-track parallel comparison, continuously observe optimal-vs-greedy diff rate, latency, fallback rate. Only when diff stable and fallback controlled, gradually increase. Gradual is not simple traffic split — it's two-strategy risk hedging.

Pruning logic changes require regression review .Dominance pruning and connected-component decomposition judgments are essentially business rules. New coupon types or constraint types from operations can easily break existing pruning assumptions. Red line: new coupon category or constraint type must pass architecture review to verify no existing pruning preconditions are violated; cannot ship directly.

Architecture Trade-offs & Scenario Boundaries

Every solution has applicability boundaries; architect's core skill is recognizing scenarios and rejecting over-engineering.

Suitable scenarios Major promotion checkout, moderate user coupon volume, complex mutex/stack rules, users sensitive to discount results, high complaint cost.
Unsuitable scenarios Few coupons, simple rules — greedy stable enough; ultra-low-latency paths, massive coupon volume without group constraints — this solution's maintenance cost too high, benefit cannot cover cost.

Many engineers fall into chasing algorithmic optimality. Architecture decisions are never about picking the most capable solution, but finding the balance point among business demands, development cost, and online stability.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Report an issue with this article
rule enginesystem stabilitydomain-driven designcoupon optimizationproduction engineeringe-commerce checkoutbounded DFSpruning algorithms

Reader feedback

Was this useful?

Useful0

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion