Preventing Inventory Overselling During Flash Sales: Designing MySQL Reservations and Redis Coordination

Preventing inventory overselling during a flash sale starts with the database operation that assigns stock to a buyer. A popular SKU can receive thousands of purchase attempts while only a few units remain. The inventory service must prevent two transactions from claiming the same unit.

The checkout path also shares inventory with seller imports, warehouse adjustments, and order cancellations. Each operation can change the quantity available for sale. The allocation rule must apply consistently across all these paths.

Engineers face three related decisions: how to protect inventory updates, how to hold stock during payment, and where to store reservation records. The concurrency method must fit the inventory model, the reservation lifecycle must account for payment delays, and the storage architecture must support the expected checkout load.

Choose a concurrency method for the inventory rule

Three MySQL concurrency methods for inventory allocation compared

Assume a product has one unit available, and two checkout transactions attempt to deduct it. The database must prevent both transactions from claiming the same unit.

For a quantity-counter model, an atomic conditional update provides a direct allocation mechanism:

UPDATE inventory
SET available_quantity = available_quantity - ?
WHERE shop_id = ?
AND product_id = ?
AND location_id = ?
AND available_quantity >= ?;

The application supplies the requested quantity in both quantity parameters and checks the affected-row count. One affected row means the update succeeded. Zero means that no inventory record met the condition. The requested quantity must be greater than zero. The application should also enforce a unique constraint on the inventory bucket identified by shop_id, product_id, and location_id. These key columns should be non-null. If the allocation model uses additional dimensions, those dimensions must also form part of the key.

The columns in the WHERE clause must identify one inventory bucket. A multi-vendor platform may need to include the shop, product, and fulfillment location in that key. The exact dimensions depend on how the platform assigns stock ownership.

Some checkout workflows must protect several records within one transaction. A locking read such as SELECT ... FOR UPDATE locks the index records encountered by the search until the transaction ends. The locking read must run inside an active transaction. This approach fits operations that must read and update related records under the same transaction. See the MySQL locking-read guide.

The query's access path controls the lock scope. Under REPEATABLE READ, a unique-index lookup using the complete unique key can lock a single index record without locking the preceding gap. A range scan can acquire next-key locks across the scanned index range. Under READ COMMITTED, ordinary locking searches generally lock index records without gap locks, subject to foreign-key and duplicate-key checks. Keep transactions short, index the columns used by locking queries, and acquire locks in a consistent order. See the MySQL transaction isolation documentation.

InnoDB can detect deadlocks and roll back a transaction. The application must retry the entire transaction when this happens. A lock-wait timeout has different default behavior: InnoDB rolls back the statement that timed out, not the entire transaction. The innodb_rollback_on_timeout changes that behavior. The application should handle these errors according to the configured rollback policy. See the MySQL deadlock documentation and InnoDB error-handling documentation.

Optimistic locking uses a version column to detect changes made after a record was read. An update succeeds only when the stored version matches the version previously read by the application. The successful update must also increment the version in the same statement:

UPDATE inventory
SET available_quantity = available_quantity - ?,
    version = version + 1
WHERE shop_id = ?
AND product_id = ?
AND location_id = ?
AND version = ?
AND available_quantity >= ?;

The application checks the affected-row count to determine whether the update succeeded. A zero-row result means the version or quantity condition was not satisfied, or the inventory bucket did not exist. The application can then reload the record and retry according to its conflict policy.

This approach suits workloads with relatively few conflicts and controlled retries. When many buyers update the same SKU row, InnoDB still serializes successful writes to that row.

Version checks detect competing updates, but they do not remove write contention on a hot row.

Use conditional updates for simple quantity rules. Use locking reads when a transaction must protect related records. Consider version checks when conflicts are infrequent and retry costs remain low.

Keep reservations consistent through payment

Reservation lifecycle showing the payment provider outside the MySQL transaction boundary

A reservation temporarily removes units from the quantity available to other buyers. The store holds those units while the payment provider processes the charge.

In a MySQL-backed reservation design, the application decrements available_quantity and creates the reservation record in the same transaction. The reservation record stores a unique identifier, quantity, status, and expiry time. If payment succeeds before expiry, the application changes the reservation status to committed. It does not decrement available_quantity again because the reservation already removed those units from availability. This transaction keeps the inventory quantity and reservation record consistent.

The two operations have separate responsibilities:

Reserve Atomically reduce available quantity and create a temporary reservation when a buyer begins marketplace checkout.

Claim: Change the reservation from active to committed after payment succeeds. Use a conditional status transition so repeated payment callbacks cannot commit the same reservation or trigger fulfillment twice.

