Notes

Part 1 of 10

Storage and retrieval

Every database does two jobs: it keeps the data you hand it, and it hands that data back when you ask. The section on data models looked at data from the user's side, through models and query languages. This section takes the database's side: how it lays data out on disk and finds it again. You rarely write a storage engine yourself, but you do pick one and tune it. A rough picture of what happens inside helps you make those choices well. Engines built for many small transactions (OLTP) look very different from engines built for big analytic queries. For OLTP there are two main families: log-structured engines, which only write new files and never edit them, and B-trees, which change pages in place. Both ideas are used for the main key-value store and for secondary indexes.

Storage and indexing for OLTP

Picture the smallest possible database, made of two tiny functions. To save a value, "set" adds a line like user42,{"name":"Asha"} to the end of a text file. To read a value, "get" scans the whole file and returns the last line that matches the key. An update never edits the old line; it just adds a newer one, and the newest line for a key wins.

  • Writing is very fast, because adding to the end of a file is about the cheapest thing a disk can do.
  • Reading is slow, because each lookup scans everything.
  • Twice the data means twice the time per lookup, which is O(n).

Here "log" means any file of records that you only ever add to. It is not the human-readable messages an app prints, and it can be binary.

What an index is

An index is a second structure, built from the main data, whose only job is to make lookups fast, for example by keeping keys in sorted order. Adding or dropping an index changes speed, never the data itself. You may want several indexes so you can search the same data in different ways. The catch: every write now has to update each index too, and each index takes disk space. So indexes speed up reads but slow down writes. That is why a database does not index everything on its own. You choose indexes based on the queries your app actually runs.