Defend Database Schema, Index Strategy, and Concurrency Controls
System DesignModel answerLast updated
Justify a database architecture by linking relational schema choices, targeted index designs, CAP theorem partition behaviors, and concurrency strategies to specific system access patterns.
During a technical architecture review, you must present and defend the database design of a data-intensive service you designed or built. You need to demonstrate how your data model, index selections, consistency guarantees, and concurrency strategies directly support your system's access patterns while preserving critical business invariants.
Requirements
- Service Blueprint: Outline a concrete service (real or hypothetical) and define at least two explicit high-volume read access patterns and two explicit write access patterns.
- Schema & Index Justification: Present the schema and explicitly justify your index selections. Address index cardinality, read acceleration, and write amplification overhead for every index proposed.
- Distributed Consistency & Partitioning: Explain how the service responds to a network partition using CAP theorem principles. Differentiate between single-node database isolation levels and multi-node replica consistency models.
- Concurrency Controls & Invariants: Detail how the architecture prevents race conditions (such as lost updates or dirty writes) during high concurrent traffic. Specify the exact lock, versioning scheme, or transaction isolation level used to defend each invariant.
Constraints & Assumptions
- Maintain consistency across the system description: your index choices, partition trade-offs, and locking mechanisms must reference the exact schema and access patterns established at the beginning.
- Clearly distinguish local ACID guarantees from distributed replication modes.
- Do not rely on generic broad assertions (e.g., "we use serializable isolation for everything"); ground every technical choice in specific operational trade-offs.
Hints
Hint 1
Start by listing explicit queries and throughput requirements before detailing tables and indexes.
Hint 2
Distinguish local ACID isolation (like Read Committed vs. Repeatable Read) from distributed replication behavior (like asynchronous primary-replica vs. quorum reads).
Hint 3
When defending indexes, explicitly mention the cost on write paths (write amplification) alongside read performance benefits.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
System Overview & Business Context
We will design and defend the database engine for an E-Commerce Inventory and Reservation Service. This service processes high-concurrency item reservations during flash sales and serves fast product availability queries to browsing shoppers.
Primary Entities
products: Catalog items (product_id,name,price,sku,created_at).inventory: Stock levels per warehouse (product_id,warehouse_id,total_stock,reserved_stock,version).reservations: Active checkout holds (reservation_id,user_id,product_id,warehouse_id,quantity,status,expires_at,created_at).
Access Patterns
Read Patterns
- R1 (Catalog Availability Lookup): Given a
product_id, retrieve total available stock across all warehouses. Frequency: High (~50,000 QPS). Latency target: < 5ms. - R2 (Expired Reservation Sweeper): Fetch all active reservations (
status = 'PENDING') whereexpires_at < CURRENT_TIMESTAMPto release stock. Frequency: Polled every 5 seconds. Latency target: < 100ms for batch execution.
Write Patterns
- W1 (Create Stock Reservation): Deduct available stock and create a reservation record when a user starts checkout. Frequency: High spike (~5,000 TPS during peak sales).
- W2 (Fulfill / Expire Reservation): Transition a reservation from
PENDINGtoCONFIRMEDorEXPIRED, adjusting stock counters accordingly. Frequency: Moderate (~2,000 TPS).
Schema & Index Strategy
CREATE TABLE inventory (
product_id BIGINT NOT NULL,
warehouse_id INT NOT NULL,
total_stock INT NOT NULL CHECK (total_stock >= 0),
reserved_stock INT NOT NULL CHECK (reserved_stock >= 0),
version BIGINT NOT NULL DEFAULT 0,
PRIMARY KEY (product_id, warehouse_id),
CONSTRAINT chk_stock_capacity CHECK (reserved_stock <= total_stock)
);
CREATE TABLE reservations (
reservation_id UUID PRIMARY KEY,
user_id BIGINT NOT NULL,
product_id BIGINT NOT NULL,
warehouse_id INT NOT NULL,
quantity INT NOT NULL CHECK (quantity > 0),
status VARCHAR(20) NOT NULL, -- 'PENDING', 'CONFIRMED', 'EXPIRED', 'CANCELLED'
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
Index Defenses
-
inventory (product_id)Index (Implicit via PK Prefix):- Target Pattern: R1 (Catalog Availability Lookup).
- Justification: Primary Key covers
(product_id, warehouse_id). Aggregating stock across warehouses for a specific product utilizes index prefix scanning. High cardinality onproduct_idmakes index lookups fast ($O(\log N)$). - Write Overhead: Baseline PK maintenance cost; no duplicate index required.
-
reservations (status, expires_at) INCLUDE (product_id, warehouse_id, quantity)Composite Partial Index:CREATE INDEX idx_reservations_pending_expiration ON reservations (expires_at) WHERE status = 'PENDING';- Target Pattern: R2 (Expired Reservation Sweeper).
- Justification: A partial B-Tree index filters out completed or cancelled orders, drastically reducing index size (high selectivity). Ordering by
expires_atallows the background job to run an index-only scan for expired items without touching table heap pages. - Write Overhead: Minimal write amplification because confirmed/cancelled state updates remove entries from this partial index, keeping memory footprint small.
Concurrency Control & Invariants
Key Invariant
Available stock (total_stock - reserved_stock) must never drop below 0, even under heavy concurrent reservation requests for the same item.
Concurrency Prevention Strategy: Optimistic Locking with Conditional Writes
Instead of using heavy pessimistic locks (SELECT ... FOR UPDATE), which can cause database lock contention and thread pool exhaustion during flash sales, we employ Optimistic Concurrency Control (OCC) using a version column combined with atomic SQL updates.
-- Step 1: Attempt to reserve stock atomically
UPDATE inventory
SET reserved_stock = reserved_stock + :qty,
version = version + 1
WHERE product_id = :product_id
AND warehouse_id = :warehouse_id
AND (total_stock - reserved_stock) >= :qty;
Why This Works:
- Atomicity: The conditional
WHEREclause enforces the business invariant directly inside the database engine during row modification. If(total_stock - reserved_stock) < :qty, zero rows are updated. - Lost Update Prevention: If two concurrent requests attempt to reserve stock simultaneously, the database's internal row-level lock serializes the actual
UPDATE. The second update re-evaluates theWHEREcondition against the newly updatedreserved_stock. - Isolation Level: Executes safely under standard Read Committed isolation. There is no need for Serializable isolation, avoiding serializable snapshot isolation (SSI) abort overhead.
Distributed Consistency & CAP Partition Behavior
1. Database Isolation vs. Replication Consistency
- Local Isolation (Read Committed): Guarantees that uncommitted transactions are never read (no dirty reads) and modifications to single rows are atomic.
- Replication Consistency: For multi-node deployments, we choose a Primary-Replica configuration with semi-synchronous replication. Writes must be acknowledged by the primary and at least one local read replica WAL buffer before returning success to the client.
2. Partition Tolerance Strategy (CP Choice)
Under the CAP Theorem, during a cross-datacenter network partition between the primary node and secondary replicas:
- Consistency over Availability (CP): The service chooses consistency for reservation writes (W1). If the primary node cannot reach the required quorum of replicas to confirm WAL persistence, write operations to that partition return a
503 Service Unavailableerror. - Stale Read Tolerance: Read queries (R1) for general catalog browsing can target asynchronous secondary replicas. Clients tolerate slightly stale stock counts during browsing, but exact stock availability is re-verified atomically at checkout via the primary node during Write Pattern W1.
Common Architectural Pitfalls Avoided
- Read-Modify-Write Race Conditions in Application Logic: Calculating
available = total - reservedinside application memory and writing back the final value leads to lost updates. Pushing the delta calculation into the conditionalUPDATEstatement guarantees correctness. - Unbounded Index Growth: Creating a non-filtered index on
reservations(expires_at)would index millions of historical rows. Using a partial index (WHERE status = 'PENDING') keeps index size small and fully resident in buffer cache. - Over-reliance on Pessimistic Locking:
SELECT FOR UPDATEcauses severe lock queuing under high concurrency. Optimistic conditional writes handle contention with higher throughput and less database overhead.