System Design Part 9 Design problems

Design Problem: Flash Sale Ticketing, and How Much Each Layer Must Turn Away When 500,000 People Chase 10,000 Seats

Bill.Lin 20 min read

System Design series Part 9-4 | Previous: Chat System | Next: Notification System | Series map

Read first: Part 7-3 Sagas and the Outbox Pattern, Part 8-5 Abuse Prevention.

Scenario and problem

The sign-up system from the series introduction: 3,000 seats and a peak of 800 writes a second, where one conditional UPDATE plus a local sold-out flag was enough. The introduction also listed option C (Redis reservation) and option D (a waiting room) for larger scale. This problem is that “larger scale”:

The platform has booked a hugely popular speaker and is holding a talk for 10,000 people.

  • 10,000 seats, a limit of 1 ticket per person
  • 500,000 people are waiting on the page before sales open, and within a few seconds of opening, most of them press the button
  • No overselling; whoever gets a seat has to pay within 10 minutes, or the seat is released
  • The sale must not affect the platform’s other features

Scale estimate

Item Estimate
Requests at the moment sales open 500,000 people press the button within 5 seconds → about 100,000 a second; with refreshes and retries, an estimated 200,000 a second
Writes that will actually succeed 10,000
Ceiling of option A from the introduction About 1,000 conditional UPDATEs a second on the hot row
Gap between requests and the ceiling 200 times
The 5 seconds when the 10,000-seat talk opens1 / 4
The 5 seconds when the 10,000-seat talk opens500k usersSign-up entryDatabase500k usersDatabase500,000 waiting10,000 seats500k usersSign-up entry200,000/sSign-up entryDatabasecond. UPDATEMax about 1,000/sSign-up entryDatabaseOther features unaffectedNo overselling
  1. Before the sale10,000 seats, a limit of 1 ticket per person. Before sales open, 500,000 people are waiting on the page, and whoever gets a seat has to pay within 10 minutes.
  2. The moment sales open500,000 people press the button within 5 seconds: about 100,000 requests a second, and with refreshes and retries, an estimated 200,000 a second.
  3. The database's ceilingThe conditional UPDATE from option A in the introduction handles about 1,000 a second on the hot row. Requests outnumber that ceiling 200 times.
  4. Other features must not sufferThe sale must not affect the platform's other features, and it must not oversell.

Of 500,000 attempts, only 10,000 will succeed. The core of the design is not making the database take 200,000 writes a second. It is rejecting requests that are bound to fail as early as possible, at every layer, so that only those 10,000 actually reach the database.

The simplest approach and its limits

Reuse option A from the introduction and add more application servers:

  • The application servers can scale horizontally, but every request ends up queuing for the lock on the same row. 200,000 requests a second hit the database, the connection pool runs dry instantly (HikariCP tuning), requests waiting for the lock time out, users retry, and the load doubles
  • Once the database is dragged down, every feature on the platform stops working, not just this talk
  • Autoscaling is too slow: from detecting the traffic rise to new instances being able to serve takes tens of seconds to a few minutes, and a flash sale is over within seconds (Stateless Services post)

Core mechanism

The funnel: how much each layer turns away

flowchart TD
    U["500,000 users<br/>about 200,000 requests a second"] --> CDN["CDN<br/>event page, sale status<br/>almost all handled at the edge"]
    CDN --> WR["Virtual waiting room<br/>admits by queue number, 2,000 people a second"]
    WR --> GW["API Gateway<br/>checks the admission token, per-user rate limit, rejects once sold out"]
    GW --> RS["Redis reservation<br/>atomic decrement in Lua, tens of thousands a second"]
    RS -->|"about 10,000 succeed"| ST[[Redis Stream]]
    ST --> DB[("MySQL<br/>final check with a conditional UPDATE<br/>kept at 1,000 a second")]
    DB --> PAY["Payment, 10-minute deadline"]
Layer In per second Let through per second How it turns requests away
CDN 200,000 Single digits (cache misses) The event page and “which number we have admitted up to” are both cacheable static responses
Virtual waiting room 500,000 people in line 2,000 people Admits by queue number; the backend’s capacity sets the admission rate
Redis reservation 2,000 About 2,000 until seats run out, 0 after Rejects immediately once sold out; per-person limit
Database About 10,000 (in total) At the consumers’ pace, 1,000 a second A conditional UPDATE does the final check

