Two orders are placed simultaneously for the last remaining item. Request A to read a stock of 1, and Request B to also read 1. Then, each creates an order and sets the stock to 0. Despite the stock field not showing a negative value, the system accepts both orders. The problem isn’t subtraction; it’s that “reading stock” and “obtaining purchase eligibility” are treated as two separate, unconstrained actions.
This document assumes that inventory is stored in PostgreSQL, with inventory units represented as integers. Orders only involve two actions: reserving and releasing, which occur before and after payment, respectively. Pre-sales, overstocking strategies, and cross-warehouse transfers require separate business models and cannot be represented using a single, ambiguous number.
First, let the database determine eligibility
If a single purchase only affects one row in the inventory, the conditional statement can be placed within the update statement. This requires that sku is guaranteed to be unique by either the database PRIMARY KEY or UNIQUE constraint, and cannot rely solely on application conventions. Otherwise, a single SKU might update multiple rows, which would violate the meaning of purchase eligibility. For example:
CREATE TABLE inventory (
sku text PRIMARY KEY,
available bigint NOT NULL CHECK (available >= 0)
);
Now, execute the conditional deduction on this single-row identity constraint:
UPDATE inventory
SET available = available - 1
WHERE sku = $1 AND available >= 1
RETURNING available;
Returning a row with a value of 1 indicates successful deduction, while returning 0 indicates that the inventory is insufficient or the item does not exist. The application should not first query and then decide whether to perform an unconditional update. Conditional updates bind the eligibility check with the write operation, requiring that competing requests must accept the database’s coordination for the same row. In common read-committed isolation levels, competing updates will wait and re-check the relevant conditions. The application should still process the results based on the final return value.
Adding CHECK (available >= 0) to a field represents a second line of defense, but it does not replace conditional updates. Constraints can reject invalid states, but they cannot tell the application how to distinguish between normal out-of-stock and system failures. Consistently translating database errors into “out of stock” also masks connection failures, statement errors, or constraint configuration issues.
Order records must be finalized together
If inventory updates and order creation fail, but the occupancy record is successfully written, it will leave an unexplained discrepancy. The inventory update, order insertion, and occupancy record writing should be performed as a single transaction. If any step fails, the entire transaction should be rolled back. This transaction only affects changes within the same database and cannot be treated as a rollable step, such as sending a request to a payment platform.
The record of occupation should include order identifier, product identifier, quantity, expiration date, and release status. When canceling an order, do not directly adjust inventory based on the status on the order page. Instead, atomically change the status from “occupied” to “released.” Only successful calls that change the status can return the inventory. This prevents the same inventory from being returned twice due to repeated cancellations, re-running of timeout tasks, and administrator compensation.
After the transaction is complete, it’s crucial to have a clear status transition defined for whether the “in transit” status will become “sold” or when payment failure will be released. Maintaining only one inventory field and then trying to guess the reason for a quantity change from the logs often leads to manual investigation, making reconciliation a manual process.
Conditional updates resolve concurrent access to a resource, but a user who loses a response due to a timeout may still be charged twice. Creating an order requires a stable business operation identity, and the database’s unique constraint and transaction ensure that the same intent is associated with the same order and the resource is reserved. Resource eligibility and request idempotency are two immutable properties that cannot be assumed to only execute once due to the atomic nature of the deduction statement. When a retry succeeds, the deduction is not performed.
Request verification of fingerprint to ensure that the product and quantity are the same, to avoid treating different carts with the same key as a successful transaction. Ensure that the quantity is a positive integer within the specified limits, preventing zero, negative values, or excessively large values from entering inventory updates. For bulk orders, each product must be de-duplicated or merged. If the SKU is not normalized, the order and total quantity checks may lose their intended meaning. First, create a standard purchase set, then begin the transaction.
The record can retain both the quantity and status, not just the order page status. The release uses conditional status migration, and only the first person to convert an active occupation to a release status is eligible for return. The transaction commits the migration and inventory increase together. If the administrator performs compensation, task cancellation, and payment callbacks simultaneously, only one valid final state will exist, without relying on the order of events in the logs. The status conversion protocol must cover all entry points, not just the shopping interface.
When multiple items are involved, the order is determined by the protocol.
When the shopping cart contains multiple items, it’s possible to use SELECT ... FOR UPDATE for related rows and then deduct the quantities uniformly. All access paths should acquire locks in a stable order based on the product identifier, rather than the order in which items are displayed in the user’s shopping cart. For example, if “Product A” is locked first, followed by “Product B”, and then “Product B” is locked again, this creates a risk of deadlock.
A fixed order can only reduce one type of deadlock, but it does not mean that deadlocks will no longer occur. The database may still experience contention due to other tables, foreign keys, or background tasks. Applications must identify and retry transaction errors, re-execute the entire transaction, and set a limited number of retries with a rollback. Any external side effects within the transaction must be removed, otherwise retrying may result in repeated notifications or repeated deductions.
Row locks also increase waiting times. The ability to purchase popular items already requires serial coordination, and increasing the number of connections does not magically increase the capacity to handle inventory. It is important to record lock waiting times, transaction durations, and the number of rejections to avoid misinterpreting the competition caused by items being out of stock as a sign that the database machine is too small.
The payment boundary must clearly define the commitment regarding inventory
The experience of pre-payment reservation versus direct deduction after payment differs significantly. The former reserves the item for the payment process but requires it to be released upon expiry; the latter reduces idle reservation but may find that the item is already sold out upon successful payment, requiring a refund or other compensation. The choice depends on the business’s commitment. The database cannot determine which product is chosen. The example in the article uses pre-payment reservation, and it should be clearly stated that the user is obtaining a limited-time qualification, not an unlimited right to keep the item.
Tasks with deadlines and payment confirmations may compete. The system can determine, based on rules, which task can be migrated when both are in a locked state. However, when a payment confirmation event is delayed, it cannot unconditionally convert the released lock into a sale and allow the inventory to be used again. This may require re-acquiring the inventory, issuing refunds, or manual intervention. The specific rules should be written in a state machine. External payment events cannot be undone by rolling back the database transaction. The transaction sender and idempotent compensation help to recover, but do not provide cross-platform atomicity.
Popular items can increase queuing, limit purchases, and implement fair strategies. However, queuing tokens do not replace the final database eligibility. The client display indicates that queuing success only means proceeding to the next step, and does not claim that the purchase has been completed. Increasing the size of the connection pool may exacerbate lock contention. It is important to limit concurrency and shorten transactions to avoid network calls within transactions. Certain sequential operations, as required by business needs, cannot be eliminated simply by increasing concurrency.
Isolation levels are not a business model.
Serializing isolation can detect more read/write errors, but the application must handle serialization failures. It doesn’t dictate how to release payment timeouts, nor does it automatically generate audit-able occupancy records. For single-row deductions, conditional updates are often more straightforward; for cross-row rules, such as multiple packages sharing a total amount, re-analyzing transaction boundaries and invariants is necessary.
Don’t confuse “no overselling” with “displaying absolutely real-time inventory.” The product listing page can display cached, approximate quantities, but the final purchase must be based on the results from the authoritative database. Cache expiration can affect the user experience, but as long as the eligibility process is correct, it should not lead to any additional sales promises.
Reconciliation: Transforming Historical Changes into Explainable Balances
The ledger consists of available inventory, actual occupancy, quantity sold, replenishment, and returns. The specific formulas depend on the model and cannot simply be compared to the total order quantity. By tracking the reasons for inventory changes and associated operations, it’s possible to identify discrepancies, duplicate returns, and manual adjustments. Unexplained discrepancies trigger an investigation, preventing the inventory figures from being automatically adjusted to “appear correct” without revealing the underlying cause.
Database constraints protect against local illegal states and ensure regular reconciliation to identify missing records across transactions. This can restrict the enumeration of occupied states, positive quantities, and order relationships, preventing data corruption from entering background recovery tasks. Soft-deleting orders may still require retaining occupation history, and direct cascading deletion could lead to audit loss. Data cleanup policies should consider business reconciliation and privacy requirements, preventing a single maintenance command from canceling incomplete inventory obligations.
Performance metrics should be recorded separately for: qualification rejections, lock waiting, transaction retries, and system errors. “Out of stock” is a normal business outcome and should not be counted as a server availability failure. Excessive lock waiting times indicate poor user experience and increased competitive costs. Aggregating data for popular SKUs can help identify bottlenecks, but the use of metrics should be limited to relevant product identifiers. Log retention should be limited to controlled samples to avoid creating a high-volume burden on the inventory system for observability purposes.
Updating a zero-row condition may simultaneously indicate both a missing product and insufficient stock. Whether this should be distinguished is determined by the interface contract, but connection failures and syntax errors cannot be classified as “out of stock.” A transaction failure returns a controlled system error and a related ID, without generating a successful page that indicates a non-persistent order. For uncertain timeout states, the client uses a stable operation indicator to query the results, without immediately creating a new purchase intent.
Inventory caching can display approximate availability, with final eligibility determined by the database. The page should clearly indicate that “in stock” means the item is available for purchase, even if the item is sold out, and should not imply that the list is real-time and accurate. The concurrency protocol ensures that the number of items purchased does not exceed the model’s allowed limit. The user experience design is responsible for handling the next steps for rejected users. It is important to distinguish between normal business competition and system failures, and to ensure that monitoring and user understanding are both accurate.
Verifying the Last Item Using Two Conversation Timelines
In the isolation test library, we establish a SKU with an available inventory of 1. Transaction A executes its update and reduces the inventory, but does not commit. Transaction B also executes the same update. We observe Transaction B waiting for Transaction A to complete. After Transaction A commits, Transaction B re-checks the row conditions under the appropriate “read-committed” behavior and returns 0 rows. The eligibility fact comes from the update’s return value, not from Transaction B’s previous read of the inventory. If Transaction A rolls back, Transaction B may acquire this eligibility. The test must cover both completion scenarios.
The synchronization points should be placed before and after database operations to create genuine competition during testing. After initiating 50 requests, they may also be serialized by a connection pool, and the lack of overselling does not prove that the competition window is valid. Using multiple connections, controlled barriers, and transaction status observation, it is clear that waiting and re-evaluation have occurred. The test environment should have reasonable timeouts to prevent a single failure from locking a session for a long time. After the test is complete, the test transactions and connections should be cleaned up, without executing sample operations on the production table.
When the condition update returns zero rows, the application can consistently express the inability to purchase according to the API agreement. If SKU shortages and out-of-stock situations need to be distinguished, appropriate queries can then be performed. However, this explanation does not re-grant the deduction privilege. Connection errors, transaction conflicts, and business rejections are classified separately, and all return “out of stock” regardless of whether any exceptions are caught. A successful transaction also requires that the order and occupancy records be committed within the same transaction, and the response cannot only reference the order ID that has not been persisted.
Release and Payment Success Must Compete for the Same Status
The order occupancy deadline is 9:00 AM, and the payment confirmation message will arrive at 9:01 AM. The system needs to determine whether to use the actual payment time, the confirmation processing time, or another rule to make the decision, rather than relying on the message sequence to automatically determine it. The external payment time must also come from a trusted vendor. If the payment has already been released, it cannot be unconditionally modified to sales; it may be necessary to re-obtain inventory or issue a refund, and the exception must enter the reconciliation process.
The release action first ensures that the atom has the necessary permissions to transition from an active state to a released state, and then returns the corresponding quantity. This is done as part of a single transaction. The cancellation, expiration, and administrator compensation processes all use the same transition, only the entity that has acquired the necessary permissions performs the return. The transition process also verifies the current state, not just the cached fields on the order page. All entry protocols must be consistent to ensure that background tasks are executed correctly, and an additional inventory is added to the manual button.
If a transaction involves multiple SKUs, it should release locks in a stable order, and consider the relationships created by foreign keys and other records. This fixed order reduces the likelihood of specific deadlocks. The database can still detect other competing transactions, and the application can retry the entire transaction with limited retries. External refunds or notifications should not be placed within the retryable transaction, as this could repeatedly call the vendor each time there is a database conflict. The sender must retain the obligation to recover, and the consumer still needs to perform deduplication and result confirmation.
Distinguishing Between Retry Purchases with the Same Key and New Purchase Intentions
The client submits a purchase, but the transaction completes successfully, but the response is lost. Subsequently, the same operation identifier is used to retry. The database should recognize the existing order, validate the request fingerprint, and return the same result, rather than deducting inventory again. The new operation identifier indicates a new intent and cannot be automatically merged based on guessing the user, SKU, and approximate time. The user may indeed have purchased twice. The idempotency range is defined by the account, business operation, and a clearly defined key, not a global string cache.
Changes in the same key with different quantities should be reported as a conflict, and the old order should not be treated as a successful new shopping cart. The system should first standardize and merge duplicate SKUs, then check for positive integers against business limits, and finally generate a stable fingerprint. The fingerprint should not provide authorization; even if retried, the current user should still be authenticated and confirmed to have the right to view existing orders. The retention period for storing the results should match the client’s retry window and auditing requirements, and should not be prematurely deleted, which would cause the same old request to be re-executed.
When the submission result is unknown, first check the existing operation facts. A database connection failure does not equal a rollback; instead, a decision on whether to retry must be based on reliable records. Unlike situations where a deadlock or serialization failure results in an unknown submission, the former typically means that the transaction needs to be fully redone, while the latter may have already resulted in an order. By combining error classification with idempotent facts, the recovery process will not be repeated due to network failures.
The overall budget constraint may not always apply to a single SKU.
Package A and Package B have separate inventories, but share a single promotional budget. Updates to individual row conditions can only protect their respective quantities, and cannot automatically protect the overall limit. The shared budget can be represented by explicitly coordinating resources and obtaining eligibility within the same transaction, or by using an isolation and full retry design that can detect cross-row anomalies. The specific choice depends on the invariance and query relationships; it is not possible to declare cross-row constraints to be complete simply by converting all queries into locked rows.
First, the transaction reads the total number of shared items. Then, it locks only a specific SKU. Another transaction may still accept the order using its own SKU. The read-write set and the locked object must cover the actual competitive boundary. This allows for more serializable detection of anomalies, but it still needs to handle failures during the commit stage and complete retries. It does not provide a payment compensation policy. The number of cached items can be approximated, but the final eligibility must be maintained in the authoritative transaction to ensure business consistency.
When reconciling, it’s important to retain the source of any changes.
The initial quantity, replenishment, net usage, sales, returns, and manual adjustments form the balance within the model. Define the quantity direction and stable relationships for each type of event, and when inconsistencies are found, first identify the source. Do not automatically adjust the numbers to make them consistent. Historical order cleanup should not delete outstanding inventory obligations. Audits should retain and evaluate personal data policies separately. Business facts can use necessary anonymized identifiers, without relying on retaining all private information.
Rejection of observation privileges, system failures, lock waiting, and retry counts, all contribute to the database becoming unavailable. Competition for hotspots may represent business serial boundaries, and cannot be resolved by simply expanding the connection pool indefinitely. The test report saves information about orders, occupancy, inventory, and external tasks, clearly demonstrating whether the database integration is actually implemented. When no environment is available, only a runnable acceptance plan is provided, without fabricating “concurrency has been passed.”
Using Concurrent Testing to Prove Immutability
Create a test product with a stock level of 10, and simultaneously send 50 purchase requests. The acceptance criteria are not that all requests are successful, but rather that exactly 10 requests are successfully processed, resulting in a stock level of 0, while the remaining requests are explicitly rejected, and all successful responses correspond to orderable items.
Subsequently, the system performs concurrent operations for repeated cancellation, expiration release, and payment confirmation, ensuring that the same resource only experiences one valid state. Furthermore, it deliberately throws an exception between the deduction and order insertion, demonstrating transaction rollback. The tests must use a real database connection; memory-simulated objects cannot prove the behavior of row locks and transaction isolation.
Finally, save a reconciliation query: The sum of “valid occupied quantity” plus “available inventory” should equal the “explainable initial quantity” plus changes in replenishment. The reconciliation result is closer to the actual business correctness than “no errors reported by the interface today.”
Concurrency testing should not simply involve sending a large number of requests and counting the number of successful responses. Instead, it should involve reading real database orders, occupancy, and inventory data to verify that each successful response corresponds to a valid submission, and that failed responses do not leave any partial writes. Furthermore, it should include retrying the same key, testing different quantities, and simulating transaction failures in the middle, and then swapping the order of cancellation and payment. Using multiple connections and controlled synchronization points to trigger competition, serial testing with a single connection cannot prove concurrency guarantees.
When a deadlock or serialization failure occurs, retry the entire transaction instead of just the last statement, and maintain the stable operation identifier. Verify the final business outcome and the number of attempts. External notifications are delivered via the inbox. Each of the following aspects – inventory immutability, idempotent requests, and external recovery – has its own proof, and when combined, they ensure a reliable purchase process. It is not a single UPDATE statement that bears all the responsibility.
The inventory model must distinguish between returned items and items that can be resold after repair. A customer returning an item does not necessarily mean that the item can be resold after passing quality inspection. If “available” is simply incremented, damaged items will become eligible for purchase. Instead, returned items should be initially recorded in a “pending inspection” status, and only after passing quality inspection can they be eligible for replenishment. The model should test the notification of repeated returns, quality inspection rejection, and quality inspection approval once each, confirming that only the last one provides a basis for increasing inventory, and maintaining the association between the original order and the return.