How to Design a High-Concurrency Interactive Lottery System: Architecture and Practice

    This article covers the architecture of an interactive lottery system built to handle traffic spikes during user reward campaigns. It explains gateway rate limiting, atomic prize inventory deduction with Redis and Lua, multi-layer anti-fraud controls, and asynchronous prize distribution backed by reliable messaging to keep data consistent.

    On community forums and online platforms, reward lotteries are a common way to boost activity and user retention once a platform reaches a milestone, such as tens of thousands of active users. These campaigns often generate a sudden flood of traffic in a very short period. For developers, the technical challenge is building a lottery system that handles high concurrency while keeping data accurate and resisting cheating. This article examines the practice of building an interactive lottery system from three angles: system architecture, inventory management, and risk control.

    1. Core Challenges of a High-Concurrency Lottery System

    In the first few seconds after a lottery starts, the system can receive dozens or even hundreds of times its normal request volume. This instant spike creates three core challenges:

    1. Availability: A sudden surge in concurrent requests can exhaust the database connection pool or server threads, which may trigger a system-wide cascading failure.
    2. Data accuracy: When many threads deduct prize inventory at the same time, the system must strictly prevent overselling (more winners than available prizes) and missing prizes (winners who never receive their prize).
    3. Fairness and security: Lottery endpoints are easy targets for bot scripts and automation tools. The system needs strict anti-abuse and risk control measures to protect legitimate users.

    2. Layered Architecture and Decoupled Design

    To address these challenges, the lottery system should use a layered architecture and separate static content from dynamic requests. Core logic should be decoupled from non-core logic.

    2.1 Access and Gateway Layer

    At the entry point, configure strict rate limiting. A gateway can apply rate limits based on the token bucket or leaky bucket algorithm, with QPS thresholds set per IP address, per user, and for the global endpoint. When requests exceed a threshold, the gateway returns a friendly message such as “The event is very busy, please try again later.” This keeps invalid requests from reaching the business services.

    2.2 Business Service Layer

    The service layer uses a microservices architecture and splits the system into several independent modules:

    • Eligibility service: Verifies the user’s login status, points balance, or task completion status.
    • Lottery core service: Runs the lottery algorithm and inventory deduction. This is the most performance-sensitive part of the system.
    • Risk control service: Runs independently and connects to the risk engine to analyze user behavior.
    • Prize distribution service: Handles the asynchronous persistence of winning records and the delivery of physical or virtual prizes.

    2.3 Storage Layer

    The system uses a multi-tier storage architecture. A distributed cache, such as a Redis cluster, absorbs the bulk of the read and write load and serves as the primary store for hot data. A relational database, such as MySQL, serves as the final persistence layer. A message queue (MQ) decouples the core lottery path from the prize distribution path so they run asynchronously.

    3. Inventory Deduction and Overselling Prevention

    In high-concurrency scenarios, the traditional approach of deducting inventory with database row locks (SELECT ... FOR UPDATE) creates serious performance bottlenecks. A better practice is to move inventory into a distributed cache and rely on the cache’s atomic operations to ensure concurrency safety.

    When deducting inventory in the cache, avoid the non-atomic “check, then deduct” pattern. A Lua script can wrap the stock check and the deduction into a single atomic operation executed by Redis. Redis runs Lua scripts serially, which eliminates overselling caused by concurrent requests.

    The following is a simplified inventory deduction Lua script:

    1. -- KEYS[1]: Key of the prize inventory
    2. -- ARGV[1]: Quantity to deduct (usually 1)
    3. local stock = tonumber(redis.call('GET', KEYS[1]))
    4. local deduct_num = tonumber(ARGV[1])
    5. if stock == nil then
    6. return -1 -- Inventory has not been initialized
    7. end
    8. if stock >= deduct_num then
    9. redis.call('DECRBY', KEYS[1], deduct_num)
    10. return 1 -- Deduction succeeded
    11. else
    12. return 0 -- Insufficient inventory
    13. end

    With this script, the system can complete the inventory check and deduction in milliseconds, even under heavy concurrent load. A return value of 1 means the user won and the inventory was deducted. A return value of 0 means all prizes have been claimed.

    4. Risk Control and Anti-Abuse Design

    Lottery campaigns often attract people who exploit promotions for personal gain, sometimes using scripts or multiple accounts. The system needs a multi-dimensional, multi-layer risk control model.

    4.1 Static Rule Filtering

    Before a request enters the lottery logic, apply strict static checks:

    • Frequency control: Use Redis to record request rates and limit how many lottery attempts a user can make in a given time window, for example, one attempt per second.
    • Device and IP limits: Set thresholds on the total requests from a single device fingerprint or IP address. When a threshold is exceeded, trigger a CAPTCHA challenge or block the request.
    • Eligibility filtering: Use a Bloom filter to quickly screen out users who do not meet the requirements, such as accounts registered too recently or accounts that have not completed identity verification. This keeps these requests from putting load on the cache layer.

    4.2 Dynamic Behavior Analysis

    For high-value prizes, the system should add a machine learning risk model. The model collects behavioral data, such as account registration time, historical activity, time spent on the page, and mouse movement patterns, and uses it to calculate a risk score. Requests with abnormal scores can be delayed or rejected.

    5. Data Consistency and Asynchronous Prize Distribution

    A successful inventory deduction in the cache does not complete the process. The system must still write winning records to the database and may need to call external services to issue coupons or ship physical prizes. These steps take time and can fail, so they must never run synchronously in the core lottery path.

    5.1 Decoupling with a Message Queue

    After the cache deducts inventory successfully, the lottery service immediately sends a winning message to the message queue. The message contains the user ID, prize ID, timestamp, and other relevant fields. The lottery API can then return the result to the user, which completes the core path.

    5.2 Eventual Consistency

    The downstream prize distribution service subscribes to the message and handles database persistence and prize delivery. To prevent missing prizes caused by lost messages, the system should use a reliable messaging mechanism:

    • Local message table: Write the winning record to a local message table in the same transaction as the inventory deduction. A scheduled task then polls the table and sends the messages to the MQ, which ensures no message is lost.
    • Idempotent processing: The distribution service must check for idempotency when it processes each message, for example, by using a unique index or a Redis distributed lock. This prevents duplicate consumption from giving one user multiple prizes.

    Summary

    Building a high-concurrency, highly available interactive lottery system tests a developer’s architectural skills across the board. Gateway rate limiting filters out invalid traffic. Distributed caching and Lua scripts solve the problem of concurrent inventory deduction. Layered risk control helps keep the campaign fair. A message queue decouples the asynchronous steps and provides eventual consistency. These approaches are widely recognized as best practices, and mastering them prepares developers for the technical demands of operational campaigns and for building more complex, highly available business systems.