Before the sale: everything is on the CDN

  • The event page is static, and the countdown follows server time (the page gets the server time when it loads and computes the offset); you cannot trust the user’s local clock
  • “Has the sale started, which number have we admitted up to, is it sold out” is a tiny JSON document that the CDN caches for 1 second (s-maxage=1, CDN post). 500,000 clients poll every 5 seconds, which is 100,000 requests a second, yet each second the origin receives only “one request per CDN node”
  • The cache key for this endpoint must ignore query parameters; otherwise an attacker who appends ?x=<random number> can make every request go through to the origin

Virtual waiting room: controlling admission with queue numbers

The Rate Limiting post mentioned the waiting room as a way to protect user experience and fairness. Here it is built as an almost stateless design:

  1. A user who enters the page before sales open gets a queue ticket: a signed token containing the user ID, the event ID, and a queue number
  2. For people already waiting before sales open, the numbers are randomly shuffled: someone who came in an hour early has the same chance as someone who came in a second early, and bots lose their speed advantage at this step (Abuse Prevention post); people who arrive after sales open are queued behind them in order of arrival
  3. Every second, the admission controller moves “which number we have admitted up to” forward by 2,000 and writes it into the status JSON that the CDN caches
  4. When the client sees that its number has been admitted, it trades the queue ticket for an admission token: short-lived (for example 2 minutes), single-use, and bound to the user and the event

Checking a queue number only takes verifying the signature and comparing numbers; no shared state is queried. The waiting room servers can scale freely, and the admission rate is entirely up to the backend.

Why 2,000 people a second: each admitted person sends roughly one purchase request within a few seconds, and Redis reservation can handle tens of thousands a second, so 2,000 leaves a lot of headroom; the real limits are the payment flow behind it and how fast the database can absorb the writes.

Redis reservation: it turns requests away, it does not keep the books

Once the admission token checks out, the purchase request runs a Lua script in Redis that atomically:

  • Checks whether this person has already bought (per-person limit)
  • Checks whether stock is greater than 0
  • Decrements stock, records the buyer, and writes “reservation succeeded” to a Redis Stream

The three steps are in one script, so no other request can get in between, and you need no distributed lock (Distributed Locks post). Once seats run out, every request is rejected after one stock read in Redis, at very low cost; the Gateway also remembers “sold out” locally, so it does not even need to touch Redis.

But Redis is not where the books are kept. Redis replication is asynchronous: if the primary confirms a decrement and crashes before replicating it to a replica, those decrements are gone after failover, stock goes back to a higher number, and a few extra tickets may then be sold (Replication post, Redundancy and Failover post). So:

  • Redis is the filter: it turns 500,000 attempts into about 10,000
  • MySQL is the authority: when the order is created, the introduction’s conditional UPDATE ... WHERE remaining > 0 still does the final check. The few extra requests Redis let in are stopped here, and those users get “Sorry, all seats are taken”

This is the same principle as the sold-out flag in the introduction: the cache layer is only an optimization; correctness lives in the database.

Failover also causes loss in the opposite direction: the decrement, the buyer record, and the Stream message from the same script disappear together. The user’s screen already shows “processing”, but a result never arrives. So “processing” needs a timeout (for example, after 60 seconds without a result, show “You did not get a seat this time; please check your orders page”), and after the event, reconcile once more against the orders in the database.

Async writes: the database handles only about 10,000 rows

The Redis Stream consumers create orders at about 1,000 a second: 10,000 take about 10 seconds. That falls right within the hot-row ceiling estimated in the introduction, so you need no seat buckets and no different database. That is the funnel at work: when the upstream layers turn away enough, the simple approach downstream is enough.

Order creation is idempotent: (event_id, member_id) is a unique key, so when the same Stream message is processed twice, the second attempt hits the unique key and is skipped (Idempotency post). A message is acknowledged (ACK) only after processing completes. When a consumer crashes or processing fails, unacknowledged messages stay in the pending list, and a periodic job uses XAUTOCLAIM to claim messages that have been idle too long and process them again.

After the client sends the purchase request, it immediately gets “processing”, then gets the result by polling or through SSE (Real-Time Updates post).

Payment and release

Once a seat is secured, the flow is the checkout from the Saga post:

  • The order status is “awaiting payment”, with a 10-minute deadline
  • Not paid in time: cancel the order, add 1 back to the seats in the database, add 1 back to the stock in Redis, and remove the buyer record
  • The add-back in Redis has to be idempotent: the release of a given order may run only once, or stock gets inflated. Record “this order has been released” with SET NX, in the same Lua script as the stock add-back

Released seats do not need to go straight back to the crowd. A better approach is to collect them for a while and open them again at an announced time, or give them to a waitlist, so that users do not keep refreshing in the hope of catching a released seat.

