Buildfest Learn System DesignRead and experiment freely · Chapter activities stay in this tab
Practice librarySystem DesignDatabases indexes and transactions

LESSON 05 • SYSTEM DESIGN

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.

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
  1. CONCEPTRelationalRelated records + constraints
  2. CONCEPTDocumentAggregate-oriented records
  3. 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
  1. STEP 1Lookup keystudent_id = 42
  2. STEP 2Index entriesLocate matching row references
  3. 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
  1. STEP 1BeginRead and validate rules
  2. STEP 2CommitAccept related changes together
  3. 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
  1. STEP 1Two buyersBoth want the final seat
  2. STEP 2Conditional updateAccept only if seat is available
  3. 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
ConceptMeaningWhat to check
Primary keyRecord identityStable and unique under the chosen model
Foreign keyDeclared relationshipReferenced record and deletion behavior
Composite indexShortcut over several fieldsLeading filters, ordering and actual query plan
AtomicityGrouped change happens together or not at allThe exact transactional boundary
IsolationRules for concurrent transactionsAllowed anomalies and database-specific behavior
DurabilityWhat an accepted commit survivesConfiguration 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.