PostgreSQL Indexing, Kafka Idempotency, and Row-Lock Ordering

Medium · Software Engineering Fundamentals · Software Engineer · Onsite

Prompt

You are building the storage and stream-processing tier for a high-traffic retail drop service where limited-inventory items sell out in seconds. Checkout requests arrive on Apache Kafka, and worker processes persist order state and stock reservations inside a PostgreSQL-compatible relational database.

Relational Schema

CREATE TABLE orders (
    order_id UUID PRIMARY KEY,
    user_id UUID NOT NULL,
    status VARCHAR(32) NOT NULL, -- 'PENDING', 'CONFIRMED', 'CANCELLED'
    created_at TIMESTAMP WITH TIME ZONE NOT NULL,
    total_amount NUMERIC(10, 2) NOT NULL
);

CREATE TABLE order_items (
    order_id UUID REFERENCES orders(order_id),
    item_id UUID NOT NULL,
    quantity INT NOT NULL,
    PRIMARY KEY (order_id, item_id)
);

CREATE TABLE inventory (
    item_id UUID PRIMARY KEY,
    available_stock INT NOT NULL CHECK (available_stock >= 0),
    reserved_stock INT NOT NULL DEFAULT 0
);

Traffic Profile & Operational Guarantees

  1. Database Read Patterns:
    • Customer history lookup (latency-critical, high QPS): Retrieve a customer's 20 latest confirmed purchases: SELECT * FROM orders WHERE user_id = ? AND status = 'CONFIRMED' ORDER BY created_at DESC LIMIT 20;
    • Scheduled reporting scan: Aggregate or inspect orders placed within an arbitrary [start_ts, end_ts] window across the entire customer base.
  2. Stream Ingestion:
    • Upstream checkout nodes publish OrderCreatedEvent(order_id, user_id, items: [(item_id, quantity)]) records to a multi-partition Kafka topic named orders.created.
    • A fleet of worker processes reads from orders.created as members of one consumer group.
    • Message delivery is at-least-once: broker retries, worker crashes, or partition rebalances may cause the same event to be delivered multiple times.
  3. Atomic Stock Deduction:
    • When handling an event, a worker must verify that every line item has sufficient available_stock, shift the requested units from available_stock into reserved_stock (available_stock -= qty, reserved_stock += qty), and transition the order's status to 'CONFIRMED' inside one atomic database transaction (or mark it 'CANCELLED' if any requested SKU lacks stock).
    • Many workers execute multi-item orders concurrently, frequently touching shared SKUs.

Engineering Questions

  1. PostgreSQL Indexing:
    • Write the CREATE INDEX statement on orders that lets PostgreSQL answer the 20-newest confirmed-orders query without scanning unrelated table rows or performing an explicit sort pass, and justify the exact column order.
    • Assess the pros and cons of narrowing this index with a partial WHERE predicate, and explain how you would index the cross-customer time-window reporting query.
  2. Kafka Partition Selection & Idempotency:
    • Which field should producers hash as the partition key on orders.created? Contrast how partitioning interacts with per-customer ordering versus cross-customer contention on popular SKUs.
    • Design the consumer + database protocol so duplicate Kafka deliveries never deduct inventory more than once for the same order_id.
  3. Row-Level Locking & Deadlock Elimination:
    • Provide the transactional SQL (or worker pseudocode) that reserves stock across all items in an order safely.
    • Show how two concurrent multi-item orders touching the same SKUs in opposite order (for instance, Order X requesting [SKU_10, SKU_20] while Order Y requests [SKU_20, SKU_10]) can deadlock, and specify how to guarantee deadlock-free lock acquisition paired with bounded retry handling.

