cconnected.
Understand the pattern. Find your own way.Find your starting point
Your learning feed/Idea 196 of 218
Ideas this builds on
High-level design196 / 218

Choose storage from reads and writes

Picture

Which record do we fetch? Which records do we list together? Which changes must succeed together? Those choices shape keys, indexes, and transactions.

Predict

Does a separate SELECT followed by an unconditional UPDATE protect stock from concurrent claims?

Walk through the small example

Not by itself. The condition must be enforced inside a suitable atomic write or transaction.

Mental model and runnable Python model

Define entities, primary keys, relationships, uniqueness, and access patterns. Relational constraints and joins can fit linked records and multi-row invariants; document or key-value access can fit aggregate-oriented retrieval, depending on the product’s actual guarantees. Normalize when independent updates matter; denormalize deliberately when a measured read path warrants maintained copies. Composite index order should match filtering and ordering. Transactions need appropriate isolation: atomicity alone does not rule out all concurrency anomalies. Serializable execution may require retrying aborted transactions.

What the function promises: The code uses SQLite in memory to demonstrate a conditional stock claim and nonnegative constraint. It is not a benchmark or a claim that SQLite and PostgreSQL have identical isolation behavior.

import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE stock (id TEXT PRIMARY KEY, qty INTEGER NOT NULL CHECK(qty >= 0))")
db.execute("INSERT INTO stock VALUES (?, ?)", ("snack", 2))
db.commit()

def claim_stock(item, count):
    if type(count) is not int or count <= 0:
        raise ValueError("Invalid quantity")
    with db:
        result = db.execute(
            "UPDATE stock SET qty = qty - ? WHERE id = ? AND qty >= ?",
            (count, item, count))
        return result.rowcount == 1

assert claim_stock("snack", 1)
assert not claim_stock("snack", 2)
assert db.execute("SELECT qty FROM stock WHERE id = ?", ("snack",)).fetchone() == (1,)
db.close()

Work and storage: Index-assisted lookup depends on the database plan and storage; each added index increases maintenance. Measure realistic queries and write contention.

When to recognize it: Claim stock only if enough remains, in one conditional update. Reading first and writing later can race with another claimant.

Check before applying it: Database selection and isolation must match actual queries and invariants, not SQL-versus-NoSQL stereotypes.

Change one rule

An operation must decrement two independent rows together. Is one successful conditional update enough?

See what changes

No. Group both updates in one transaction, verify all required conditions, and choose isolation or locking that preserves the cross-row invariant. Roll back the whole operation on failure.

Connect

Make an API safe to call again: API access patterns reveal the queries and writes storage must support.

Repository and unit of work: A repository must expose the transactional guarantees the domain needs.