Designing High‑Performance Coupon Codes with Bit‑Level Encoding

This article explains how to design scalable, collision‑free coupon codes by using a custom binary layout, bit‑field allocation, checksum validation, obfuscation, Base62 encoding, and provides complete Java‑style algorithms and database schema for production use.

Lin is Dream
Lin is Dream
Lin is Dream
Designing High‑Performance Coupon Codes with Bit‑Level Encoding

In everyday transaction systems such as Alipay, WeChat, Taobao, or food‑delivery platforms, coupons are ubiquitous. The author, who has long participated in bank and marketing system development, outlines the three lifecycle stages of coupons—production, distribution, and redemption—and focuses on the design of bulk coupon number generation.

What is the structure of a coupon number?

How can the coupon number structure be customized?

How to prevent coupon codes from being forged?

How should the database tables be designed?

1. Coupon Structure

Random strings (e.g., UUID) are unsuitable for production‑grade coupon codes for three reasons:

No order: Completely random strings lack any predictable sequence, forcing frequent database duplicate checks and increasing system load.

No embedded information: Random codes reveal no activity or batch data, making reverse lookup impossible.

Low generation efficiency: Under high concurrency, random generation easily collides, leading to unstable performance.

Therefore, production‑grade coupon codes are typically designed using bit‑level fields .

1. Bit‑field design

A bit is the smallest data unit in a computer; eight bits form a byte. By allocating bits to different parts—such as time, machine ID, and sequence—you can control the range, ensure uniqueness, and maintain natural ordering. This approach mirrors many unique ID generation schemes.

2. Advantages of bit‑fields

Compared with random strings, bit‑fields can carry hidden information (e.g., version, activity ID, batch ID, sequence) without being visible to users. They are naturally ordered, enable fast indexing, and can embed security data (MAC, salt) for future extensions.

The final coupon code is generated by: custom binary concatenation → large integer → Base62 encoding → fixed‑length string (e.g., 30 characters) .

2. Custom Binary Layout

A complete coupon number consists of the following fields: version, activity ID, batch ID, sequence, and checksum.

1. Custom fields

Version: Used for system upgrades; typically fixed at v1.

Activity ID: Identifies the marketing activity (e.g., Double 11, Children’s Day).

Batch ID: Allows multiple issuance batches within the same activity, facilitating inventory tracking.

Sequence: Guarantees uniqueness per coupon; often generated via Redis auto‑increment or a distributed ID generator such as Snowflake.

Checksum: A short signature derived from the previous fields and a secret key, used to reject forged codes before they reach the database.

2. Coupon code capacity

The example allocates 4 bits for version, 24 bits for activity ID, 12 bits for batch ID, 20 bits for sequence, and 4 bits for checksum, totaling 64 bits (fits in a Java long).

| version(4) | activityId(24) | batchId(12) | seq(20) | checksum(4) |

3. Checksum and Obfuscation

The checksum is calculated as (raw64 ^ secret) & 0xF, producing a 4‑bit signature that quickly filters illegal codes.

long raw = ((long) version & 0xF) << 60
            | ((long) activityId & 0xFFFFFF) << 36
            | ((long) batchId & 0xFFF) << 24
            | ((long) seq & 0xFFFFF) << 4;
long checksum = (raw ^ secret) & 0xF;
raw |= checksum;

To prevent external reverse‑engineering, the raw data is obfuscated with a multiplication constant MUL (odd) and an XOR constant XORK:

long perm = (raw64 * MUL) ^ XORK; // reversible obfuscation

The obfuscated value is then encoded with Base62 to produce the final user‑visible coupon string.

String code = Base62.encode(perm);

4. Generation Demo

Example constants:

secret = 0xA5A5A5A5A5A5A5A5
MUL = 0x9E3779B97F4A7C15

(odd) XORK = 0xC3A5C85C97CB3127 Base62 charset:

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

Given version=1, activityId=1, batchId=1, seq=1, the algorithm produces the 11‑character coupon 54qkCv1w1AO. For seq=2, the coupon becomes 2HYmzNkLPFc, demonstrating that coupons from the same activity and batch appear completely different.

5. Database Design

Two tables are defined: coupon_batch for batch metadata and coupon_code for individual coupons.

CREATE TABLE `coupon_batch` (
  `id` BIGINT NOT NULL COMMENT 'Batch primary key',
  `activity_id` BIGINT DEFAULT NULL COMMENT 'Associated activity',
  `batch_code` VARCHAR(32) DEFAULT NULL COMMENT 'Batch identifier',
  `total_count` INT DEFAULT NULL COMMENT 'Planned issuance quantity',
  `issued_count` INT DEFAULT NULL COMMENT 'Already issued quantity',
  `created_at` DATETIME DEFAULT NULL COMMENT 'Creation time',
  `status` TINYINT DEFAULT NULL COMMENT '0=active, 1=ended',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Coupon batch table';

CREATE TABLE `coupon_code` (
  `id` BIGINT NOT NULL COMMENT 'Primary key',
  `code` VARCHAR(16) NOT NULL COMMENT 'Base62 coupon code',
  `activity_id` BIGINT DEFAULT NULL COMMENT 'Redundant activity ID',
  `batch_id` BIGINT DEFAULT NULL COMMENT 'Batch ID',
  `seq` INT DEFAULT NULL COMMENT 'Sequence number',
  `checksum` TINYINT DEFAULT NULL COMMENT 'Local checksum',
  `status` TINYINT DEFAULT NULL COMMENT '0=unused,1=used,2=expired',
  `issued_to` BIGINT DEFAULT NULL COMMENT 'User ID who received the coupon',
  `issued_at` DATETIME DEFAULT NULL COMMENT 'Issuance time',
  `redeemed_at` DATETIME DEFAULT NULL COMMENT 'Redemption time',
  `created_at` DATETIME DEFAULT NULL COMMENT 'Creation time',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_code` (`code`) COMMENT 'Unique coupon code index',
  INDEX `idx_batch` (`batch_id`) COMMENT 'Batch ID index',
  INDEX `idx_status` (`status`) COMMENT 'Status index'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Coupon code table';

The full generation workflow is: iterate over seq for a given activityId and batchId, compute checksum, apply the reversible obfuscation, encode with Base62, and batch‑insert the results into coupon_code using asynchronous workers.

In summary, each seemingly random coupon string is actually a carefully crafted 64‑bit value that encodes version, activity, batch, sequence, and a short signature, providing uniqueness, ordering, and security for large‑scale marketing systems.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Code Generationdatabase designCouponbit encoding
Lin is Dream
Written by

Lin is Dream

Sharing Java developer knowledge, practical articles, and continuous insights into computer engineering.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.