Scope & Expectations

  • Index mechanics and trade-offs: Justify composite B-tree column ordering (equality predicates vs. sort keys), explain when partial indexes and time-range indexes (such as B-tree vs. BRIN) help, and note planner pitfalls.
  • End-to-end stream idempotency: Reason accurately about Kafka partition semantics across multi-item carts, manual offset commits relative to PostgreSQL commits, and atomic deduplication inside the database transaction.
  • Concurrency correctness under load: Present race-free SQL locking that preserves the available_stock >= 0 invariant, prove why canonical key ordering breaks circular lock waits, and cover connection rollback, bounded backoff, and dead-letter routing.

Step-by-step walkthrough

  1. Composite index column order for customer order history

    A B-tree index is a balanced tree data structure that keeps index entries sorted lexicographically by its listed columns, allowing PostgreSQL to jump directly to a matching key in logarithmic time instead of scanning every table row. Our hot query filters on two equality conditions and sorts by a timestamp with a small limit:

    SELECT * FROM orders
    WHERE user_id = ? AND status = 'CONFIRMED'
    ORDER BY created_at DESC
    LIMIT 20;
    

    The golden rule for multi-column B-tree indexes is equality columns first, sort (or range) column last. Compare how the leaf entries look for Customer U7 under the two candidate column orders:

    Good order: (user_id, status, created_at DESC)
      (U7, 'CANCELLED', 14:05)
      (U7, 'CONFIRMED', 14:09)  <-- Jump straight here and read 20 contiguous entries!
      (U7, 'CONFIRMED', 14:04)  <-- Already sorted newest-first; stop immediately at 20.
      (U7, 'PENDING',   14:10)
    
    Bad order:  (user_id, created_at DESC, status)
      (U7, 14:10, 'PENDING')    <-- Must read and discard non-CONFIRMED entries
      (U7, 14:09, 'CONFIRMED')
      (U7, 14:05, 'CANCELLED')  <-- Confirmed rows are interleaved with other statuses!
      (U7, 14:04, 'CONFIRMED')
    

    Define the composite index as:

    CREATE INDEX orders_user_status_created_idx
        ON orders (user_id, status, created_at DESC);
    

    Why each column sits in that position:

    • user_id before status (leftmost-prefix rule): Because both user_id = ? and status = 'CONFIRMED' are exact equalities, either (user_id, status, created_at DESC) or (status, user_id, created_at DESC) puts a user's confirmed orders into one contiguous sorted run. Putting high-cardinality user_id first additionally allows queries filtering on WHERE user_id = ? alone to reuse this same index.
    • created_at DESC last: Within (user_id, 'CONFIRMED'), entries sit in newest-to-oldest order. PostgreSQL executes an Index Scan + Limit, reads at most 20 index entries, fetches those 20 rows from the orders heap (SELECT * needs total_amount), and performs zero table scan and zero sort. (PostgreSQL can also scan an ASC B-tree backward, though explicit DESC documents intent and is required if sorting on mixed directions.)
    • Numeric example: Suppose a power user has 5,000 total orders (4,000 confirmed). An index on (user_id) alone fetches 5,000 heap rows, filters down to 4,000, sorts all 4,000 in memory, and discards 3,980. The composite index touches exactly 20 index entries and 20 heap rows.
  2. Evaluate partial indexes and the cross-user analytics query

    A partial index includes a WHERE clause in its index definition so PostgreSQL indexes only the subset of rows satisfying that condition:

    CREATE INDEX orders_user_confirmed_created_idx
        ON orders (user_id, created_at DESC)
        WHERE status = 'CONFIRMED';
    
    • When it wins: status no longer needs to be stored inside every index tuple, making each entry narrower, and 'PENDING' or 'CANCELLED' rows never enter or churn the index. If only 15% of flash-sale attempts become 'CONFIRMED' (while 85% cancel due to stockouts), the partial index is ~85% smaller and much more likely to stay hot in RAM.
    • Trade-offs: It cannot serve queries for 'PENDING', 'CANCELLED', or all orders. Also, PostgreSQL only picks a partial index when the query planner can prove at plan time that the query predicate implies status = 'CONFIRMED'—a literal 'CONFIRMED' works, whereas a generic prepared statement using status = $2 will skip the partial index.

    For the periodic cross-user analytics query (WHERE created_at BETWEEN ? AND ?), neither user-leading index helps because created_at is buried behind millions of distinct user_id values. Add a dedicated time index (and run heavy analytics against a read replica so flash-sale writes on the primary are unaffected):

    -- Option A: Standard B-tree for selective, narrow time windows (e.g., a 5-minute spike)
    CREATE INDEX orders_created_at_idx ON orders (created_at);
    
    -- Option B: BRIN index for wide scans on append-only, time-ordered tables
    CREATE INDEX orders_created_at_brin_idx ON orders USING brin (created_at);
    

    A BRIN (Block Range Index) stores only the minimum and maximum created_at value for each contiguous 128-page (1 MB) disk range instead of indexing every row. Because orders arrive roughly in chronological order, physical disk order mirrors created_at: for 100 million orders (~10 GB across ~1.22 million 8 KB pages), a B-tree index takes ~2.4 GB (~24 bytes/row), whereas a BRIN index needs only ~9,500 range summaries (~300 KB) while still skipping every irrelevant disk block range.

  3. Kafka partition key: why `user_id` wins (and why SKU contention stays)

    A Kafka partition is an ordered, append-only log shard inside a topic. Within a single consumer group, Kafka assigns each partition to at most one consumer instance at a time, mapping messages by hash(partition_key) mod num_partitions.

    Producer: Order X (Customer U7 -> SKU_10) ---> Partition 0 ---> Consumer Worker 1 \
                                                                                       +--> Both lock SKU_10 in DB!
    Producer: Order Y (Customer U9 -> SKU_10) ---> Partition 3 ---> Consumer Worker 4 /
    

    Evaluate the three candidate partition keys:

    • item_id (rejected): A single OrderCreatedEvent contains multiple items ([(SKU_10, 3), (SKU_20, 2)]). Splitting one order across multiple partitions destroys single-order atomicity (you cannot easily confirm an order only if all items succeed), and a viral drop SKU would route 100% of traffic to a single overloaded partition and consumer.
    • user_id (recommended): Spreads traffic evenly across millions of customers while keeping every event for a given customer—and therefore every lifecycle event for each of their orders—strictly ordered on one partition. Per-customer purchase caps (such as "max 2 units per shopper") are also naturally serialized per user during steady-state consumption.
    • order_id (viable alternative): Gives the flattest possible distribution even if automated bot accounts spam orders under one user_id, while still keeping events for the same order_id ordered.

    Crucial takeaway: no Kafka partition key eliminates cross-order SKU contention. Because Customer U7 (Partition 0) and Customer U9 (Partition 3) buy the same hot SKU at the same millisecond on different consumers, PostgreSQL itself must serialize concurrent inventory updates safely. Also size the partition count generously upfront, because increasing num_partitions later changes hash(key) mod N and temporarily breaks key ordering.

  4. Guarantee exact-once inventory updates under at-least-once delivery

    At-least-once delivery means Kafka guarantees every message arrives one or more times: if a consumer commits its PostgreSQL transaction and crashes (or loses partition ownership during a consumer-group rebalance) one millisecond before committing its Kafka offset, the next consumer replays that exact same OrderCreatedEvent.

    Idempotency means applying the same event once, twice, or ten times leaves the database in the exact same state—decrementing inventory at most once per order_id. Note that Kafka's built-in "exactly-once" transactions only coordinate Kafka-to-Kafka pipelines; they cannot include an external PostgreSQL commit.

    Achieve end-to-end idempotent processing with two rules:

    1. Commit an idempotency record in the exact same PostgreSQL transaction as the stock update: Create a tiny processed_orders table keyed by order_id (or rely on INSERT INTO orders(order_id, ...) ON CONFLICT (order_id) DO NOTHING if the consumer inserts the orders row itself):
    CREATE TABLE processed_orders (
        order_id     UUID PRIMARY KEY,
        processed_at TIMESTAMPTZ NOT NULL DEFAULT now()
    );
    
    Inside the transaction, run `INSERT INTO processed_orders (order_id) VALUES (:order_id) ON CONFLICT (order_id) DO NOTHING`.
    - If `rowcount == 0`, this order was already processed: roll back (no-op), commit the Kafka offset, and move on.
    - If two consumers race on the exact same `order_id` during a rebalance, PostgreSQL's unique-key lock blocks the second `INSERT` until the first transaction either commits (second sees `0` rows inserted and skips) or rolls back (second proceeds cleanly).
    
    1. Disable Kafka auto-commit and commit the offset strictly AFTER PostgreSQL COMMIT: If the worker crashes before COMMIT, PostgreSQL rolls back both the stock change and processed_orders, so the Kafka replay executes cleanly. If it crashes after COMMIT but before offset commit, the replay hits processed_orders and becomes a harmless no-op. (If you also emit a downstream OrderConfirmed Kafka event, insert it into a PostgreSQL transactional outbox table inside this same transaction and let a background relay publish it.)
  5. Transactional SQL for multi-item stock reservation

    Before touching the database, aggregate any duplicate item_id entries in the incoming event (for example, [(SKU_10, 1), (SKU_10, 2)] -> [(SKU_10, 3)]) and sort the distinct item_ids in ascending order.

    Use pessimistic row locking (SELECT ... FOR UPDATE), which locks the selected inventory rows exclusively until our transaction finishes, forcing competing transactions on those same items to wait in line rather than reading stale stock counts:

    BEGIN;
    SET LOCAL lock_timeout = '2s';
    
    -- Step 1: Idempotency guard committed atomically with inventory & order updates.
    INSERT INTO processed_orders (order_id)
    VALUES (:order_id)
    ON CONFLICT (order_id) DO NOTHING;
    -- If 0 rows inserted -> already handled! ROLLBACK, commit Kafka offset, and return.
    
    -- Step 2: Acquire exclusive row locks in strict ascending item_id order.
    -- PostgreSQL sorts the matching rows by item_id first, then locks them one by one.
    SELECT item_id, available_stock
    FROM inventory
    WHERE item_id = ANY(:sorted_unique_item_ids)
    ORDER BY item_id ASC
    FOR UPDATE;
    
    -- Step 3 (in application code): Verify every requested item_id exists in the result
    -- and has available_stock >= requested_qty.
    -- If ANY item lacks stock, cancel the order and COMMIT (stockout is a valid outcome,
    -- NOT an error to retry!):
    --   UPDATE orders SET status = 'CANCELLED'
    --   WHERE order_id = :order_id AND status = 'PENDING';
    --   COMMIT;
    
    -- Step 4: Sufficient stock for all items -> decrement available and increment reserved.
    -- (Rows are already locked by Step 2; loop in sorted item_id order or batch via unnest.)
    UPDATE inventory
    SET available_stock = available_stock - :qty,
        reserved_stock  = reserved_stock  + :qty
    WHERE item_id = :item_id;
    
    -- Step 5: Persist order items (if not pre-inserted) and mark the order CONFIRMED.
    UPDATE orders
    SET status = 'CONFIRMED'
    WHERE order_id = :order_id AND status = 'PENDING';
    
    COMMIT;
    -- Step 6: Only AFTER PostgreSQL COMMIT succeeds, commit the Kafka message offset.
    

    Why SELECT ... ORDER BY item_id ASC FOR UPDATE matters instead of a single unsorted UPDATE ... FROM (VALUES ...): in PostgreSQL, a multi-row UPDATE locks rows in whatever physical/plan order the optimizer chooses, whereas SELECT ... ORDER BY item_id ASC FOR UPDATE places PostgreSQL's LockRows executor node above the Sort/ordered index scan, guaranteeing deterministic ascending lock acquisition. Meanwhile, CHECK (available_stock >= 0) acts as a last-resort database invariant (SQLSTATE 23514) that makes negative stock impossible even if application logic has a bug.

  6. How overlapping orders deadlock—and why global lock ordering prevents it

    A deadlock is a circular wait where two or more transactions freeze permanently because each holds a row lock the other needs to continue. Watch what happens if Order X ([SKU_10, SKU_20]) and Order Y ([SKU_20, SKU_10]) lock items in arrival order:

    Unsorted locking -> DEADLOCK:
      Time   Order X (items [SKU_10, SKU_20])          Order Y (items [SKU_20, SKU_10])
      t1     Locks SKU_10                              Locks SKU_20
      t2     Requests lock on SKU_20 (waits on Y)      Requests lock on SKU_10 (waits on X)
      t3     Cycle: X -> Y -> X! After deadlock_timeout (1s), PostgreSQL aborts one with 40P01.
    
    Sorted locking (both sort to [SKU_10, SKU_20]) -> DEADLOCK-FREE:
      Time   Order X (sorted [SKU_10, SKU_20])         Order Y (sorted [SKU_10, SKU_20])
      t1     Locks SKU_10                              Requests lock on SKU_10 (waits behind X; holds NOTHING!)
      t2     Locks SKU_20, updates stock, COMMITs      (still waiting on SKU_10)
      t3                                               Wakes up, locks SKU_10 then SKU_20, checks stock, COMMITs
    

    Why ascending key order makes deadlocks mathematically impossible: Suppose a wait cycle T1 -> T2 -> ... -> Tk -> T1 existed. Because every transaction acquires locks in strictly increasing item_id order, any transaction Ti waiting for row r_next can only hold locks on rows strictly smaller than r_next. Following the cycle would imply r_1 < r_2 < ... < r_k < r_1, so r_1 < r_1—a contradiction. Every code path that touches inventory (reservations, order cancellations releasing reserved stock, warehouse restocks) must follow this exact same ascending item_id lock order, and always lock inventory before orders.

    Concrete stock trace with SKU_10: available = 8, SKU_20: available = 4: - Order X wants (SKU_10: 3, SKU_20: 2) and Order Y wants (SKU_20: 3, SKU_10: 1). - Both sort keys to [SKU_10, SKU_20]. Order X wins SKU_10 first, locks SKU_20, verifies 8 >= 3 and 4 >= 2, updates SKU_10 -> (avail 5, res 3) and SKU_20 -> (avail 2, res 2), marks Order X 'CONFIRMED', and commits. - Order Y now acquires SKU_10 (avail 5 >= 1) and SKU_20 (avail 2 < 3), sees insufficient stock on SKU_20, marks Order Y 'CANCELLED', and commits cleanly with zero deadlocks.

  7. Bounded retries, explicit rollback, and dead-letter handling

    Even with deadlock-free reservation order, transient database errors can still occur—such as 55P03 (lock_not_available when lock_timeout = '2s' expires on a hot SKU), 40001 (serialization_failure), or 40P01 (deadlock_detected if an unmigrated admin script locked out of order).

    Handle failures with three production safeguards:

    • Explicitly rollback() the connection on error before retrying so the database session does not stay stuck in PostgreSQL's aborted transaction (25P02) state.
    • Bounded retries with exponential backoff and jitter: Retry at most 3 times (50 ms, 100 ms, 200 ms multiplied by a random 0.5x–1.5x factor—jitter prevents dozens of waiting workers from slamming the same row at the exact same millisecond). Because a failed transaction rolled back its processed_orders insert too, retrying is completely safe.
    • Dead-Letter Queue (DLQ): If a message still fails after 3 attempts or throws a non-retryable error (malformed JSON, schema violation), publish the raw event to orders.created.dlq, flush the producer, and commit the Kafka offset so one poison message never stalls the entire partition.
    from collections import defaultdict
    import json
    import random
    import time
    
    RETRYABLE_SQLSTATES = {"40P01", "40001", "55P03"}  # deadlock, serialization, lock_timeout
    MAX_ATTEMPTS = 3
    
    
    def reserve_order_once(conn, order_id: str, items: list[tuple[str, int]]) -> None:
        """Execute one atomic PostgreSQL transaction to deduplicate and reserve stock."""
        # Sum duplicate item_ids and sort in ascending item_id order to prevent deadlocks
        qty_by_item: dict[str, int] = defaultdict(int)
        for item_id, qty in items:
            qty_by_item[item_id] += qty
        sorted_items = sorted(qty_by_item.items())
        sorted_ids = [item_id for item_id, _ in sorted_items]
    
        with conn.cursor() as cur:
            cur.execute("SET LOCAL lock_timeout = '2s'")
            cur.execute(
                "INSERT INTO processed_orders (order_id) VALUES (%s) ON CONFLICT DO NOTHING",
                (order_id,),
            )
            if cur.rowcount == 0:
                # Duplicate delivery: roll back no-op transaction and return cleanly
                conn.rollback()
                return
    
            cur.execute(
                """
                SELECT item_id, available_stock
                FROM inventory
                WHERE item_id = ANY(%s)
                ORDER BY item_id ASC
                FOR UPDATE
                """,
                (sorted_ids,),
            )
            stock_by_item = dict(cur.fetchall())
    
            insufficient = any(
                stock_by_item.get(item_id, -1) < qty for item_id, qty in sorted_items
            )
            if insufficient:
                cur.execute(
                    "UPDATE orders SET status = 'CANCELLED' WHERE order_id = %s AND status = 'PENDING'",
                    (order_id,),
                )
                conn.commit()
                return
    
            for item_id, qty in sorted_items:
                cur.execute(
                    """
                    UPDATE inventory
                    SET available_stock = available_stock - %s,
                        reserved_stock  = reserved_stock  + %s
                    WHERE item_id = %s
                    """,
                    (qty, qty, item_id),
                )
            cur.execute(
                "UPDATE orders SET status = 'CONFIRMED' WHERE order_id = %s AND status = 'PENDING'",
                (order_id,),
            )
            conn.commit()
    
    
    def process_kafka_message(msg, conn, dlq_producer, db_error_cls) -> None:
        """Process one Kafka message with bounded retries, rollback cleanup, and DLQ fallback."""
        payload = json.loads(msg.value())
        items = [(entry["item_id"], entry["quantity"]) for entry in payload["items"]]
    
        for attempt in range(1, MAX_ATTEMPTS + 1):
            try:
                reserve_order_once(conn, payload["order_id"], items)
                return
            except db_error_cls as exc:
                # Always clear the aborted transaction state on conn before retrying
                conn.rollback()
                sqlstate = getattr(exc, "sqlstate", None)
                if sqlstate not in RETRYABLE_SQLSTATES or attempt == MAX_ATTEMPTS:
                    dlq_producer.produce("orders.created.dlq", value=msg.value(), key=msg.key())
                    dlq_producer.flush()
                    return
                backoff = 0.05 * (2 ** (attempt - 1)) * random.uniform(0.5, 1.5)
                time.sleep(backoff)
    