Preparing before the sale

  • Scale out in advance: based on the estimate, have the waiting room, Gateway, and Redis scaled out 30 minutes before the sale opens; do not rely on autoscaling
  • Isolation: this event uses its own Redis and its own service instances, so a failure or overload does not affect the platform’s other features (Circuit Breaker and Bulkhead post)
  • Load testing: test the whole path with a traffic pattern close to the real one, especially the CDN cache key and the waiting room’s admission
  • Degradation plan: when Redis fails, the waiting room pauses admission instead of letting traffic hit the database directly

Comparing options

Option Suitable scale Cost
A. Conditional UPDATE + sold-out flag (introduction) Hundreds to a thousand a second The hot row is the ceiling
B. Seat buckets in the database Thousands a second Totals have to be summed; the last seats are unevenly spread
C. Redis reservation + async writes Tens of thousands a second Two more components; consistency between Redis and the database depends on the final check and reconciliation
D. Virtual waiting room Any scale, backend load fully under control Users have to wait; the queuing experience needs designing
Lottery (Abuse Prevention post) Any scale, load spread over the whole registration period Not “first come, first served”; the business side has to agree

The talk platform’s choice: D + C + A. The waiting room controls the rate of entry, Redis turns away requests that are bound to fail, and the database uses the simplest conditional UPDATE to guarantee no overselling. If the business can accept it, a lottery is a simpler and fairer alternative.

In Java

1. Admission tokens: issuing and verifying

java
@Component
public class AdmissionTokens {

    private final JwtEncoder encoder;
    private final JwtDecoder decoder;

    public AdmissionTokens(@Value("${flashsale.admission-key}") String base64Key) {
        SecretKey key = new SecretKeySpec(Base64.getDecoder().decode(base64Key), "HmacSHA256");
        OctetSequenceKey jwk = new OctetSequenceKey.Builder(key).build();
        JWKSource<SecurityContext> jwkSource = (selector, context) -> selector.select(new JWKSet(jwk));
        this.encoder = new NimbusJwtEncoder(jwkSource);
        this.decoder = NimbusJwtDecoder.withSecretKey(key).build();
    }

    /** Once the queue ticket's number has been admitted, issues a single-use admission token valid for 2 minutes. */
    public String issue(long memberId, long eventId) {
        Instant now = Instant.now();
        JwtClaimsSet claims = JwtClaimsSet.builder()
                .subject(Long.toString(memberId))
                .audience(List.of("flashsale:" + eventId))
                .id(UUID.randomUUID().toString())                      // jti: used to prevent reuse
                .issuedAt(now)
                .expiresAt(now.plus(Duration.ofMinutes(2)))
                .build();
        JwsHeader header = JwsHeader.with(MacAlgorithm.HS256).build();
        return encoder.encode(JwtEncoderParameters.from(header, claims)).getTokenValue();
    }

    public Jwt verify(String token, long memberId, long eventId) {
        Jwt jwt = decoder.decode(token);                               // verifies the signature and expiry
        if (!jwt.getSubject().equals(Long.toString(memberId)) || !jwt.getAudience().contains("flashsale:" + eventId)) {
            throw new AccessDeniedException("Admission token does not belong to this user or event");
        }
        return jwt;
    }
}
  • The token is bound to the user (compared with the logged-in identity) and to the event, so it is useless once transferred or taken to another event
  • “Single use” is checked with jti in the Redis reservation script; see the next section
  • Only the waiting room and the Gateway hold the HMAC key, managed as in the Encryption post

2. Redis reservation

java
@Component
public class SeatReservation {

    // KEYS[1] stock, KEYS[2] buyer set, KEYS[3] usage record of this admission token, KEYS[4] reservation stream
    // ARGV[1] member ID, ARGV[2] seconds left on the token
    private static final RedisScript<Long> RESERVE = RedisScript.of("""
            if redis.call('SET', KEYS[3], '1', 'NX', 'EX', ARGV[2]) == false then
              return -2
            end
            if redis.call('SISMEMBER', KEYS[2], ARGV[1]) == 1 then
              return -1
            end
            local stock = tonumber(redis.call('GET', KEYS[1]) or '0')
            if stock <= 0 then
              return 0
            end
            redis.call('DECR', KEYS[1])
            redis.call('SADD', KEYS[2], ARGV[1])
            redis.call('XADD', KEYS[4], '*', 'member', ARGV[1])
            return 1
            """, Long.class);

    private final StringRedisTemplate redis;

    public SeatReservation(StringRedisTemplate redis) {
        this.redis = redis;
    }

