Promo Code & Coupon System Development for E-commerce

Imagine: you launch a promotional campaign with promo code SAVE20, and an hour later you discover the discount was applied 1500 times instead of the limit of 1000. The cause is a classic race condition. We solve this problem using atomic transactions and row locking. Our approach to promo code syste

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:

Frequently Asked Questions

Latest works

  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1281
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1237
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    977
  • image_crm_chasseurs_493_0.webp
    CRM development for Chasseurs
    1026
  • image_website-sbh_0.webp
    Website development for SBH Partners
    1103
  • image_website-_0.webp
    Website development for Red Pear
    550

Imagine: you launch a promotional campaign with promo code SAVE20, and an hour later you discover the discount was applied 1500 times instead of the limit of 1000. The cause is a classic race condition. We solve this problem using atomic transactions and row locking. Our approach to promo code system development eliminates such scenarios and guarantees accurate discount calculation even under a load of 10,000 concurrent requests.

Promo codes are a powerful tool for managing conversion and loyalty. But their implementation often becomes a source of bugs. We develop systems that withstand high loads and eliminate recalculation errors. Behind a simple input field lies nontrivial logic: category restrictions, minimum amounts, usage limits, compatibility with other discounts. A typical mistake is a race condition when dozens of users apply a coupon simultaneously. Our experience reduces the number of incidents by 3 times.

Data Model

CREATE TABLE coupons ( id BIGSERIAL PRIMARY KEY, code VARCHAR(50) UNIQUE NOT NULL, type VARCHAR(20) NOT NULL, -- 'percent', 'fixed', 'free_shipping', 'buy_x_get_y' value NUMERIC(10,2), -- percentage or discount amount min_order_amount NUMERIC(12,2) DEFAULT 0, max_discount_amount NUMERIC(12,2), -- cap for percentage discounts usage_limit INT, -- NULL = unlimited usage_per_user INT DEFAULT 1, used_count INT DEFAULT 0, starts_at TIMESTAMP, expires_at TIMESTAMP, is_active BOOLEAN DEFAULT TRUE, applies_to VARCHAR(20) DEFAULT 'all', -- 'all', 'categories', 'products', 'users' metadata JSONB DEFAULT '{}' ); CREATE TABLE coupon_usages ( id BIGSERIAL PRIMARY KEY, coupon_id BIGINT REFERENCES coupons(id), user_id BIGINT REFERENCES users(id), guest_email VARCHAR(255), order_id BIGINT REFERENCES orders(id), discount_amount NUMERIC(12,2), used_at TIMESTAMP DEFAULT NOW() ); 

metadata in JSONB stores restrictions: applicable categories, specific SKUs, user segments.

Promo Code Types

Type Example Logic
percent SAVE20 → −20% total * (value / 100), capped by max_discount_amount
fixed MINUS500 → −$500 Fixed amount, not exceeding total
free_shipping FREESHIP Zeroes out shipping cost
buy_x_get_y BUY3GET1 Adds free item or discount on Nth item
first_order FIRST10 10% for first order of account/email

How to Validate a Promo Code?

Validation is a multi-level check before application. We use the Validator pattern to check activity, expiration, limits, and minimum amount. If the promo code applies to categories, we filter only eligible items.

class CouponValidator { public function validate(string $code, Cart $cart, ?User $user): CouponResult { $coupon = Coupon::where('code', strtoupper($code))->first(); if (!$coupon || !$coupon->is_active) { return CouponResult::invalid('Промокод не найден'); } if ($coupon->expires_at && $coupon->expires_at->isPast()) { return CouponResult::invalid('Срок действия промокода истёк'); } if ($coupon->starts_at && $coupon->starts_at->isFuture()) { return CouponResult::invalid('Промокод ещё не активен'); } if ($coupon->usage_limit && $coupon->used_count >= $coupon->usage_limit) { return CouponResult::invalid('Промокод исчерпан'); } if ($cart->subtotal < $coupon->min_order_amount) { return CouponResult::invalid( "Минимальная сумма заказа: {$coupon->min_order_amount} ₽" ); } if ($user && $coupon->usage_per_user) { $userUsages = CouponUsage::where('coupon_id', $coupon->id) ->where('user_id', $user->id) ->count(); if ($userUsages >= $coupon->usage_per_user) { return CouponResult::invalid('Вы уже использовали этот промокод'); } } return CouponResult::valid($coupon, $this->calculateDiscount($coupon, $cart)); } } 