Intuition & how it works

Think of a limited-drop retail backend as a busy warehouse fulfillment desk with three jobs: looking up a shopper's receipt binder quickly (indexing), making sure a faxed order slip that prints twice never ships two boxes (Kafka idempotency), and making sure two clerks pulling items from shared shelves never freeze waiting on each other (deadlock-free row locking).

Naive designs fail on all three fronts under peak drop load:

  • Indexing user_id alone forces PostgreSQL to pull thousands of historical orders per frequent shopper and sort them in memory on every page view.
  • Relying on Kafka partition keys or auto-committed offsets either loses orders on worker crashes or double-decrements stock when consumer rebalances replay messages.
  • Locking inventory rows in the arbitrary order listed in each cart lets Order X ([SKU_10, SKU_20]) lock SKU_10 while Order Y ([SKU_20, SKU_10]) locks SKU_20, freezing both in a circular deadlock right when traffic peaks.

Walk through two concurrent drop orders when SKU_10 has 8 units and SKU_20 has 4 units:

  1. Kafka routing: Customer U7's Order X (SKU_10 x 3, SKU_20 x 2) and Customer U9's Order Y (SKU_20 x 3, SKU_10 x 1) hash by user_id to different partitions and land on two workers simultaneously.
  2. Idempotent + ordered DB transaction: Both workers insert their order_id into processed_orders inside BEGIN ... COMMIT and sort item IDs ascending ([SKU_10, SKU_20]) before running SELECT ... ORDER BY item_id ASC FOR UPDATE.
  3. Clean serialization: Order X locks SKU_10 then SKU_20 while Order Y waits on SKU_10 holding zero locks. Order X confirms (SKU_10 -> 5, SKU_20 -> 2) and commits; Order Y wakes up, sees SKU_20 has 2 < 3, marks Order Y 'CANCELLED', commits its DB transaction, and only then commits its Kafka offset.