Payment requests should use a stable idempotency key for each logical operation. If a connection fails, the application can retry the same operation with the same key and the same parameters when the provider supports idempotency. A new key identifies a separate request, which can repeat the operation and create duplicate side effects.

Payment providers expose their own idempotency and webhook behavior. For example, Stripe documents how its API handles repeated requests in its idempotent request guide. Its Checkout integration also uses server-side webhooks to report payment events. For delayed payment methods, checkout.session.completed does not necessarily confirm successful payment. The application must also handle checkout.session.async_payment_succeeded and checkout.session.async_payment_failed according to the provider's event contract.

Reservation expiry creates another case the application must handle. A payment may remain pending after its reservation expires, and another buyer may reserve the released unit before the first payment succeeds. The application must attempt to reacquire inventory under the same allocation rules before fulfilling the late payment. If stock has already been committed to another order, the store needs a recovery policy. If payment has only been authorized, the provider may support cancellation or voiding. If payment has been captured, a refund may be required. The application may also contact the customer with an alternative fulfillment option.

Expiry processing must change the reservation status and restore the released quantity in the same MySQL transaction. A conditional status transition ensures that repeated expiry jobs cannot release the same units more than once.

The payment provider operates outside the MySQL transaction. The application must handle delayed responses, repeated callbacks, and payment outcomes that arrive after checkout has ended.

Redis vs MySQL: Where reservation state belongs

Sequence of a Redis provisional hold and MySQL allocation with the uncertainty window marked

The MySQL-backed design keeps reservation records and inventory changes within one transactional boundary. A Redis-backed design can use Redis for temporary reservation coordination while MySQL remains authoritative for inventory allocation and accounting. The second design can give the reservation path additional capacity for short-lived operations, but it introduces coordination between two storage systems.

Redis supports atomic commands and server-side scripts that can combine reservation checks and updates. These operations can manage provisional holds, throttle competing requests, or coordinate access to a limited pool. Redis executes Lua scripts atomically and blocks other server activity while a script runs, so scripts should remain short. A Redis hold must not authorize an order until the authoritative inventory allocation has succeeded in MySQL. See the Redis scripting documentation.

Consider two checkout paths. One path obtains a provisional hold in Redis. Another path updates inventory directly in MySQL. If the Redis path treats its hold as a completed reservation, the MySQL path could still allocate the same stock. The final allocation check must therefore occur in MySQL, or every allocation path must use a shared coordination mechanism that enforces the same stock limit.

One approach is to create a provisional Redis hold, then attempt the corresponding inventory reservation in MySQL. The MySQL transaction conditionally reduces available quantity and records the reservation. The application confirms the reservation only after that transaction commits. If the MySQL operation fails, the provisional Redis hold must be released or allowed to expire. If the result is uncertain because the connection failed during commit, the application must check the reservation identifier in MySQL before releasing the Redis hold. A reconciliation process should detect holds and reservations left in incomplete states.

This design keeps MySQL authoritative, but every confirmed reservation still requires a MySQL allocation write. Redis can help manage admission and short-lived coordination, but it does not remove the database write needed to protect inventory. If the main bottleneck is contention on the MySQL inventory row, adding Redis does not eliminate that contention.

Inventory location adds another dimension. A reservation model that identifies stock only by product may not distinguish units held at separate fulfillment locations. The allocation key must represent the inventory pool from which the order will be fulfilled. This is particularly relevant when coordinating inventory across multiple sellers.

A quantity-counter model stores the available amount in an inventory record. An individual-unit model represents each available unit with its own record. The latter can support allocation at unit level, but maintaining a permanent row for every physical unit may create a large table for products with high stock counts.

One possible implementation uses a bounded pool of available-unit records. Reservations consume records from the pool, while a replenishment process refills it from the inventory ledger. The pool represents allocatable units, so replenishment must never create more available records than the authoritative inventory permits. When the pool empties, the reserve operation can trigger replenishment. A lock can ensure that only one transaction replenishes a given pool at a time, while other requests wait for the operation to finish.

SELECT ... FOR UPDATE SKIP LOCKED can select available records without waiting for rows held by other transactions. The MySQL documentation states that SKIP LOCKED returns an inconsistent view of the data and is unsuitable for general transactional reads. It is intended for queue-like workloads where skipping locked rows is acceptable. An available-unit pool may fit that pattern, but the allocation rules must account for partial results. If a request needs five units and the query finds only three unlocked records, two other records may still exist but remain locked by concurrent transactions. The application must retry, wait, or return a temporary allocation failure according to its checkout policy. It must not treat a partial result as proof that the inventory ledger is empty. See the MySQL locking-read guide.

