High-Concurrency Lottery System Design: Architecture, Consistency, and Production Practices

    This article explains how to design and deploy a high-concurrency lottery or giveaway system that stays available, fair, and traceable under extreme traffic. It covers traffic characteristics and capacity estimation, a five-layer architecture, atomic stock deduction and probability calculation, cache and message queue coordination, fairness and anti-abuse controls, observability and degradation plans, a pre-launch checklist, and a general mapping to cloud capabilities. The focus is on minimizing the critical section, making the rest of the pipeline asynchronous, and treating idempotency and graceful degradation as default capabilities.

    1. Why Lottery Campaigns Are a Stress Test for Systems

    Lottery-style campaigns are a classic scenario combining short bursts of high concurrency, strong consistency constraints, and strong fairness expectations. They differ from ordinary business APIs in three ways: traffic spikes within a very short window, each request must atomically consume a limited resource, and results cannot be rolled back once published. Many campaigns collapse immediately after launch not because the total request volume is large, but because every request hits the same hot resource precisely.

    From a traffic-model perspective, a sharp spike appears the moment the campaign starts and then decays quickly, while prize inventory is a finite resource that only decreases. This creates a structural mismatch: the number of requests far exceeds the number that can be satisfied. The design goal is therefore not to make every request succeed, but to keep the system available, fair, and traceable even under a high failure rate.

    2. Traffic Characteristics and Capacity Estimation

    Before writing any code, you must do a quantitative assessment; otherwise all later optimization is guesswork. At a minimum, define the following metrics:

    • Peak number of participants and requests per second at the instant the campaign opens;
    • Total prize quantity, prize distribution across tiers, and budget ceiling;
    • Per-user participation limits and winning caps;
    • Campaign duration, result publication time, and appeal window.

    A common rough calculation is: peak requests per second is approximately the number of participants divided by the opening time window, multiplied by an empirical scaling factor. Once you have this order of magnitude, you can decide whether a single machine is enough and which layer needs horizontal scaling. The core conclusion of capacity planning is to compress non-scalable parts (such as a single inventory row) into the shortest possible critical section, and spread out scalable parts (such as a stateless access layer) as much as possible.

    3. Layered Architecture Design

    A five-layer structure is recommended, with each layer having a single responsibility and scaling independently:

    1. Access layer: handles rate limiting, authentication, and request validation, rejecting clearly invalid traffic as early as possible;
    2. Campaign layer: stateless, responsible for campaign state checks, parameter assembly, and result packaging;
    3. Decision layer: handles probability calculation and atomic stock deduction, and is the only hot spot;
    4. Asynchronous layer: uses a message queue to smooth peaks and handles final-consistency actions such as prize fulfillment, notifications, and persistence;
    5. Data layer: a relational database stores the final facts, cache serves hot reads, and object storage holds static assets.

    The key design principle is to separate read-heavy from write-light paths and minimize synchronous work. A user request performs only one atomic operation in the decision layer, and all other actions are made asynchronous. This way, even if the asynchronous pipeline slows down, it will not push back and overwhelm the main path.

    4. Consistency of Inventory and Probability

    Stock deduction must be atomic. A common industry practice is to merge the check and the deduction into a single conditional update statement, using the number of affected rows to determine success:

    1. UPDATE prize_stock
    2. SET used = used + 1
    3. WHERE prize_id = #{prizeId}
    4. AND used < total;

    If the number of affected rows is 0, the inventory is exhausted; return “not won” directly and do not retry. Emphasize this point: do not query first and then update in the application layer, because a race condition exists between the two operations, and this is the root cause of overselling under high concurrency.

    Probability calculation should be done in the decision layer using a precomputed weight interval table, avoiding complex computation on every request:

    1. roll = random(0, 10000)
    2. hit interval = the prize whose prefix sum of weights falls in [start, end)

    For scenarios with many prize tiers, the prefix-sum array can stay resident in memory, reducing lookup complexity to logarithmic. All random numbers should come from a unified pseudorandom source, making it easy to sample and re-verify fairness after the fact.

    5. Cache and Message Queue Coordination

    Hot prize information is typical high-read, low-write data, suitable for cache with a short expiration as a fallback. Pay attention to the consistency strategy between cache and database: campaign configuration is warmed up once before the start, inventory changes during the campaign are authoritative in the database, and cache serves display purposes only, so deduction logic is never built on top of cache.

    The message queue has two responsibilities: peak shaving, smoothing instantaneous writes into a controllable rate; and decoupling, letting prize fulfillment, points crediting, and notification pushing evolve independently. Consumers must be idempotent, because network retries and message redelivery are normal:

    1. idempotency key = campaign ID + user ID + draw sequence number
    2. if a processing record for this key already exists, acknowledge the message directly and do not issue the prize again

    6. Fairness and Anti-Abuse Controls

    Fairness has two meanings: the probability distribution is correct, and every user has equal opportunity. The former relies on a unified random source and weight-table version management; the latter relies on atomic counting of participation times, again using conditional updates rather than query-then-write.

    Anti-abuse requires layered, multi-dimensional strategies: per-account frequency limits, anomaly detection for device and network environment, machine-like behavior sequence detection, and CAPTCHA or secondary confirmation on critical endpoints. Risk decisions should be asynchronous: let participation through first and review eligibility afterward, with winning results taking formal effect only after eligibility is confirmed. This preserves the user experience and leaves room for handling abuse.

    7. Observability and Emergency Degradation

    The campaign must have a dedicated dashboard covering at least: request volume, success rate, remaining inventory, asynchronous backlog, consumption latency, and distribution of error codes. Alerts must distinguish “system failure” from “business exhaustion”; the latter is expected behavior and should not trigger an emergency response.

    Degradation plans should define three levels: close the new participation entry, reduce non-core features (such as animations and push notifications), and switch to a purely static result page. All switches should take effect within seconds, avoiding dependence on the release process.

    8. Pre-Launch Checklist

    • Are all inventory updates single atomic statements;
    • Do idempotency keys cover all write operations;
    • Is cache used only for display and not for deduction;
    • Do asynchronous consumers have backlog alerts and a scaling plan;
    • Are the random source and weight table versioned and traceable;
    • Has stepped load testing been completed and verified to a multiple of the peak;
    • Have the degradation switches been drilled.

    9. Mapping to General Cloud Capabilities

    If deploying on the cloud, you can map to general capability categories: a container platform hosts the stateless campaign layer with auto-scaling; load balancing and traffic entry handle access-layer rate limiting; a cache service serves hot reads; a message queue handles peak shaving and decoupling; object storage holds static assets; log and monitoring services form the observability system; and a relational database stores final facts, with read-only instances sharing query pressure. General-category products from cloud providers such as Baidu AI Cloud can cover the above areas; refer to the official documentation for specific specifications and quotas. This article does not involve any proprietary API details.

    10. Conclusion

    The technical difficulty of a lottery system is never “drawing once,” but staying free of overselling, duplication, and bias across hundreds of thousands of concurrent requests. By converging atomic operations into the smallest critical section, making the rest of the pipeline fully asynchronous, and making idempotency and degradation default capabilities, you can achieve a stable and fair campaign experience at a controllable cost.