Key points

  • Equality-first, sort-last B-tree index: CREATE INDEX ON orders (user_id, status, created_at DESC) groups all confirmed orders for a user into one contiguous, pre-sorted range in the B-tree index (a sorted tree index), reading just 20 index entries and 20 table rows with zero sort step.
  • Partial and analytics indexes: A partial index (ON orders (user_id, created_at DESC) WHERE status = 'CONFIRMED') shrinks index size and write overhead when confirmed orders are a fraction of rows (provided queries use the literal 'CONFIRMED'). Cross-user timestamp analytics (WHERE created_at BETWEEN ? AND ?) needs its own (created_at) B-tree or compact BRIN (Block Range Index) on a read replica.
  • Partition Kafka by user_id (or order_id), never item_id: Partitioning by user_id preserves per-user and per-order event ordering while distributing load; because multi-item orders from different users touch the same SKUs concurrently across partitions, PostgreSQL must enforce inventory safety.
  • Transactional idempotency + post-commit offsets: Commit an INSERT INTO processed_orders (order_id) ... ON CONFLICT DO NOTHING inside the exact same PostgreSQL transaction as the stock decrement, and commit the Kafka offset manually only after COMMIT.
  • Canonical ascending lock order (ORDER BY item_id ASC FOR UPDATE): Deduplicating and sorting item_ids globally before acquiring pessimistic row locks eliminates circular wait cycles (r_1 < r_2 < ... < r_1 is impossible).
  • Bounded retries + DLQ: Configure SET LOCAL lock_timeout = '2s', call conn.rollback() on failure, retry transient SQLSTATEs (40P01, 40001, 55P03) at most 3 times with exponential backoff and jitter (randomizing retry delays), and route exhausted or malformed events to a dead-letter queue (DLQ).

