A deep dive into designing a production-grade offer validation service — from client-side validation caches and real-time UX feedback to server-side conditions engines, stackable offers with priority ordering, and race-condition-safe usage tracking.
We are building an offer validation service — a client-server SDK that handles the lifecycle of coupon codes, promo codes, and stackable offers at checkout. Think of it as the validation layer that sits between the user typing a promo code into an input field and the order being placed, answering one question: is this offer valid for this cart at this moment?
Every e-commerce platform above a certain scale needs this. Shopify has discount codes with usage limits. Amazon has coupon clipping and promotional credits. Uber Eats has stackable promotions that combine restaurant offers with platform discounts. The underlying engine is always the same: a rules evaluator that checks conditions, a usage tracker that prevents oversubscription, and a feedback layer that communicates results to the user without friction.
We will use the RADIO framework throughout this article: Requirements, Architecture, Data Model, Interface (API), and Optimization — covering every layer from the React input component to the database transaction that deducts the usage slot.
Key Insight
The hard part of offer validation is not evaluating individual conditions. It is handling the race between the optimistic UI (showing "SAVE20 applied!" instantly) and the authoritative server check that must decrement a usage counter in a way that two users claiming the last slot do not both succeed.
1. Requirements & Scoping
An offer validation service touches the checkout flow, the admin panel where offers are created, the order pipeline that records applied discounts, and the reporting system that measures campaign effectiveness. Before we design, we scope what the system must support and what we explicitly leave for future iterations.
Functional
Single-code validation — check one offer at a time
Scope by asking: "What happens when two users race for the last available slot of a limited coupon?" If the answer is "one succeeds, one gets an error", you need pessimistic locking in the usage tracker. If the answer is "both succeed and we fix it after", you can use eventual consistency. The choice determines your database isolation level.
2. Core Concepts — Offers, Conditions, Rules
Every offer validation system has four core abstractions. Getting these right determines whether your promotions are flexible enough for marketing and safe enough for finance.
Offers are the high-level campaign entity. An offer has a code (like SAVE20), a discount definition (20% off, $10 off, free shipping), and a set of temporal constraints (active dates, usage limits). Offers can be coupons (user-entered codes), promotions (generally available), or gift cards (store credit).
Conditions are the rules that determine whether an offer applies. The most common are minimum purchase amount, applicable categories (only applies to electronics), user tier (pro members get extra discount), and geographic restrictions (not valid in certain regions). Conditions are stored as a list of { field, operator, value } tuples that the engine evaluates against the cart context.
Validation results carry more than just a boolean. They include structured error codes that the frontend can translate into user-friendly messages, computed discount details (raw value vs capped value), and warnings (like "this offer is already applied"). The result object is the contract between the validation engine and the UI.
Usage tracking records every successful application of an offer. This is where race conditions live — two users simultaneously hitting "Apply" on the last available slot. The usage tracker must use database-level locking or atomic counters to ensure correctness.
Abstraction
Example
Lives Where
Offer
code: 'SAVE20', discount: 20%
Created in admin, evaluated on server
Condition
cart.total >= 50
Evaluated server-side
ValidationResult
{ valid: true, discount: { ... } }
Emitted by server, consumed by client
UsageRecord
offer + user + order + timestamp
Written on apply, read on validate
Warning
Do not conflate offer validation with payment processing. Validation answers "can this code be applied?" The actual discount is applied during order calculation, and the final price is authorized during payment. The validation service is a gate before the financial pipeline — it prevents bad offers from reaching the order system, but it does not calculate final pricing.
3. Data Model — Offer Definitions & Usage Tracking
The data model defines how offers, conditions, and usage records are stored and queried. A well-structured model is the difference between a promotion system marketing can configure independently and one that requires engineering for every new campaign.
The Core Data Types
Every offer validation system needs at least four tables: offers stores the offer definition, offer_conditions stores the rules that govern applicability, offer_counters maintains atomic usage counts, and offer_usages records every user-order combination that consumed a slot.
The exclusivity_group field is subtle but powerful. Multiple offers might belong to the "platform-wide promo" group, meaning only the best one applies. An offer with exclusivity_group: null is compatible with anything unless explicitly marked non-stackable. This lets marketing create overlapping campaigns without manual conflict resolution.
4. Architecture — Client Cache + Server Engine
The offer validation architecture is split into two layers: the client-side validation cache that provides instant feedback, and the server-side validation engine that is the single source of truth. The client cache is optimistic — it stores recent results to avoid network calls when the user re-types or corrects a code. The server engine is authoritative — every code must be checked against the live database before it can be applied to an order.
The Validation Flow
User types promo code
Input event triggers debounced validation (400ms delay). Prevents a network call per keystroke.
Client cache lookup
Check in-memory cache keyed by code + cart fingerprint. If cached and fresh (< 30s), return instantly. No network call.
Server validation request
POST /api/offers/validate with code and cart context. Debounced to 400ms idle. Shows spinner during request.
Client stores result in cache with 30s TTL, capped at 50 entries. Future lookups skip the network.
UI renders feedback
Map result status to visual feedback: green border + checkmark for valid, red for errors, animated transitions.
Figure 1 — Two-layer architecture. The client hook checks cache and calls the server. The server engine evaluates conditions and records usage against the database. Results flow back to update the UI.
Why Client-Side Caching Matters
A user typing a promo code triggers validation on every pause. Without caching, a single code entry could generate 3-5 network requests. With caching, only the first request hits the server. Subsequent edits (adding/removing items from cart, switching between codes) are served from cache. The 30-second TTL ensures stale data does not persist past a reasonable window, and the 50-entry cap prevents memory leaks on long-running single-page sessions.
The cache key includes the cart fingerprint (cartId + total) because the validity of a percentage-off coupon changes when the cart total changes. A cache entry for a $100 cart is stale when the user adds another item — the discount amount has changed even if the code is still valid.
Key Insight
The cart fingerprint in the cache key is the detail most implementations miss. A naive cache keyed only by code returns stale discount amounts when the cart changes. Including the cart total means the cache auto-invalidates when quantities change. For more precision, include a hash of the item IDs.
5. Client SDK — Hooks, Cache, Real-Time Feedback
The client SDK is the interface that React components use to validate offers. It exposes a single hook — useOfferValidation — that handles the validation lifecycle: debounced input, cache lookup, server request, and state management. The hook returns a state machine that drives the UI.
The Validation State Machine
The validation state has seven distinct states: idle (no code entered), validating (network request in flight), valid (offer accepted, discount calculated), invalid (code does not apply), expired (offer window passed), limit_reached (usage cap hit), and error (network failure). Each state maps to a distinct visual treatment in the UI.
The hook provides two validation functions: validate for immediate (button-triggered) checks and debouncedValidate for keystroke-triggered checks. The debounce window of 400ms balances responsiveness against network cost. If the user types "SAVE20", the debounced function fires only once, 400ms after they stop typing. If they clear the input before 400ms elapses, the pending call is cancelled.
Strategy
Trigger
Latency
Best For
Debounced (400ms)
On input change
400ms + network
Inline "check as you type" UX
Immediate (validate)
On "Apply" button click
Network only
Explicit submission flow
Cached (instant)
On any check with fresh cache
<1ms
Reducing redundant network calls
Tip
Always provide both a debounced input handler and an explicit "Apply" button. The debounced handler gives instant visual feedback as the user types. The explicit button gives them a sense of control and a clear action to trigger validation when they are done typing. Some users find auto-validating inputs disorienting — the button is their safety net.
6. Server-Side Validation Engine
The server-side validation engine is the authoritative decision maker. Every offer that appears valid on the client must be re-validated on the server before it can be applied to an order. The engine runs a strict pipeline: lookup, temporal check, usage check, condition evaluation, and discount calculation. If any step fails, the entire validation fails.
The Validation Pipeline
Offer lookup by code
Query the offers table. Case-insensitive match. Returns 404-style error if code does not exist.
Temporal gate
Check isActive, startsAt, expiresAt. Expired and not-yet-active offers fail fast before any I/O.
Usage limits
Check global usage counter and per-user usage counter against their respective caps.
Run through the conditions list. Each rule resolves a field from the cart context and applies its operator.
Discount calculation
Compute raw discount, apply cap, return the final value. Only reached if all prior gates passed.
Figure 2 — The validation pipeline runs six sequential gates. Any failure aborts early and returns a structured error code. Only passes all six reach the discount calculation.
example.typescript
class OfferValidationEngine {
async validate(
code: string,
userId: string,
cart: CartContext,
): Promise<ValidationResult> {
const errors: ValidationError[] = [];
const warnings: string[] = [];
// 1. Lookup offer
const offer = await this.findOffer(code);
if (!offer) {
return this.fail('OFFER_NOT_FOUND', 'Invalid promo code');
}
// 2. Active & date range
if (!offer.isActive) {
return this.fail('OFFER_INACTIVE', 'This offer is no longer active');
}
if (offer.expiresAt && new Date() > offer.expiresAt) {
return this.fail('OFFER_EXPIRED', 'This offer has expired');
}
if (new Date() < offer.startsAt) {
return this.fail('OFFER_NOT_STARTED', 'This offer is not active yet');
}
// 3. Global usage limit
if (offer.maxUsages !== null) {
const usageCount = await this.usageRepo.countByOffer(offer.id);
if (usageCount >= offer.maxUsages) {
return this.fail('USAGE_LIMIT_REACHED',
'This offer has reached its usage limit');
}
}
// 4. Per-user usage limit
if (offer.maxUsagesPerUser !== null) {
const userUsage = await this.usageRepo.countByOfferAndUser(
offer.id, userId);
if (userUsage >= offer.maxUsagesPerUser) {
return this.fail('USER_USAGE_LIMIT_REACHED',
'You have already used this offer');
}
}
// 5. Min purchase amount
if (offer.minPurchaseAmount !== null &&
cart.total < offer.minPurchaseAmount) {
return this.fail('MIN_PURCHASE_NOT_MET',
`Minimum purchase of ${formatCurrency(offer.minPurchaseAmount)} required`);
}
// 6. Category/product constraints
const categoryError = this.checkCategoryRestrictions(offer, cart);
if (categoryError) errors.push(categoryError);
const productError = this.checkProductRestrictions(offer, cart);
if (productError) errors.push(productError);
// 7. Custom conditions
const conditionsPassed = await this.evaluateConditions(
offer.conditions, { userId, cart });
if (!conditionsPassed.ok) {
errors.push({
code: 'CONDITIONS_NOT_MET',
message: conditionsPassed.error ?? 'Conditions not satisfied',
});
}
if (errors.length > 0) {
return { valid: false, offer, errors, warnings };
}
// 8. Calculate discount
const discount = this.calculateDiscount(offer, cart);
// 9. Idempotency: check if already applied
const alreadyApplied = await this.usageRepo.findByOfferAndOrder(
offer.id, cart.orderId);
if (alreadyApplied) {
warnings.push('This offer is already applied to this order');
}
return { valid: true, offer, discount, errors, warnings };
}
private calculateDiscount(
offer: Offer,
cart: CartContext,
): { type: string; value: number; cappedValue: number } {
let value = 0;
if (offer.discountType === 'percentage') {
const eligibleTotal = this.getEligibleTotal(offer, cart);
value = eligibleTotal * (offer.discountValue / 100);
} else if (offer.discountType === 'fixed_amount') {
value = offer.discountValue;
}
const cappedValue = offer.maxDiscountCap !== null
? Math.min(value, offer.maxDiscountCap)
: value;
return { type: offer.discountType, value: Math.round(value * 100) / 100,
cappedValue: Math.round(cappedValue * 100) / 100 };
}
private getEligibleTotal(offer: Offer, cart: CartContext): number {
let items = cart.items;
if (offer.applicableCategories.length > 0) {
items = items.filter(i =>
offer.applicableCategories.includes(i.category));
}
if (offer.applicableProducts.length > 0) {
items = items.filter(i =>
offer.applicableProducts.includes(i.productId));
}
if (offer.excludedCategories.length > 0) {
items = items.filter(i =>
!offer.excludedCategories.includes(i.category));
}
if (offer.excludedProducts.length > 0) {
items = items.filter(i =>
!offer.excludedProducts.includes(i.productId));
}
return items.reduce((sum, i) => sum + i.price * i.quantity, 0);
}
}
The Conditions Evaluator
The conditions evaluator is a pluggable rule engine. Each offer has a list of { field, operator, value } rules that are evaluated in order. The evaluator resolves each field from the cart context using built-in resolvers (cart total, item count, user tier, shipping country) and applies the operator. If any rule fails, the entire validation returns a conditions-not-met error.
example.typescript
class ConditionsEvaluator {
async evaluate(
rules: Rule[],
context: { userId: string; cart: CartContext },
): Promise<{ ok: boolean; error?: string }> {
for (const rule of rules) {
const value = this.resolveField(rule.field, context);
const passed = this.applyOperator(rule.operator, value, rule.value);
if (!passed) {
return {
ok: false,
error: `Condition failed: ${rule.field} ${rule.operator} ${rule.value}`,
};
}
}
return { ok: true };
}
private resolveField(
field: string,
ctx: { userId: string; cart: CartContext },
): unknown {
// Built-in resolvers
const resolvers: Record<string, () => unknown> = {
'cart.total': () => ctx.cart.total,
'cart.itemCount': () => ctx.cart.items.length,
'cart.uniqueItems': () => new Set(
ctx.cart.items.map(i => i.productId)).size,
'user.isNew': () => ctx.cart.userCreatedAt >
new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
'user.tier': () => ctx.cart.userTier,
'cart.hasSubscription': () => ctx.cart.items.some(
i => i.isSubscription),
'cart.shippingCountry': () => ctx.cart.shippingCountry,
'payment.method': () => ctx.cart.paymentMethod,
};
return resolvers[field]?.() ?? undefined;
}
private applyOperator(
op: Rule['operator'],
actual: unknown,
expected: unknown,
): boolean {
switch (op) {
case 'eq': return actual === expected;
case 'neq': return actual !== expected;
case 'gt': return typeof actual === 'number' &&
typeof expected === 'number' && actual > expected;
case 'gte': return typeof actual === 'number' &&
typeof expected === 'number' && actual >= expected;
case 'lt': return typeof actual === 'number' &&
typeof expected === 'number' && actual < expected;
case 'lte': return typeof actual === 'number' &&
typeof expected === 'number' && actual <= expected;
case 'in': return Array.isArray(expected) &&
expected.includes(actual);
case 'not_in': return Array.isArray(expected) &&
!expected.includes(actual);
case 'contains': return typeof actual === 'string' &&
typeof expected === 'string' && actual.includes(expected);
default: return false;
}
}
}
The resolver pattern makes the conditions system extensible. New fields can be added without changing the evaluation logic — just add a new entry to the resolvers map. Marketing can create complex offers like "20% off for premium users in the US who have a subscription in their cart" by combining resolvers without writing code.
Validation Error Codes
Code
Meaning
Client UX
OFFER_NOT_FOUND
Code does not exist
"Invalid promo code"
OFFER_EXPIRED
Past expiration date
"This offer has expired"
USAGE_LIMIT_REACHED
Global usage cap reached
"This offer is fully claimed"
USER_USAGE_LIMIT_REACHED
User used it max times
"You have already used this offer"
MIN_PURCHASE_NOT_MET
Cart below minimum
"Minimum purchase of $X required"
CONDITIONS_NOT_MET
Custom rule failed
"Offer conditions not satisfied"
Warning
The server engine must be idempotent for the same code+cart input. If a network error causes the client to retry, the engine must return the same result — not decrement the usage counter twice. The simplest approach is to check for an existing usage record (offer_id + order_id) before counting a new application. If the record exists, return the cached result.
7. UX Feedback Patterns
The feedback UX is where offer validation meets the real user experience. A well-designed feedback system makes offer application feel seamless and satisfying. A poorly designed one makes users wonder if their code was even registered. The key is mapping every validation state to a specific visual treatment that communicates the result without requiring the user to read text carefully.
State-Driven Feedback
Every validation state maps to a distinct visual pattern. The input border changes color (blue for validating, green for valid, red for errors). An animated icon appears next to the input (spinner, checkmark, X, clock). A message below the input explains the result in plain language. The transitions between states are smooth — a flash from "validating" to "valid" should show a brief success animation, not a jarring swap.
example.tsx
// Offer input with real-time validation
function OfferCodeInput() {
const { state, debouncedValidate, validate } =
useOfferValidation(cartContext);
const [inputValue, setInputValue] = useState('');
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(e.target.value);
debouncedValidate(e.target.value);
};
const handleApply = () => {
validate(inputValue);
};
return (
<div style={{ position: 'relative' }}>
<div style={{ display: 'flex', gap: 8 }}>
<input
value={inputValue}
onChange={handleChange}
placeholder="Enter promo code"
aria-label="Promo code"
style={{
border: `1px solid ${getBorderColor(state)}`,
padding: '10px 12px',
borderRadius: 6,
flex: 1,
}}
/>
<button onClick={handleApply}
disabled={state.status === 'validating'}>
Apply
</button>
</div>
<ValidationFeedback state={state} />
</div>
);
}
function ValidationFeedback({ state }: { state: ValidationState }) {
switch (state.status) {
case 'idle':
return null;
case 'validating':
return (
<Message type="info">
<Spinner /> Checking offer...
</Message>
);
case 'valid':
return (
<Message type="success">
<CheckIcon /> {state.result.offer!.title} applied!
{state.result.discount && (
<span> You save {formatDiscount(state.result.discount)}</span>
)}
</Message>
);
case 'invalid':
return (
<Message type="error">
<XIcon /> {state.errors[0]?.message ?? 'Invalid code'}
</Message>
);
case 'expired':
return (
<Message type="error">
<ClockIcon /> This offer has expired
</Message>
);
case 'limit_reached':
return (
<Message type="warning">
<UsersIcon /> This offer is fully claimed
</Message>
);
case 'error':
return (
<Message type="error">
<AlertIcon /> {state.message}
</Message>
);
}
}
function getBorderColor(state: ValidationState): string {
switch (state.status) {
case 'valid': return '#22c55e';
case 'invalid': case 'expired':
case 'limit_reached': case 'error': return '#ef4444';
case 'validating': return '#3b82f6';
default: return '#d1d5db';
}
}
function formatDiscount(d: { type: string; value: number }): string {
if (d.type === 'percentage') return `${d.value}% off`;
return `$${d.value.toFixed(2)} off`;
}
Feedback Patterns Compared
Pattern
Description
Best For
Inline validation
Real-time feedback below/beside the input field
Primary pattern for single-code entry
Toast notification
Transient message at top/bottom of screen
Secondary confirmation after Apply button
Order summary update
Live recalculation of totals with discount breakdown
Showing the financial impact of applied offer
Offer chip/tag
Applied offer shown as a removable chip above the total
Multi-offer stacking, easy removal
Key Insight
The most impactful UX improvement for offer validation is showing the monetary impact of an applied offer immediately. Do not just show a green checkmark — show "You save $12.00" with a line-through on the original price. This creates a dopamine feedback loop that encourages users to find and apply more codes. It is the same psychological mechanism that makes coupon sites profitable.
8. Stackable Offers — Priority & Exclusivity
The ability to stack multiple offers on the same order is what separates a basic coupon system from a serious promotions engine. Stacking introduces complexity: offers have priority ordering, exclusivity groups that prevent combining certain promotions, and combinatorial rules that determine the optimal discount mix.
The Stacking Rules
When multiple offers are applied, the stacking engine sorts them by stackPriority (lower numbers first). Offers within the same exclusivityGroup are compared and only the best one (highest discount) is kept. Non-stackable offers (isStackable: false) can only be the sole applied offer — if another is already applied, the non-stackable one is rejected. The discount is applied cumulatively to the running total.
Figure 3 — The stacking engine validates all codes, groups by exclusivity, keeps only the best per group, and applies stackable offers cumulatively to the running total.
Only $10 off applies. Non-stackable rejects stacking.
Mixed groups
10% off (group A) + 20% off (group A) + $5 off (group B)
20% off (best of A) + $5 off (B). Both apply.
Tip
For the stacking engine, always apply percentage discounts before fixed-amount discounts. This maximizes the discount for the user and matches the mental model of "percentage off the original price, then additional fixed savings." The priority field lets you override this ordering for specific campaigns — for example, a "free shipping" code should apply last regardless of its priority because it does not stack arithmetically with monetary discounts.
9. Optimizations & Caching
Performance is critical for offer validation because it runs during checkout — the moment when users are most sensitive to delay. Every millisecond of validation latency increases cart abandonment risk. The optimization strategy spans client caching, server-side query optimization, and database-level concurrency control.
Client-Side Caching
The in-memory client cache (30s TTL, 50-entry cap) eliminates redundant network calls when the user re-types a code or toggles between offers. The cache key includes the cart fingerprint, so changes to the cart automatically invalidate stale entries. For long-running single-page sessions, the LRU eviction policy ensures the cache does not grow unbounded.
Server-Side Query Optimization
The most expensive server-side operation is the usage counter check. A naive implementation reads the counter from the database on every validation. Use a read-through cache (Redis or in-memory with TTL) for counter values. The cache is invalidated when a usage slot is consumed. This reduces the database read load by orders of magnitude — the counter changes only when someone successfully applies the offer, which is a fraction of validation requests.
Race Condition Protection
The usage counter is the most concurrency-sensitive part of the system. Two users validating the same limited offer simultaneously must not both receive a "valid" result when only one slot remains. The solution is pessimistic locking: the reservation query uses SELECT ... FOR UPDATE to lock the counter row, reads the current count, increments it within the same transaction, and commits. The second user's transaction waits for the first to complete, then reads the updated counter and sees the limit reached.
Figure 4 — Two users race for the last usage slot. User A's transaction commits first; User B's transaction reads the updated counter and rolls back. The pessimistic lock prevents oversubscription.
example.typescript
// Optimistic usage reservation with rollback
class OfferUsageTracker {
async reserve(
offerId: string,
userId: string,
orderId: string,
): Promise<{ success: boolean; error?: string }> {
const trx = await this.db.transaction();
try {
// Lock row for update (pessimistic)
const current = await trx.oneOrNone(
`SELECT usages FROM offer_counters
WHERE offer_id = $1 FOR UPDATE`,
[offerId],
);
const maxUsages = await this.getMaxUsages(offerId);
if (current && current.usages >= maxUsages) {
await trx.rollback();
return { success: false,
error: 'Offer usage limit reached' };
}
// Increment counter
await trx.query(
`INSERT INTO offer_counters (offer_id, usages)
VALUES ($1, 1)
ON CONFLICT (offer_id)
DO UPDATE SET usages = offer_counters.usages + 1`,
[offerId],
);
// Record usage
await trx.query(
`INSERT INTO offer_usages (offer_id, user_id, order_id, used_at)
VALUES ($1, $2, $3, NOW())`,
[offerId, userId, orderId],
);
await trx.commit();
return { success: true };
} catch (e) {
await trx.rollback();
return { success: false, error: 'Failed to reserve offer' };
}
}
async release(offerId: string, orderId: string): Promise<void> {
// Decrement counter on order cancellation
await this.db.tx(async (trx) => {
await trx.query(
`UPDATE offer_counters
SET usages = GREATEST(0, usages - 1)
WHERE offer_id = $1`,
[offerId],
);
await trx.query(
`DELETE FROM offer_usages
WHERE offer_id = $1 AND order_id = $2`,
[offerId, orderId],
);
});
}
}
// Race condition scenario:
// User A and User B both validate the last available slot
// Server-side: SELECT ... FOR UPDATE serializes the writes
// One succeeds, one gets 'USAGE_LIMIT_REACHED'
Caching Strategy Comparison
Strategy
Latency
Freshness
Complexity
No cache (DB per call)
20-50ms
Always fresh
Simple
Client memory cache (30s TTL)
<1ms
Stale up to 30s
Low — in-memory LRU
Redis counter cache
1-3ms
Sub-second invalidation
Moderate — Redis infra
Pessimistic lock (FOR UPDATE)
10-50ms (queued)
Always fresh, serialized
High — transaction + lock
Pre-Validation at Cart Change
When the cart changes (item added, quantity changed, item removed), all currently applied offers should be re-validated silently in the background. An offer that was valid for a $100 cart might no longer apply when the total drops below the minimum purchase amount. If a re-validation fails, the UI should softly remove the offer and show a warning — not surprise the user at the payment screen. This is a batch validation endpoint that checks all applied offers at once.
Key Insight
The silent re-validation on cart change is what separates production-grade systems from prototypes. A user who adds an item, applies a code, then removes the item that made the minimum-purchase condition should see the offer automatically deactivate — not proceed to checkout thinking they have a discount that the server will reject. The batch validation endpoint should return a list of { offerId: string, valid: boolean } pairs that the client merges into its state.
10. Key Takeaways
If you remember only a few things from this article, make them these:
Client cache with cart fingerprint
Cache validation results in-memory with 30s TTL. Include cart fingerprint in the key so cache auto-invalidates when the cart changes. 50-entry LRU cap prevents memory leaks.
Server is the single source of truth
Every offer must pass the server validation engine regardless of client cache state. The server checks dates, usage limits, conditions, and calculates the authoritative discount.
Use pessimistic locking for usage counters
SELECT ... FOR UPDATE prevents two users from claiming the last available slot. The transaction serializes writes and the second transaction sees the updated counter.
Design structured error codes, not strings
Return structured error codes (OFFER_EXPIRED, USAGE_LIMIT_REACHED) from the server. The client maps codes to localized messages. This enables multi-language support without touching the backend.
Re-validate silently on cart change
When the cart changes, batch-check all applied offers. Remove invalid offers gracefully and warn the user before they reach payment. Prevents checkout-time surprises.
Exclusivity groups prevent combinatorial explosion
Group competing offers into exclusivity groups and pick the best discount per group. Stack the winners. This avoids the unbounded combinatorics of evaluating every subset.