Trending

World technology news

→
Retry-safe stock reservations with SQLite 3.35
Software Engineering · 2021
Software Engineering2021

Retry-safe stock reservations with SQLite 3.35

A SQLite workflow that reads a conditional stock update through RETURNING and records the outcome under a durable request ID.

Archive retrospective · Topic year 2021

Developer's JournalPublished: Nov 27, 20266 min read
Reading progress0%
In this article
  1. Give each reservation intent a stable identity
  2. Read the result of a conditional update
  3. Run the reservation fixture
  4. Find the commit and retry boundaries
  5. Monitor attempts and business decisions separately

Give each reservation intent a stable identity

Suppose a warehouse has five units and a sales application asks it to reserve three. The database commits, but the connection drops before the response reaches the caller. A retry must recover the original result without decreasing stock again. The caller therefore creates a request ID for each reservation intent and keeps that ID through transport retries. One table holds available quantities by SKU. A second table holds the original request parameters and the decision for each ID. If a retry arrives after another purchase changed the stock, the replay still returns the original recorded balance. A rejection also receives a durable decision. A shopper who later wants to try again after a restock initiates a new intent with a fresh ID. SQLite 3.35.0, released on March 12, 2021, introduced RETURNING so this workflow can obtain the modified value from the update itself.

Read the result of a conditional update

Reject an invalid quantity before executing stock SQL. The update targets the requested SKU and checks whether its available quantity covers the request. If both conditions hold, the statement subtracts the amount and RETURNING provides the new count. If neither an existing SKU nor enough stock is found, the statement produces zero rows. A larger business system can distinguish those rejection reasons with another read in the same transaction. This fixture combines them under a single rejection. The balance included in an accepted reply is the one observed in that specific reservation decision. It can differ from the amount available at the time of a replay. If an old request ID arrives with different parameters, the application reports an input conflict and preserves the receipts already recorded. Correlating those conflicts to callers helps distinguish a faulty ID generator from unintended key reuse.

Database access flowConceptual sketch · summary of the article's technical flow

Run the reservation fixture

The script below uses Python's standard sqlite3 module with a memory-only database. The linked SQLite engine determines SQL feature availability, so check sqlite3.sqlite_version for version 3.35.0 or later. Request A reserves three units and records a remaining balance of two. A replay returns two again. Request B asks for four and receives a rejection. Request C then reserves the final two units. The initial response, replay, rejection, and final acceptance are asserted independently. The script also checks the stored stock count and prints the three decision records in request order. It consumes the UPDATE result before inserting the receipt in the same transaction. This is a single-row update, so pulling all returned rows is bounded here. If you adapt this pattern to batch writes, read the engine's documentation about how it accumulates RETURNING output and measure the memory implications separately.

import sqlite3

db = sqlite3.connect(":memory:", isolation_level=None)
db.executescript("""
CREATE TABLE stock (sku TEXT PRIMARY KEY, available INTEGER NOT NULL CHECK(available >= 0));
CREATE TABLE receipt (
    request_id TEXT PRIMARY KEY, sku TEXT NOT NULL,
    quantity INTEGER NOT NULL CHECK(quantity > 0),
    accepted INTEGER NOT NULL, remaining INTEGER
);
INSERT INTO stock VALUES ('A-10', 5);
""")

def reserve(request_id, sku, quantity):
    if not request_id or type(quantity) is not int or quantity <= 0:
        raise ValueError("invalid reservation")
    db.execute("BEGIN IMMEDIATE")
    try:
        prior = db.execute(
            "SELECT sku, quantity, accepted, remaining FROM receipt WHERE request_id=?",
            (request_id,),
        ).fetchone()
        if prior is not None:
            if prior[:2] != (sku, quantity):
                raise ValueError("request ID conflicts with receipt")
            result = prior[2:]
        else:
            rows = db.execute(
                "UPDATE stock SET available=available-? WHERE sku=? AND available>=? "
                "RETURNING available",
                (quantity, sku, quantity),
            ).fetchall()
            result = (1, rows[0][0]) if rows else (0, None)
            db.execute(
                "INSERT INTO receipt VALUES (?, ?, ?, ?, ?)",
                (request_id, sku, quantity, *result),
            )
        db.execute("COMMIT")
        return result
    except Exception:
        db.execute("ROLLBACK")
        raise

assert reserve("A", "A-10", 3) == (1, 2)
assert reserve("A", "A-10", 3) == (1, 2)
assert reserve("B", "A-10", 4) == (0, None)
assert reserve("C", "A-10", 2) == (1, 0)
assert db.execute("SELECT available FROM stock").fetchone() == (0,)
print(db.execute("SELECT request_id, accepted, remaining FROM receipt ORDER BY request_id").fetchall())
# [('A', 1, 2), ('B', 0, None), ('C', 1, 0)]

Find the commit and retry boundaries

The stock update and the receipt write are a single unit of work. An error between them should leave neither change committed. Publish the success reply only after COMMIT succeeds. Receiving the RETURNING value does not establish durability. BEGIN IMMEDIATE attempts to acquire the write transaction before checking for an existing receipt, giving this design a consistent decision boundary. A competing database connection can cause SQLITE_BUSY. In a file-backed validation, open two independent connections and see how long a writer must wait. Apply any contention retry to the whole transaction and preserve the same request ID. Repeating only the stock update risks losing the business decision check. Give retry loops a time bound that fits the application response budget. A deterministic in-memory fixture demonstrates the logic, while concurrency behavior requires a separate file-based test.

Monitor attempts and business decisions separately

Four requests to an HTTP handler can correspond to just three reservation decisions. Track accepted and rejected decisions independently of transport attempts, and count request ID conflicts and temporary database contention separately. Exercise an intentional reply failure after the transaction commits. Then issue the same ID and verify that the caller receives the recorded result. Test simultaneous submits from separate connections before depending on this behavior in production. Retain receipts through the intended retry horizon. If callers belong to different tenants, scope uniqueness to the appropriate tenant and request identity. Later cancellation and shipment actions are distinct business changes and deserve their own records. When a single SQLite file serves write-heavy traffic, observe writer waits alongside request latency so successful updates do not conceal slow replies. The example establishes an expected result for six fixture assertions and leaves throughput claims to a measured workload.

Technical referencesSQLite transaction modes ↗
Be the first reader ✎ Write a comment

Reader discussion

Discussion prompt

Which alternative architecture would you try for the same problem?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.