Common mistakes

  • Putting created_at before status in the composite index: (user_id, created_at DESC, status) interleaves 'PENDING' and 'CANCELLED' rows into the scan, forcing PostgreSQL to read and discard arbitrary numbers of non-matching entries before finding 20 confirmed orders.
  • Using two separate single-column indexes on (user_id) and (status): Combining them via a Bitmap Index Scan loses timestamp order, forcing PostgreSQL to fetch every confirmed order for that user and sort them all before applying LIMIT 20.
  • Expecting a partial index to match WHERE status = $2 in a generic prepared plan: Because the planner cannot prove $2 = 'CONFIRMED' for all parameter values, a generic plan ignores the partial index.
  • Assuming partitioning by user_id prevents inventory race conditions: Two different users buying the same hot item hash to different partitions and execute simultaneously on separate consumer instances.
  • Committing Kafka offsets before PostgreSQL COMMIT (or leaving auto-commit enabled): A crash after the offset commit permanently drops the order without reserving stock. Conversely, checking processed_orders in a separate SELECT transaction before the UPDATE transaction creates a check-then-act race condition.
  • Computing new_stock = old_stock - qty in Python without FOR UPDATE: Two workers both read available_stock = 1, both write 0, and oversell 2 units without ever tripping CHECK (available_stock >= 0).
  • Forgetting conn.rollback() before retrying in psycopg: A failed SQL statement leaves a PostgreSQL session in aborted transaction (25P02) state, causing immediate failure on retry attempts 2 and 3 unless rolled back first.

