Databases and apps: how to find one row among billions
Behind every online store, bank, messenger, and game with save files there is a database. Its job seems simple — store records and find them — but the requirements are tough: an answer in fractions of a millisecond among billions of rows, thousands of simultaneous clients, and not a single lost payment, even if the power goes out in the server room. Let’s look at how a DBMS executes a query, why it needs indexes and a log, and how it uses RAM and SSDs.
Why you need a DBMS when you have files
You could store a shop’s orders in an ordinary file — one line per order. Problems will start quickly. To find order No. 42, you would have to read the entire file. If two customers place orders at the same time, their records will get mixed up. If the power fails in the middle of a write, the file will be left half-modified. If you need “all of Ivan’s orders in May over 1,000 rubles,” you will have to write a program for every such question.
A database management system (DBMS) solves all of this once and for everyone. The most widespread are PostgreSQL, MySQL, Microsoft SQL Server, and Oracle; SQLite is a small embedded DBMS that runs inside every smartphone, every browser, and countless applications — it is probably the most widely used database in the world.
The relational model, invented by Edgar Codd in 1970, stores data in tables: rows are records, columns are typed fields. Relationships between tables are defined by keys: the orders table has a customer_id column that refers to the customers table. Each fact is stored in one place, so when you change a customer’s address, you don’t need to edit thousands of orders.
There are other models too: document databases (MongoDB) store records as JSON, key-value stores (Redis) as an in-memory dictionary, and columnar databases (ClickHouse) are optimized for analytics over billions of rows. But the principles — indexes, a log, a page cache, transactions — are similar across all of them.
See also: The operating system: who shares out the processor, memory and devices
SQL: what you want, not how to find it
SQL is a declarative language: you describe the result, not the algorithm. The query SELECT name, total FROM orders JOIN customers ON customers.id = orders.customer_id WHERE orders.created_at >= '2025-05-01' AND total > 1000 says: “give me the names and totals of orders over 1,000 since May 1.” Not a word about the order in which to read the tables, which indexes to use, or how to join them.
First, the query text is processed by the parser: it checks the syntax and builds a tree. Then the analyzer checks it against the database schema: do these tables and columns exist, are the types compatible, does the user have the necessary permissions. Then the tree is rewritten into a logical plan — a set of relational algebra operations: select, filter, join, group, sort.
Being declarative is SQL’s main strength. The same query written 20 years ago runs differently and faster today, because the DBMS has learned new techniques and the data has changed. A programmer doesn’t have to rewrite code when a table grows from a thousand rows to a billion — adding an index is enough.
The dangerous side is SQL injection. If a program builds a query by gluing strings together, for example “WHERE name = '” + user input + “'”, an attacker can type a quote followed by their own code. The right way is parameterized queries: the query text and the data are sent to the server separately, and the data is never interpreted as SQL.
See also: Languages and runtimes: how program text becomes processor instructions
The planner: choosing the cheapest path
A single query can be executed in thousands of ways: read the whole table or go through an index, in what order to join five tables, with which algorithm. The difference between the best and the worst plan can be a factor of a million. The plan is chosen by the optimizer (the query planner).
It relies on statistics that the DBMS collects about the data: how many rows a table has, how many distinct values a column has, distribution histograms. From these it estimates how many rows will pass each filter. If 0.1% of rows satisfy the condition total > 1000, an index pays off. If 60% do, it is cheaper to read the table sequentially: reading pages in order is faster than jumping around via an index.
There are three main algorithms for joining tables. Nested loops — for each row of one table, find its match in the other via an index; good when there are few rows. Hash join — build an in-memory hash table from the smaller table and run the larger one through it. Merge join — if both sides are already sorted by the join key, walk through them in parallel, like merging two sorted lists.
The EXPLAIN command shows the chosen plan with cost estimates, and EXPLAIN ANALYZE also runs the query and shows the real numbers. The most common reason a query “suddenly got slow” is a bad estimate: the statistics are stale, the optimizer thinks there are 10 rows when there are 10 million, and it picks nested loops where a hash join was needed.
Pages: how a table is laid out on disk
A DBMS reads and writes data not in rows or bytes but in fixed-size pages: 8 KB in PostgreSQL, 16 KB in InnoDB (MySQL), 4 KB by default in SQLite. A table is a file (or a set of files) made of such pages. A page is the indivisible unit of exchange between the disk, memory, and the DBMS cache.
Inside a page there is a header, an array of pointers to rows, and the rows themselves, which fill the page from the end. In PostgreSQL a row starts with a header of about 24 bytes (the numbers of the transactions that created and deleted this version, flags), followed by the column values with alignment. An 8 KB page holds anywhere from a few to a few hundred rows. Long texts and JSON are moved out into separate storage.
Page size is a compromise. A storage device delivers data in 4 KB blocks, and an SSD internally reads 16 KB flash pages, so reading less makes no sense. Pages that are too large would force you to read lots of unneeded data for the sake of one row. 8–16 KB fits well both with SSDs and with the OS’s virtual memory pages.
The page number plus the row number within it is the row’s physical address (in PostgreSQL it is called a TID). This is exactly the address that indexes store. Reading one random page from an NVMe SSD takes 50–100 µs, from RAM — less than a microsecond. The entire architecture of a DBMS is built around this difference of hundreds of times.
See also: Storage: SSDs and hard drives
Indexes and B-trees
Without an index, the only way to find the row with id = 42 is to scan every page of the table. For a 100 GB table, that is 12 million pages — minutes. An index is an additional structure, sorted by key, that immediately tells you which page holds the row you need.
Almost all DBMSs use a B-tree (more precisely, a B+ tree). It is a tree in which every node is a page. Internal nodes hold sorted separator keys and links to child pages: “keys below 1000 — go left, from 1000 to 2000 — go here.” Leaves hold keys and row addresses, and the leaves themselves are linked in a chain for reading ranges. The tree is always balanced: the path from the root to any leaf has the same length.
Its key property is a huge branching factor. An 8 KB page holds hundreds of “key — link” pairs. With a branching factor of 400, a tree of height 3 covers 400³ = 64 million keys, and a tree of height 4 covers 25 billion. So any row among billions is found in 3–4 page reads, and since the root and the top level always stay in memory, you need to go to disk once or twice, and more often not at all.
Indexes have a cost. Each index is a copy of part of the data, and every insert or update of a row must update all of the table’s indexes. That is why indexes are built on the columns that are frequently searched, not on all of them. For databases with very heavy write loads (event logs, metrics), LSM trees are used (RocksDB, Cassandra): writes accumulate in memory and are flushed to disk as large sorted files, which are later merged in the background. Writing this way is faster; reading is a bit slower.
The buffer pool: hot pages in RAM
A DBMS keeps a page cache in RAM — the buffer pool. Every read first looks for the page there; if it isn’t there, it reads it from disk and puts it into the pool, evicting a page that hasn’t been used for a long time (approximately LRU, often using the “clock” algorithm). For PostgreSQL on a server, the buffer pool is usually given about a quarter of the memory, and another part works as the OS page cache; InnoDB is often given 70–80% of memory.
In a production database, the buffer pool hit rate is 99% or higher: hot data (recent orders, active users, the tops of indexes) is almost always in memory. That is why a database server is, above all, a lot of memory: hundreds of gigabytes or even terabytes of DDR5 per server are not unusual.
Changes also happen in memory: a row is modified in a page in the buffer pool, the page is marked “dirty,” and it is written to disk later. If every change were immediately written in place, writing pages scattered all over the disk would become the bottleneck. But then a question arises: what happens to the changes if the power fails? The answer is the log.
The gap between memory and disk explains why a database “suddenly” slows down several times over: the data has grown and no longer fits in memory, and queries that used to be served from the buffer pool now go to the SSD. This usually shows up as a sharp drop in the cache hit rate.
See also: DDR5 memory: how a byte is stored
Transactions: all or nothing
A money transfer is two operations: debit 1,000 from account A and credit it to account B. If the server crashes between them, the money disappears. A transaction combines operations into a single whole that has the four ACID properties. Atomicity: either all operations are performed, or none of them. Consistency: after the transaction, all rules hold (the balance isn’t negative, references are valid). Isolation: concurrent transactions don’t see each other’s half-finished changes. Durability: a committed transaction survives a crash.
Isolation is the hardest part. If you locked the entire table for the duration of each transaction, thousands of clients would be waiting in line. PostgreSQL and InnoDB use multiversion concurrency control (MVCC): changing a row creates a new version of it, while the old one remains as long as transactions started earlier may still see it. Each transaction sees a snapshot of the database as of its start: readers don’t block writers, and writers don’t block readers. Old versions are later cleaned up by a background process (VACUUM in PostgreSQL).
The SQL standard defines isolation levels from “read uncommitted” to “serializable,” and by default DBMSs don’t use the strictest one: PostgreSQL uses Read Committed, MySQL uses Repeatable Read. Strict isolation costs performance, and a programmer must understand which anomalies the chosen level allows.
When two transactions want to change the same row, the second one waits for a lock. If A waits for B and B waits for A, that is a deadlock. The DBMS detects such cycles and rolls back one of the transactions, and the application must be able to retry it.
See also: The operating system: who shares out the processor, memory and devices
The write-ahead log: durability through sequential writes
The rule of the write-ahead log (WAL): before a modified data page reaches the disk, a log record describing the change must reach the disk. When a transaction is committed (COMMIT), the DBMS appends its records to the end of the log and calls fsync — asking the OS and the storage device to guarantee the data is saved. Only after that does the client get “done.” The data pages themselves can stay “dirty” in memory for as long as needed.
Why is this faster than writing the pages right away? A transaction may change rows on ten different pages in different places in the files, while the log is a single write at the end of a file. Sequential writing is the fastest operation for any storage device. In addition, the DBMS combines log records from many concurrent transactions into one fsync (group commit).
The time of an fsync depends heavily on the storage device. A server SSD with power-loss protection (capacitors that let it finish writing data from its cache when power is cut) acknowledges a write within tens of microseconds. An ordinary consumer SSD has to actually write the data to NAND — that takes hundreds of microseconds to milliseconds. There are drives that “lie” and acknowledge an fsync without having saved the data — when the power goes out, a database on them can lose committed transactions.
Periodically the DBMS performs a checkpoint: it writes all dirty pages to disk, after which the old part of the log can be deleted. Recovery after a crash is simple: find the last checkpoint and reapply all log records after it. The same log is used for replication: a replica server receives a stream of WAL records and applies them locally, lagging behind the primary by just milliseconds.
Client, server, and application
A DBMS runs as a separate server program (PostgreSQL listens on TCP port 5432, MySQL on 3306), and an application connects to it as a client: a web server, a mobile backend, an analyst’s script. The query goes over the network as a message in the DBMS’s protocol, and the response comes back as rows. Even if the database is on the same server, the exchange goes through a socket.
A connection is expensive: in PostgreSQL, each connection is a separate process on the server using several megabytes of memory. That is why applications use connection pools: they keep from ten to a hundred connections open and hand them out to queries in turn. Prepared statements let you parse and plan SQL once and then execute it with different parameters.
A typical online store page load is 5–30 database queries. If each one travels over the network inside the data center in 0.2–0.5 ms plus execution time, it adds up to 5–20 ms. A common mistake is the “N + 1” problem: a program fetches a list of 100 orders in one query and then separately requests the customer for each one — 101 queries instead of one with a JOIN. ORM libraries, which hide SQL behind objects of the programming language, especially often push you toward this.
When one database isn’t enough, people use replicas (read-only copies kept up to date via the WAL), an in-memory cache in front of the database (Redis stores ready-made answers to frequent queries), and sharding — splitting the data across several servers, for example by ranges of customer ids. Backups are made regularly and must be verified by actually restoring them: a replica won’t save you from an accidental DELETE — it will faithfully repeat it.
See also: Network and server: how data finds its way and comes back · Server: a computer for the data center