Building a Gift Certificate System for E-Commerce

Gift certificates are a popular loyalty tool, but their implementation in e-commerce is full of pitfalls. A typical self-written system suffers from **race condition**: when two users attempt to apply the same code simultaneously, the balance can go negative. Or the remaining balance is lost after p

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_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1414
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1284
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    980
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1240
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    982
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    994

Gift certificates are a popular loyalty tool, but their implementation in e-commerce is full of pitfalls. A typical self-written system suffers from race condition: when two users attempt to apply the same code simultaneously, the balance can go negative. Or the remaining balance is lost after partial debiting, and codes are easy to brute-force. We solve these problems at the architecture level using PostgreSQL row locking and cryptographically strong generation. In 10+ years in e-commerce, we have implemented over 50 certificate systems—from simple fixed denominations to complex reusable ones with refunds and promo campaigns. In this article, we'll break down the key technical solutions that guarantee balance integrity and user convenience.

Supported Certificate Types

Type Nominal Source Usage
Fixed 500, 1000, 2000 RUB Sold or promo Single-use or multi-use
Custom Any amount Purchase or manual issuance Multi-use with remaining balance
Promo Set by store Automatic (birthday, loyalty) Adjustable expiration

Why Atomic Debiting Is Fundamental

Without row locking, two requests could simultaneously read a balance of 1000 RUB and debit 900 RUB each, leaving -800 RUB. Our code prevents this via lockForUpdate() within a transaction:

public function apply(string $code, Order $order, float $maxAmount): CertificateApplication { return DB::transaction(function () use ($code, $order, $maxAmount) { $cert = GiftCertificate::lockForUpdate() ->where('code', $code) ->where('is_active', true) ->where(fn($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now())) ->firstOrFail(); if ($cert->balance <= 0) { throw new CertificateExhaustedException($code); } $amountToUse = min($cert->balance, $maxAmount); $balanceBefore = $cert->balance; $cert->decrement('balance', $amountToUse); if ($cert->balance == 0) { $cert->update(['is_active' => false]); } GiftCertificateUsage::create([ 'certificate_id' => $cert->id, 'order_id' => $order->id, 'amount_used' => $amountToUse, 'balance_before' => $balanceBefore, 'balance_after' => $cert->balance, ]); return new CertificateApplication($cert, $amountToUse); }); } 

Every call to the apply method is an atomic operation. If two attempts come simultaneously, the second waits for the first to complete. This is the only way to guarantee balance integrity in a high-load store. According to PostgreSQL documentation, SELECT ... FOR UPDATE locks the selected rows from modifications by other transactions until the current one finishes (see FOR UPDATE). In practice, with 3000+ certificate applications per day, we have not recorded a single case of balance desynchronization.

Why Log Every Debiting

The gift_certificate_usages table is an immutable log. The current balance is denormalized for speed but can always be reconstructed from the log. This protects against cache errors and enables history auditing. For example, when an order is cancelled, we restore the balance based on the last record. In 99% of cases, restoration takes less than 10 ms, even for certificates with hundreds of partial debits.

Generating Collision-Free Codes

We use an alphabet without similar-looking characters (0/O, 1/I/l)—the code is easy to type manually. 32 characters, 4 segments of 4 characters give 32^16 ≈ 10^24 combinations. This is billions of times more secure than sequential IDs: brute-forcing is impossible, collisions are eliminated.

class GiftCertificateCodeGenerator { private const ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; private const SEGMENT_LENGTH = 4; private const SEGMENTS = 4; public function generate(): string { do { $code = $this->makeCode(); } while (GiftCertificate::where('code', $code)->exists()); return $code; } private function makeCode(): string { $segments = []; for ($i = 0; $i < self::SEGMENTS; $i++) { $segment = ''; for ($j = 0; $j < self::SEGMENT_LENGTH; $j++) { $segment .= self::ALPHABET[random_int(0, strlen(self::ALPHABET) - 1)]; } $segments[] = $segment; } return implode('-', $segments); // ABCD-EF3H-K7MN-PQRT } } 

The generator checks uniqueness in the database, but the collision probability is negligible. A code looks like X9ZL-2K7W-5P4Q-8J3R. We typically generate up to 10,000 codes in a single batch—uniqueness check completes in fractions of a second.

More on the generation process We use the `random_int` library for cryptographically strong randomness. Segments are separated by hyphens for ease of entry. The length of 16 characters (4x4) is chosen as an optimal balance between security and readability. For mobile devices, a QR code is available.

Refund on Order Cancellation

When an order is returned, the balance is restored within the initial nominal value. The certificate becomes active again if its remaining balance was zero. If the certificate has expired—return policy is at the store's discretion (extend or refund in cash). We implemented this using the same locking mechanism as for debit—data consistency is guaranteed.

Purchasing a Certificate as a Product

A gift certificate is a special line item in the order. When the order is paid, the OrderPaid listener creates the certificate and sends it to the recipient. The email contains a beautiful HTML template, a QR code for quick application, and a PDF for printing. The sender's personal message is added automatically. 95% of buyers leave positive feedback about this gifting method.

Comparison: Self-Written vs Our System

Criterion Self-Written System Our Implementation
Race condition protection None PostgreSQL row locking
Code generation Sequential IDs Cryptographically strong, 10^24 combinations
Partial debiting No Atomic with logging
Refund Manual Automatic within transaction
Scalability Limited Up to 10,000 certificates/day

What's Included

  • Analysis of the store's business processes and rule configuration (categories, limits, expiration)
  • Database schema and logic design (generation, application, refunds)
  • Frontend implementation: certificate selection widget, personal cabinet with balance
  • Integration with payment gateway and email service
  • Unit test coverage (including race condition scenarios)
  • Documentation and access credentials

Get an engineer consultation: we'll assess timelines and cost for your project.

Work Stages

  1. Analysis—clarify requirements, define business rules
  2. Design—database schema, service architecture
  3. Implementation—write code, test on isolated staging
  4. Testing—load tests, verify atomicity and refunds
  5. Deployment—roll out to production, monitoring

Implementation Timelines

A complete system takes from 1.5 to 2 weeks. Timelines are refined after requirements analysis. Order a gift certificate system development — receive an engineer consultation. We'll assess your project for free. Contact us to discuss your project.