Follow-up questions

  • How would you adjust the indexing design if callers filter by any status value—or omit the status filter altogether—instead of querying only 'CONFIRMED' orders? For queries filtering on any single status (WHERE user_id = $1 AND status = $2 ORDER BY created_at DESC LIMIT 20), the full composite index (user_id, status, created_at DESC) already serves every status value optimally without sorting, so you simply drop the 'CONFIRMED'-only partial index. If the UI also lets users query all statuses at once or multiple statuses (status IN ('PENDING', 'CONFIRMED')), add (user_id, created_at DESC) (or replace the composite index with (user_id, created_at DESC) INCLUDE (status) if most orders match common filters): PostgreSQL walks the user's newest orders first and filters on status inline, though keeping (user_id, status, created_at DESC) still helps if users frequently filter for a rare status like 'CANCELLED' buried behind thousands of confirmed orders.
  • Suppose one viral product gets 10,000 purchase attempts per second; how can you relieve PostgreSQL row-lock contention on that single inventory record? Because a row lock is held from SELECT ... FOR UPDATE (or UPDATE) until COMMIT, a 2 ms database transaction caps a single row at 1 / 0.002 s = 500 serial updates per second regardless of consumer count. Mitigate this by combining four techniques: (1) slot/bucket sharding—split item_id's 1,000 units across N = 32 inventory_buckets(item_id, bucket_id, available_stock) rows and lock one non-empty bucket via FOR UPDATE SKIP LOCKED LIMIT 1, multiplying row throughput by up to 32x; (2) single-statement conditional decrement (UPDATE inventory SET available_stock = available_stock - :qty ... WHERE item_id = :id AND available_stock >= :qty) to minimize lock hold time to a single network round-trip; (3) in-memory admission / micro-batching—gate single-SKU drops in an atomic Redis Lua counter or single-writer batcher that flushes 100 reservations per SQL UPDATE; and (4) edge load-shedding—cache a "sold out" flag once stock hits 0 so the remaining 9,000 doomed attempts per second are rejected before touching PostgreSQL.
  • When does optimistic concurrency control with a version column beat pessimistic SELECT ... FOR UPDATE row locking, and why does it struggle during a flash sale? Optimistic concurrency control (OCC) reads (available_stock, version) without locking and updates via UPDATE inventory SET ..., version = version + 1 WHERE item_id = :id AND version = :v, retrying if 0 rows match. OCC is preferred when contention per SKU is low (a long-tail catalog where two buyers rarely touch the same item in the same millisecond), when business logic spans slow external RPCs or user think time where holding a DB lock would exhaust the connection pool, or in data stores without row-level FOR UPDATE locks. In a hot flash sale, however, OCC collapses under retry storms: if 50 workers read version = 1 simultaneously, 1 succeeds and 49 fail and retry against version = 2, requiring 50 + 49 + ... + 1 = 50 * 51 / 2 = 1,275 database round-trips in the worst case versus 50 queued pessimistic lock acquisitions (or 50 conditional WHERE available_stock >= :qty updates, which only fail when stock actually runs out).

Follow-up questions

Similar questions

More Persistence interview questions

All 2 Persistence questions →