The physical schema also affects lock behavior. A reservation query that uses a secondary index may cause InnoDB to lock both the secondary-index record and the corresponding clustered primary-key record. A carefully chosen primary key and access path can reduce unnecessary locking. The schema should reflect the dimensions used to identify inventory, not merely provide a convenient row identifier. See the MySQL documentation on locks set by different SQL statements.

Transaction isolation also affects replenishment. Under REPEATABLE READ, gap locks can block inserts in some search and index-scan patterns. READ COMMITTED generally avoids gap locks for locking searches and index scans, although foreign-key and duplicate-key checks remain exceptions. Changing isolation levels may address a specific locking pattern, but it does not eliminate deadlocks. Transactions must still acquire locks in a consistent order. See the MySQL transaction isolation documentation.

A migration between these designs should preserve the current allocation source of truth while the new path is tested. A shadow deployment can calculate or record reservation outcomes in both systems while only one system controls allocation and fulfillment. The secondary path must not independently reserve stock or trigger order processing. The team can compare outcomes before switching traffic gradually. A rollback mechanism should remain available during the transition.

Trace database connection use across checkout

Inventory contention is only one source of checkout pressure. Other operations may occupy database connections while buyers wait to reserve stock.

Tag SQL statements by business process and correlate the tags with application traces. Measure how long each process holds a connection, then inspect the work performed between connection checkout and release. Pay particular attention to application work performed while a transaction remains open, including network calls and processing that does not require the database connection.

An engineering team investigating checkout pressure should examine several signals:

Lock waits concentrated on one SKU point to contention around records used by that inventory allocation. Inspect the blocking transaction, index access path, and competing operations before assigning the cause.

Long connection hold times can indicate that network calls or application processing are occurring before the connection is returned to the pool.

Rising retry counts during a traffic spike call for a review of conflict rates, retry limits, transaction duration, and the types of errors triggering retries.

Include seller imports, warehouse updates, and administrative adjustments in the investigation. Those operations may update the same inventory records as checkout. The inventory key should reflect the store's allocation unit, including seller or shop ownership where required.

Test the design with a single SKU under several concurrent demand patterns. Send 100 simultaneous one-unit purchase attempts for 100 available units, then 1,000 simultaneous one-unit attempts for 10 available units. Run another test with zero available stock. Include multi-item orders and payment timeouts followed by retries.

For a quantity-counter model, verify that the available quantity never falls below zero and that each successful reservation reduces stock exactly once. Verify that committed claims do not deduct the reserved quantity again. For an individual-unit model, verify that each unit record belongs to no more than one active reservation or committed claim. Also test pool exhaustion while the ledger still contains stock. Replenishment should run once, and waiting requests should continue after it finishes.

Include a test where a multi-item order can acquire only some of its required units. Verify that the application follows its defined allocation policy, whether that policy requires all-or-nothing allocation or permits partial fulfillment. If the transaction fails, verify that any partial reservations are released exactly once.

For the Redis design, test failures between the provisional hold and the MySQL allocation, including a MySQL timeout, an application restart, and a failed Redis release. Confirm that retries and reconciliation do not create duplicate reservations or leave stock unavailable indefinitely.

Record deadlocks, lock waits, retry counts, P95 and P99 latency, and connection hold time. These measurements help locate contention and connection pressure during the test. Performance testing should include both normal checkout traffic and contention concentrated on a single inventory key.

Choose the architecture from the workload

A quantity-counter model may be sufficient when the store has a simple allocation rule and modest contention on each inventory key. A MySQL-backed reservation model keeps inventory changes and reservation records within one transactional database boundary. A Redis-assisted model can coordinate provisional holds and manage short-lived request pressure, but MySQL must still authorize each inventory allocation if it remains the source of truth.

The choice depends on the inventory model, the reservation lifecycle, and the capacity available to checkout. A bounded unit pool introduces replenishment and locking behavior. A separate reservation store requires recovery and reconciliation between systems. A quantity counter concentrates competing writes on inventory records.

Examine the allocation key, the number of competing updates, the payment lifecycle, and database connection use before changing the architecture. Then decide whether the current quantity model needs a different concurrency method or whether the reservation storage design itself needs to change.

For teams building or scaling high-concurrency commerce platforms, Techosquare provides e-commerce website development to align inventory allocation, payment reservations, and database architecture with checkout and fulfillment requirements.