How it works
A database has two jobs: keep what you give it and find it again. The smallest design that does both is a file you only append to. Each write adds a key and value to the end, and an update is a newer record for the same key. Sequential writes are the cheapest pattern on most storage, and a crash can damage only the tail, because earlier records are never rewritten.
Finding data is the weak spot, since a read would otherwise scan the whole file. So keep an index, a structure that maps a key to where its data lives. An in-memory hash map from key to byte offset is enough. Say parcel 8841 was written as “packed” at offset 0 and “shipped” at offset 4096. The map holds 8841 at 4096, so a read costs one hash lookup and one disk read. Riak’s Bitcask engine works this way. The costs: every key must fit in memory, range queries are out because a hash map has no order, old versions pile up until a job rewrites the file, and the map must be rebuilt after a restart.
The same idea protects larger engines. A write-ahead log (WAL) makes each change durable before the engine’s main on-disk files are altered, so recovery can replay whatever had not reached them. A returned write call may only have reached the operating system’s cache; the data is safe only after a sync call such as fsync. Syncing on every commit is slow, so engines often group commits into one sync.
A team needs to store 200 million device records. With overhead, each index entry takes about 40 bytes (example figures), and the server has 16 GB of memory. They also want a list of devices seen in the last hour. Would you approve an append-only log with an in-memory hash index?
Not as the only structure. The index fits: 200 million entries at 40 bytes is 8 GB, and point lookups would be fast. But a hash map has no order, so “seen in the last hour” means scanning everything. Add a structure sorted by time or pick a sorted engine, which is the next lesson. If the hourly list were dropped, the simple design would be a good fit.
Use this as a guide for self review; written answers are not graded.Keep in mind
- Appending is fast and crash-friendly; finding data later is what needs an index.
- A write is durable once the log is synced to the device, not when the write call returns.