    public ReserveResult reserve(long eventId, long memberId, Jwt admission) {
        String tag = "{flashsale:" + eventId + "}";        // hash tag: every key lands in the same Redis Cluster slot
        long ttl = Math.max(1, Duration.between(Instant.now(), admission.getExpiresAt()).toSeconds());
        Long code = redis.execute(RESERVE,
                List.of(tag + ":stock", tag + ":buyers", tag + ":admission:" + admission.getId(), tag + ":reservations"),
                Long.toString(memberId), Long.toString(ttl));
        return switch (code.intValue()) {
            case 1 -> ReserveResult.RESERVED;
            case 0 -> ReserveResult.SOLD_OUT;
            case -1 -> ReserveResult.ALREADY_RESERVED;
            default -> ReserveResult.ADMISSION_USED;
        };
    }
}
  • Every key the script touches must be passed in through KEYS; the script must not build key names itself. On Redis Cluster these keys must also be in the same slot, so they all carry the {flashsale:42} hash tag. This also means that all operations for one event run on the same node, and that node has to handle the admission rate; right now that is 2,000 a second, far below its limit
  • Before the sale, write the stock into stock and check it once against the seats in the database
  • On SOLD_OUT, the Gateway remembers locally that this event is sold out, and later requests no longer call Redis

3. Async writes: the database does the final check

java
@Component
public class ReservationConsumer implements StreamListener<String, MapRecord<String, String, String>> {

    private static final Logger log = LoggerFactory.getLogger(ReservationConsumer.class);

    private final StringRedisTemplate redis;
    private final OrderCreator orders;
    private final Rejections rejections;
    private final long eventId;

    public ReservationConsumer(StringRedisTemplate redis, OrderCreator orders, Rejections rejections,
                               @Value("${flashsale.event-id}") long eventId) {
        this.redis = redis;
        this.orders = orders;
        this.rejections = rejections;
        this.eventId = eventId;
    }

    @Override
    public void onMessage(MapRecord<String, String, String> record) {
        long memberId = Long.parseLong(record.getValue().get("member"));
        try {
            orders.createOrReject(eventId, memberId);                    // idempotent
        } catch (SoldOutAtDatabaseException e) {
            rejections.notifyNotSecured(eventId, memberId);              // tell the user they missed out, remove the Redis buyer record, do not add stock back
        } catch (RuntimeException e) {
            log.warn("Failed to create order; message {} stays in the pending list for reprocessing", record.getId(), e);
            return;                                                      // no ACK
        }
        redis.opsForStream().acknowledge("order-writers", record);
    }
}

@Configuration
public class ReservationStreamConfig {

    @Bean(destroyMethod = "stop")
    StreamMessageListenerContainer<String, MapRecord<String, String, String>> reservationListener(
            RedisConnectionFactory connectionFactory, ReservationConsumer consumer,
            @Value("${flashsale.event-id}") long eventId) {
        StreamMessageListenerContainerOptions<String, MapRecord<String, String, String>> options =
                StreamMessageListenerContainerOptions.builder()
                        .pollTimeout(Duration.ofSeconds(1))
                        .build();
        StreamMessageListenerContainer<String, MapRecord<String, String, String>> container =
                StreamMessageListenerContainer.create(connectionFactory, options);
        container.receive(Consumer.from("order-writers", ConsumerName.current()),
                StreamOffset.create("{flashsale:" + eventId + "}:reservations", ReadOffset.lastConsumed()),
                consumer);
        container.start();
        return container;
    }
}

@Service
public class OrderCreator {

    private final JdbcClient jdbc;
    private final IdGenerator ids;
    private final DelayedTasks tasks;

    public OrderCreator(JdbcClient jdbc, IdGenerator ids, DelayedTasks tasks) {
        this.jdbc = jdbc;
        this.ids = ids;
        this.tasks = tasks;
    }

