How Is a Red Envelope System Designed for High‑Concurrency?
This article breaks down the end‑to‑end design of a high‑traffic red‑envelope service, covering its three‑stage lifecycle, a fair double‑mean allocation algorithm, the need to separate grabbing from settlement, and how Redis, Lua scripts, and message queues handle massive concurrent requests.
Lifecycle of a Red Envelope
A red envelope goes through three steps: Issue (发) – set amount and count, mark the record as paid and push it to the group; Grab (抢) – when a user clicks, the system checks if they have already grabbed, whether the envelope is expired, and remaining count, using a distributed lock to ensure one‑person‑one‑grab; Settle (拆) – calculate the actual money, update balances, and send an MQ message for asynchronous payout. An additional fallback job returns unclaimed money after 24 hours.
Why Separate "Grab" and "Settle"?
Hundreds of users may click simultaneously while only a few envelopes (e.g., 10) are available. If every request performed full money calculation and database writes, the DB would be overwhelmed. By filtering early in the "Grab" layer—checking duplicates, expiration, and balance—the system blocks most invalid traffic, allowing only the few successful grabs to proceed to the costly "Settle" stage.
Fair Distribution: Double‑Mean Method
The article presents two algorithms for splitting 100 CNY into 10 packets. Pure random allocation gives the first user a range (0, 100), averaging 50, and later users get progressively less, which is unfair. The recommended "double‑mean" method uses the formula:
Current Upper Limit = (Remaining Amount ÷ Remaining Count) × 2For 100 CNY / 10 packets, the first upper limit is 100÷10×2 = 20. After the first grab, 90 CNY remains for 9 packets, still 20, and so on. Each user’s expected amount is 10 CNY, removing the advantage of grabbing early. The only drawback is that, except for the last packet, each amount is less than twice the mean, which is fair but not purely random.
Handling Traffic Surges
For low traffic, direct database access suffices. When traffic scales, the database becomes the bottleneck. The solution moves hot operations to Redis: the gateway rate‑limits requests based on the total envelope count (e.g., allow 20 requests for 10 packets, drop the rest); after duplicate checks, a Lua script atomically decrements the stock in Redis; grab and settle records are written asynchronously via MQ, and payouts are processed later. If Redis fails, the system can fall back to the database. In short, high‑frequency reads/writes are handled by Redis, while persistence is delegated to MQ.
When to Compute the Amount: Pre‑calc vs Real‑time
Two options exist. Pre‑calculating during the "Issue" phase offers high performance and strong consistency, but requires extra storage, which may be prohibitive for million‑scale events. Real‑time calculation during "Settle" saves memory and suits ultra‑large activities, but introduces higher concurrency complexity and overhead. The rule of thumb: use pre‑calc for extreme performance and consistency; use real‑time for massive scale with limited memory.
Putting It All Together
The core of a red‑envelope system is "layered filtering + asynchronous fallback": separate "Grab" and "Settle" to block invalid traffic early, use a distributed lock to enforce one‑person‑one‑envelope, apply the double‑mean algorithm for fairness, and rely on Redis plus MQ to absorb traffic spikes while guaranteeing eventual consistency. Choosing pre‑calc or real‑time amount computation depends on activity size and memory budget. Master this flow and you can confidently answer interview questions on high‑concurrency backend design.
Conclusion
A seemingly simple red envelope encapsulates a full suite of high‑concurrency design patterns applicable to flash sales, coupon grabs, and limited‑time purchases.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Code Farming
Senior engineer at a top internet giant, sharing Java, AI, tech knowledge, growth insights, and interview experiences.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