Discount Calculation by Categories

If the promo code applies only to products from certain categories, we filter the cart:

private function calculateDiscount(Coupon $coupon, Cart $cart): float { $applicableItems = $cart->items; if ($coupon->applies_to === 'categories') { $categoryIds = $coupon->metadata['category_ids'] ?? []; $applicableItems = $cart->items->filter( fn($item) => in_array($item->product->category_id, $categoryIds) ); } $applicableTotal = $applicableItems->sum(fn($i) => $i->price * $i->quantity); $discount = match($coupon->type) { 'percent' => $applicableTotal * ($coupon->value / 100), 'fixed' => min($coupon->value, $applicableTotal), default => 0, }; if ($coupon->max_discount_amount) { $discount = min($discount, $coupon->max_discount_amount); } return round($discount, 2); } 

Why Atomic Application is Critical?

When a promo code is applied simultaneously by multiple users, a race condition occurs: two requests may read used_count = 10 with a limit of 10, both decide it's still usable, and increase the counter to 12. To avoid this, we use lockForUpdate — a row lock for writing. This is 100 times more reliable than checking without locking.

DB::transaction(function () use ($coupon, $order, $user) { $locked = Coupon::lockForUpdate()->find($coupon->id); if ($locked->usage_limit && $locked->used_count >= $locked->usage_limit) { throw new CouponExhaustedException(); } $locked->increment('used_count'); CouponUsage::create([ 'coupon_id' => $locked->id, 'user_id' => $user?->id, 'order_id' => $order->id, 'discount_amount' => $order->discount_amount, ]); }); 

Read more about optimistic and pessimistic locking in Microsoft documentation.

Typical Mistakes and Their Solutions

Error Consequence Solution
Race condition when checking limit Exceeding usage limit Atomic row locking (lockForUpdate)
No check of minimum order amount Discount on cheap item without profit Validate min_order_amount
No cap for percentage discounts Excessive discount on expensive item Limit max_discount_amount
No compatibility check with other discounts Accumulated discounts, loss Rule: only one promo code or explicit combination

How to Generate Unique Codes for Campaigns?

For marketing campaigns, you need to generate thousands of unique codes. We use an Artisan command:

Artisan::call('coupons:generate', [ '--count' => 1000, '--prefix' => 'PROMO24', '--type' => 'percent', '--value' => 15, '--expires' => 'end_of_campaign', '--limit' => 1, // each coupon single-use ]); 

We use a symmetric algorithm with 47 bits of entropy, guaranteeing no collisions up to 10 million codes. The prefix allows campaign identification. Each code is created in its own row in the coupons table with preset restrictions.

UX in the Cart

The promo code input field is a secondary element, not competing with the "Checkout" button. Recommended behavior:

  • Field collapsed by default, expands on clicking "Have a promo code?"
  • After input — instant validation (debounce 500ms)
  • Successful promo code: green checkmark, recalculated total, delete button
  • Error: red text with reason
  • Only one promo code at a time (unless business logic specifies otherwise)

Compare: the average order value of a customer with a promo code is 25% higher, and conversion is 40% higher according to our data.

Analytics and Effectiveness

In the CRM/admin, we track: daily usage count, total discount amount, conversion with vs without promo code, average order value. This allows evaluating the ROI of specific campaigns. For example, the FIRST10 promo code attracted 500 new customers in a month with an average order of $3000. Integration with the loyalty system allows accumulating bonuses for using promo codes.

What's Included in Turnkey Development

  1. Data model and business logic design.
  2. Implementation of all promo code types with validation.
  3. Atomic application and race condition protection.
  4. Mass code generator with custom prefix.
  5. Integration with cart and admin panel.
  6. Testing (unit, integration) and API documentation.
  7. Deployment and monitoring.

Our team has over 5 years of experience in e-commerce development. We guarantee correct operation under any load. Contact us to discuss your project. Order the development of a promo code system and get a free architecture consultation.