Databases indexes and transactionsKeep the right records. Protect every important rule.
Databases indexes and transactions. Learn the concepts, explore a model and defend your design.
05SYSTEM DESIGN
DEFINITION
A database stores and retrieves records under a defined set of guarantees. A data model organizes those records around useful operations and rules. An index is a maintained access shortcut. A transaction coordinates selected changes so concurrent operations do not violate the invariants that the database and application are designed to enforce.
Choose a data model from the access pattern
CONCEPTRelationalRelated records + constraints
CONCEPTDocumentAggregate-oriented records
CONCEPTKey-valueDirect lookup by a key
A familiar product name is not a substitute for defining the reads and writes.
CONCEPT 1
Choose storage from the questions you ask
Think about the canteen records
An order has an identifier, student, total, status and items. A relational database can store orders and order items in related tables. A key identifies a record, and a foreign key can connect a child record to its parent. Constraints let the database enforce selected rules, such as a unique operation identifier or a valid required relationship.
Other data models
A document database stores records shaped like documents with nested values. A key-value store retrieves a value by a key. Graph databases emphasize relationships and paths. These are useful models, not labels that prove a product is faster or more scalable. Consider the reads, writes, consistency guarantees, operational limits and team experience of the actual product.
Large files belong in a different discussion
Store photo or video bytes in suitable object storage, accessed by an object key. Keep owner, status, size and other metadata in a database where it can be queried and authorized. A search index can help find content, but the application should still check the current right to access it. A derived search result is not automatic permission to retrieve a private file.
CONCEPT 2
An index is a maintained shortcut
The book-index analogy
Without an index, finding one student's orders may require examining many records. An index stores an organized path to selected values, like an index helping you find a topic in a book. Unlike a paper book index, it must change as data is inserted, updated or deleted. Faster selected reads therefore cost storage and extra maintenance on writes.
Put the query before the index
Suppose the important query lists one student's orders in creation order. An index beginning with student_id, followed by created_at and id, may help that filtering and stable ordering. A composite index uses more than one field, and field order matters. An index designed for one query does not automatically help a different query that filters by unrelated fields.
Check rather than guess
A database query plan explains the access strategy the database expects to use. Test with realistic row counts and distributions, then measure actual work and latency. A table of 20 rows is not evidence for performance at 20 million rows. Sometimes a scan is sensible because most rows are needed. Adding an index to every field can slow writes without helping the important user journeys.
An index is a maintained shortcut
STEP 1Lookup keystudent_id = 42
STEP 2Index entriesLocate matching row references
STEP 3Table rowsRead the requested records
An index reduces some read work but uses space and must be maintained during writes.
CONCEPT 3
A transaction protects related changes
Two students want the last sandwich
Suppose stock is one. Both requests read one before either changes it. If each independently decides the item is available, both can accept an order. The problem is concurrency: the combined result violates the rule even if each request looks reasonable alone. The rule is that accepted reservations must never exceed available stock.
Make the decision atomic
A database can execute a conditional change: reduce stock only if it is still greater than zero. One request changes the record; the other sees that its change did not succeed. Check the affected-row result. If a stock reservation and order must be recorded together, group them in an appropriate transaction. Atomic means the relevant change is indivisible at the chosen boundary, not simply fast.
The ACID vocabulary
Atomicity means grouped changes apply together or not at all. Consistency means declared database rules are preserved; it is not the same meaning as every replica immediately agreeing. Isolation concerns how concurrent transactions interact. Durability concerns what a committed result survives under the stated configuration. These words describe contracts whose implementation and settings need to be understood.
A transaction gives related changes one boundary
STEP 1BeginRead and validate rules
STEP 2CommitAccept related changes together
STEP 3RollbackDiscard uncommitted changes
A database transaction does not automatically include an external payment provider.
CONCEPT 4
Isolation and the limits of transactions
Not every transaction sees the same world
Isolation levels allow different observations and conflicts. Names and details vary by database. Read committed, repeatable read and serializable are not universal promises independent of implementation. Serializable execution aims for results equivalent to some serial order of transactions, but a conflicting transaction may be aborted. The application must know how to retry a whole transaction safely.
Keep slow work outside the locked section
Holding a stock lock while calling a slow payment provider can block other buyers for too long. A local database transaction also does not automatically include that provider's state. Reserve inventory, record an explicit pending state and handle the payment through a recoverable workflow. Confirm only after appropriate evidence, and release reservations according to a well-defined expiry or compensation policy.
A common interview follow-up
What if payment succeeds and the application crashes before updating the order? The answer is not to charge again blindly. Use a stable operation identity, provider idempotency where supported and reconciliation that checks the existing outcome. Keep an allowed state-transition rule so a delayed callback cannot turn an already refunded order into a fresh confirmed purchase.
Concurrent updates need an atomic decision
STEP 1Two buyersBoth want the final seat
STEP 2Conditional updateAccept only if seat is available
STEP 3ResultOne winner; one rejection
Checking availability earlier in application code does not reserve the seat.
Key learning points
Start with reads, writes, relationships and invariants before choosing a product.
Relational, document, key-value and graph models describe different organizations, not a quality ranking.
Place large object bytes and queryable ownership metadata according to their access needs.
Indexes add storage and write cost as well as accelerating suitable reads.
Protect the final-stock decision with an authoritative atomic operation.
Compare the important ideas
Databases indexes and transactions: concepts and trade-offs
Concept
Meaning
What to check
Primary key
Record identity
Stable and unique under the chosen model
Foreign key
Declared relationship
Referenced record and deletion behavior
Composite index
Shortcut over several fields
Leading filters, ordering and actual query plan
Atomicity
Grouped change happens together or not at all
The exact transactional boundary
Isolation
Rules for concurrent transactions
Allowed anomalies and database-specific behavior
Durability
What an accepted commit survives
Configuration and stated failure assumptions
WORKED EXAMPLE
Reserve the final item
Two students both read stock = 1. A separate unprotected write by each can accept two orders. Instead, make a conditional update that decrements only while stock is positive, check which request succeeded and store the related reservation consistently. Do not keep the lock while calling a slow payment provider. The external effect needs its own recoverable workflow.
Further reading
Original teaching explanations by Buildfest Learn. Check these primary references for the underlying concepts and implementation details.
Two buyers both saw one available seat. Compare a separate read-then-write with an authoritative conditional update.
1A and B both saw one seat
2Both write after stale reads
32 bookings for 1 seat
This interleaving oversells the seat.
Make the eligibility check and accepted state transition atomic at the authoritative store. The loser must get an unavailable result; a stale browse response does not grant a reservation.
Chapter review: two questions
Attempt both questions before opening the model answers.
Question 1
For list-my-submissions, filter by learner and collection and order by created_at plus id. Propose an index and describe how to validate it.
Reveal model answer
A composite index on learner_id, collection, created_at and id is a useful hypothesis for this query shape. Check a representative query plan, row counts and latency distribution, and measure write overhead. The best exact index depends on the database, predicates, sort direction and workload.
Question 2
Two buyers race for one seat. Show the atomic decision, the losing response and the recovery if the winner's reply is lost after commit.
Reveal model answer
Use a conditional reservation update or correct locking transaction so one request wins. The loser receives an unavailable result. The winner retries using the same operation key and retrieves its stored result, rather than creating a second purchase. Record reservation and operation outcome consistently at the chosen boundary.
Answers stay in this tab. Download before leaving. This practice is not graded or saved to your account.