Designing a High‑Concurrency Red Packet System with Atomic CAS Operations

This article explains how to generate red packets, calculate random amounts, and handle user grabbing and opening actions while ensuring high‑concurrency safety using atomic CAS operations in a cache to prevent oversubscription.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
Designing a High‑Concurrency Red Packet System with Atomic CAS Operations

Red Packet Generation

When a red packet is created, its ID and quantity are stored in the database and also placed in a cache.

User Interaction

Grabbing a red packet consists of two actions: the "grab" step determines whether the user obtains eligibility, and if successful, the "open" step calculates the exact amount, records the transaction flow, and credits the user's account.

Amount Calculation Method

The amount is random, ranging from 0.01 to twice the remaining average value. For example, if 100 CNY is split into 10 packets, the average is 10 CNY; each packet’s amount varies between 0.01 CNY and 20 CNY. If the first three packets have already taken 40 CNY, the remaining 60 CNY for 7 packets will be between 0.01 CNY and (60/7 × 2) ≈ 17.14 CNY.

Red packet amount calculation
Red packet amount calculation

Ensuring Safety Under High Concurrency

The "grab" action reduces the remaining packet count by one. This decrement operation is atomic, implemented with a cache CAS (compare‑and‑swap) mechanism to guarantee uniqueness.

CAS works by allowing a write only if the value read earlier has not been modified by another process. For instance, if the remaining count is 10 and many users attempt to grab simultaneously, CAS ensures that only one request successfully decrements the count at a time.

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.

BackendalgorithmCASred packet
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

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.