    @Transactional
    public void createOrReject(long eventId, long memberId) {
        long orderId = ids.next();
        try {
            jdbc.sql("""
                            INSERT INTO ticket_order (id, event_id, member_id, status, pay_deadline)
                            VALUES (:id, :e, :m, 'PENDING_PAYMENT', NOW(3) + INTERVAL 10 MINUTE)
                            """)
                    .param("id", orderId).param("e", eventId).param("m", memberId).update();
        } catch (DuplicateKeyException e) {
            return;                                                      // the same message processed again
        }
        int updated = jdbc.sql("UPDATE event SET remaining = remaining - 1 WHERE id = :e AND remaining > 0")
                .param("e", eventId).update();
        if (updated == 0) {
            // Extra requests Redis let in (for example, a decrement lost in failover) are stopped here
            throw new SoldOutAtDatabaseException(eventId, memberId);
        }
        // The payment deadline task is created in the same transaction as the order; if the order rolls back, the task does not exist either
        tasks.schedule("PAYMENT_DEADLINE", "PAYMENT_DEADLINE:order:" + orderId, "{\"orderId\":" + orderId + "}",
                Instant.now().plus(Duration.ofMinutes(10)), "ticketing-service");
    }
}
  • INSERT first and the hot row’s UPDATE last, so the lock is held for the shortest time (the LLD decision from the introduction)
  • SoldOutAtDatabaseException rolls back the transaction; the consumer catches it, tells the user they did not get a seat, and removes the Redis buyer record. Do not add the stock back in Redis, because the database has already confirmed there are no seats left
  • The payment deadline is handed to the Distributed Scheduler: the task is created in the same transaction as the order, and 10 minutes later the handler uses a conditional update to check whether payment has been made
  • Consume with a listener container, not @Scheduled plus a blocking read: without virtual threads enabled, Spring Boot’s scheduler has only one thread, and each read that blocks for 1 second delays every other scheduled job in the same application
  • The consumer group must be created before the sale (XGROUP CREATE). Reading with lastConsumed() (that is, >) only gets new messages; messages that failed without an ACK stay in the pending list and are not redelivered automatically. You need a periodic job that uses XAUTOCLAIM to claim messages that have been idle beyond a set time and process them. Consumer names must be fixed, so that after a restart a consumer can find its own pending messages again
  • The number of consumers sets the rate of writes to the database; this is the last valve protecting the database

The code above is written from the official documentation for Spring Boot 4.1, Spring Security 7.1, and Spring Data Redis 4.1, and has not been compiled or run. ConsumerName, Rejections, SoldOutAtDatabaseException, and IdGenerator are illustrative components; for the implementation of DelayedTasks, see the Distributed Scheduler post.

Pitfalls and gotchas

  • Treating Redis as the authority: decrements lost in failover cause overselling. The database needs a final check, and you reconcile once more after the event
  • “Processing” without a timeout: failover loses the reservation message too, and the user waits forever for a result
  • Lua script keys not in the same slot: the script fails outright on Redis Cluster. Use a hash tag
  • A CDN cache key that includes query parameters: an attacker adds random parameters, and every request goes through to the origin
  • Relying on the user’s local time: changing the computer’s clock shows the “Buy” button early. The button is only UI; the server decides when the sale really opens
  • Relying on autoscaling: the flash sale is over before scaling finishes
  • Clients retrying without limit: resending right after every failure multiplies the load. Put a suggested retry time in the response, and have the client retry with jittered backoff (Timeout and Retry post)
  • Adding released seats straight back into Redis: the release is not idempotent, and stock gets inflated
  • Sharing resources with other features: the flash sale uses up the shared Redis or database connection pool, and the whole platform goes down with it

Threat model

STRIDE Threat On the talk platform Defense
Spoofing Queuing with many accounts; transferring admission tokens Scalpers register thousands of accounts to raise their odds; they sell admission tokens to others Deduplicate by verified phone number or real-name identity (8-5); tokens are bound to the user
Tampering Tampering with the queue ticket’s number Changing the number to 1 Queue tickets and admission tokens are both signed; the server trusts only signed content
Repudiation Fairness disputes A user objects: “I was in line early and still did not get a seat” Keep each queue ticket’s issue time and number, plus the records of admission and reservation
Information disclosure Remaining seats and admission progress used to tune the attack Bots decide when to fire in bulk from the remaining seats Show only a coarse status (“selling fast”, “sold out”); this is not the main line of defense
Denial of service Traffic at the moment of opening; bypassing the CDN; calling the reservation API directly Random query parameters go through the cache; calling the purchase API directly without passing through the waiting room Normalize the cache key; the Gateway accepts only requests with a valid admission token; admission tokens are single-use
Elevation of privilege Abuse of admin functions Insiders change the stock or hold seats for specific accounts Stock adjustments require MFA and two-person review; every adjustment is written to the audit log

When to use it, and when not to

  • Use option A from the introduction: the peak is under a thousand a second, which is the case for most events
  • Add a waiting room: traffic far exceeds what the backend can handle, or you need a fair queuing experience
  • Add Redis reservation: after the waiting room admits people, purchase requests per second still exceed the database’s hot-row ceiling
  • Consider a lottery: the business can accept it, and you want to remove the speed race and scalping at the root
  • Do not build it all from the start: the waiting room, reservation, async writes, and reconciliation are each a component you have to operate. Estimate first, and build only when you are sure you need it

References

Comments