Courses / Databases for Backend Interviews / Chapter 2
Module 2 · Database foundations · Chapter 2 of 27
Before Databases: What Goes Wrong with Plain Files
No prerequisites. Next up: Databases and the DBMS: Catalogues, Schemas and Data Independence.
Part 1 · Keeping records in files
A file is a list of bytes
A small shop can keep its orders in a folder of files, and for one program working alone that is fine. The trouble starts when a second program, a second writer or a new question arrives.
A file is a named sequence of bytes. The operating system stores and returns the bytes, and that is all it does. It has no idea that your bytes are orders, customers or prices. The meaning lives in your code.
So the first job when you keep records in a file is to choose a format: a rule for turning a record into bytes and back. A common choice is JSON Lines: one JSON object per line, with a newline between records. It suits an order log because adding a record means adding one line to the end of the file.
A record is one set of related values, such as one order. A field is one named value inside it, such as the quantity. A database will give these words stricter meanings later. For now, a record is one line and a field is one key in that line.
What your code now has to do
With plain files, your program is responsible for every job around the data. Read the table to see how many of them exist.
| Job | Who does it with a plain file |
|---|---|
| Find one record | Your code reads lines and compares them one by one |
| Change one record | Your code rewrites the whole file, or a part of it, itself |
| Reject a bad record | Your code, in every program that writes the file |
| Share the file between programs | Nobody: each program must agree on the format by hand |
| Survive a crash half way through a write | Nobody, unless you build it |
| Answer a new question | A new function that reads every line again |
Notice that finding a record is a scan: a read of every record from the start until you find a match. The cost of a scan grows with the size of the file. Ten orders are quick to scan. Ten crore are not. A database avoids most scans with an index, which a later chapter covers.
Look at the last rows of the table. They are about time and change, not about format. A file format can be perfect and still fail when two programs write at once, when a save stops half way, or when the questions change every week. Those failures are not bugs in one program. They come from the file having no rules of its own.
An order log in a file
This script appends three orders to orders.jsonl, reads them back and answers one question about one customer. It is a perfectly good design for one program that runs alone.
import { appendFileSync, readFileSync } from 'node:fs' const file = 'orders.jsonl' type Order = { id: number; customer: string; qty: number } function addOrder(order: Order) { appendFileSync(file, JSON.stringify(order) + '\n') } function allOrders() { return readFileSync(file, 'utf8') .split('\n') .filter((line) => line.length > 0) .map((line) => JSON.parse(line)) } addOrder({ id: 1, customer: 'Meera', qty: 2 }) addOrder({ id: 2, customer: 'Arjun', qty: 5 }) addOrder({ id: 3, customer: 'Meera', qty: 1 }) const orders = allOrders() console.log(`${orders.length} orders on disk`) const total = orders .filter((o) => o.customer === 'Meera') .reduce((sum, o) => sum + o.qty, 0) console.log(`Meera has ordered ${total} items`)
3 orders on disk Meera has ordered 3 items
The program prints this.
The file itself holds one JSON object per line. This is what a plain text editor would show.
{"id":1,"customer":"Meera","qty":2}
{"id":2,"customer":"Arjun","qty":5}
{"id":3,"customer":"Meera","qty":1}Run the same script a second time and it prints this.
6 orders on disk Meera has ordered 6 items
The file now holds orders 1, 2 and 3 twice, and Meera seems to have ordered six items. Appending never looks at what is already there. Nothing in the file says that an order id must be unique, so nothing refuses the second copy. A rule like that is a key: a field, or set of fields, whose value must identify exactly one record. With a file, enforcing a key means reading every line before each append, in every program that writes. A database declares the key once and checks it on every write.
Check yourself
What does the operating system know about the records you store in a file?
- Nothing. It stores and returns bytes.
- The format and the meaning of each field live in your code, so every program that reads the file must agree on them.
Why is finding one order in a JSON Lines file called a scan?
- The program has no way to jump to a record, so it reads lines from the start until one matches.
- The work grows with the size of the file.
You run the order script twice and it reports six orders and six items for Meera. What went wrong, and what would have prevented it?
- The second run appended the same three orders again. Appending does not check what is already in the file.
- A key on the order id, checked on every write, would have refused the duplicates. A database enforces it once for every program.
Part 2 · Two writers, one file
Read, modify, write
Real applications run more than one process: a web server with several workers, a nightly job beside the app, a script someone runs by hand. They can all touch the same file.
Take a counter, such as the number of orders placed today. To add one you must read the number, modify it in memory, and write it back. This sequence is called a read-modify-write. Between your read and your write, the value in the file can change under you, and your write will then overwrite it with an old answer.
A race condition is a bug whose result depends on the timing of two actions. A lost update is the race condition you get here: two writers each build their change on the same old value, and the second write wipes out the first.
The next scene shows the order of events. Both processes read 10, so both compute 11. The file should now say 12 and says 11.
The race, step by step
Watch for both processes reading the same value before either writes
Read it as steps
Both read 10, both write 11, one increment disappears.
Notice that neither process did anything wrong on its own. Each ran correct code. The bug lives in the gap between the read and the write, which the file format cannot close, because a file has no notion of "this value is being changed right now".
Running the race
Here are two programs. bump.ts adds one to the counter file 2,000 times. It also counts the reads that returned an empty string, for a reason you will see below. race.ts starts two copies at once and compares the final number with the 4,000 it should be.
import { readFileSync, writeFileSync, appendFileSync } from 'node:fs' const times = Number(process.argv[2]) let emptyReads = 0 for (let i = 0; i < times; i++) { const text = readFileSync('counter.txt', 'utf8') if (text === '') emptyReads++ writeFileSync('counter.txt', String(Number(text) + 1)) } appendFileSync('empty-reads.txt', `${emptyReads}\n`)
import { spawn } from 'node:child_process' import { readFileSync, writeFileSync, rmSync } from 'node:fs' writeFileSync('counter.txt', '0') rmSync('empty-reads.txt', { force: true }) const each = 2000 function run(): Promise<void> { return new Promise((resolve) => { const child = spawn(process.execPath, ['bump.ts', `${each}`]) child.on('exit', () => resolve()) }) } await Promise.all([run(), run()]) const final = Number(readFileSync('counter.txt', 'utf8')) const want = each * 2 console.log(`expected ${want}, found ${final}, lost ${want - final}`) const raw = readFileSync('empty-reads.txt', 'utf8') const empties = raw.trim().split(/\s+/) console.log(`reads that saw an empty file: ${empties.join(' and ')}`)
Three runs follow. The numbers change from run to run because they depend on how the operating system schedules the two processes. Expect different values on your machine.
expected 4000, found 21, lost 3979 reads that saw an empty file: 259 and 237 expected 4000, found 21, lost 3979 reads that saw an empty file: 253 and 287 expected 4000, found 13, lost 3987 reads that saw an empty file: 259 and 272
The result is far worse than one lost update here and there. Almost every increment is lost. The empty-read counts say why. writeFileSync first empties the file and then writes the new text, so for a moment the file holds nothing. A process that reads in that moment gets an empty string, and Number("") is 0. The counter then restarts from 1.
So two failures stack up: a stale read, which is the lost update, and a read of a half-finished write, which is a first look at the next lesson.
Locking by hand, and what it costs
You can stop the race by letting only one process work at a time. A lock is a marker that says "I am using this, wait". Opening a file with the flag wx fails if the file already exists, so creating a file named counter.lock works as a lock: whoever creates it holds the lock, and deleting it releases the lock.
import { readFileSync, writeFileSync, rmSync } from 'node:fs' import { openSync, closeSync } from 'node:fs' const times = Number(process.argv[2]) function lock() { for (;;) { try { closeSync(openSync('counter.lock', 'wx')) // fails if it exists return } catch { // someone else holds the lock: try again } } } for (let i = 0; i < times; i++) { lock() const n = Number(readFileSync('counter.txt', 'utf8')) writeFileSync('counter.txt', String(n + 1)) rmSync('counter.lock') }
expected 4000, found 4000, lost 0 expected 4000, found 4000, lost 0
Two runs of the locked version.
Now no increment is lost. But the fix is yours to maintain. If a process crashes while it holds the lock, counter.lock stays on disk and every other process waits forever, so you would need a rule for deciding that a lock is stale. The loop above also spins at full speed while it waits. A database has locking built in, with rules for both problems.
Two processes read the value 10 and both write back 11. What is this bug called, and what is the correct final value?
- It is a lost update, a kind of race condition.
- The correct value is 12, because two increments happened.
In the runs the counter ended at 21, 21 and 13, not at about half of 4,000. Why so low?
- writeFileSync empties the file before it writes, so many reads saw an empty file and turned it into 0.
- The counter kept restarting, so lost updates were not the only cause.
What new problem does a hand-made lock file bring?
- A process that crashes while holding the lock leaves the file behind, and everyone else waits forever.
Part 3 · A crash in the middle of a write
Writing is not one step
Even with one writer, a file can be damaged. The reason is that "save this file" is several operations, and a crash can land between any two of them.
When your program calls writeFileSync, Node asks the operating system to open the file, and the flag w truncates it: the old content is thrown away at once. Then the new bytes are written. The operating system usually holds them in memory first and flushes them to the disk later. If the process or the machine stops half way, the file holds a new beginning and no end, or nothing at all.
A file in that state is a torn write: part new, part missing. The SQLite documentation on atomic commit goes further. It does not even assume that one disk sector is written atomically: a power failure in the middle of a sector write can leave part of the sector changed and part not. It also assumes that the operating system buffers writes and may reorder them, which is why SQLite calls fsync at fixed points. Careful programs flush explicitly and order their steps for the same reasons.
There are two levels of failure. A process crash kills your program but the operating system survives and still holds buffered bytes. A power loss or operating system crash loses whatever was not yet on the disk. This lesson can demonstrate the first. It cannot demonstrate the second on this machine, so what the fsync step protects against is explained from the documentation, not shown.
Write to a temp file, then rename
The standard fix has three steps. Write the new content to a temporary file next to the real one. Call fsync on it, which asks the operating system to push that file's bytes to the storage device before it returns. Then rename the temporary file over the real one.
On Linux the manual page for rename says that when the new name already exists it is replaced atomically: there is no moment at which another process finds the name missing. So a reader opens either the whole old file or the whole new file. A crash before the rename leaves the old file untouched and a stray temp file you can delete. The commit point is the rename.
Watch for the old file staying valid while the temp file is half written
Read it as steps
A crash before the rename leaves the old file untouched.
The order matters. If you renamed first and flushed later, a power loss could leave the real name pointing at a file whose bytes never reached the disk.
Power loss needs one more step. The Linux manual page for fsync says that flushing a file does not necessarily put the directory entry that names it on disk; that takes an fsync of the directory too. The rename changes the directory, so a fully durable save on Linux also flushes the directory after the rename. The run below leaves that step out and does not test power loss.
A killed writer, with and without the fix
writer.ts saves a file holding 2,000 orders. In unsafe mode it writes straight into state.json. In safe mode it writes state.json.tmp, calls fsync and renames. With the argument stop it prints a line after writing half of the text and then waits, so the parent can kill it at exactly that point. A real crash lands at an arbitrary moment, so this is a stand-in that makes the demonstration repeatable.
import { openSync, writeSync, fsyncSync } from 'node:fs' import { closeSync, renameSync } from 'node:fs' const [mode, when] = process.argv.slice(2) const orders = Array.from({ length: 2000 }, (_, i) => ({ id: i + 1, customer: `customer-${i % 40}`, qty: 1 + (i % 5), })) const text = JSON.stringify({ version: 2, orders }) const half = Math.floor(text.length / 2) function pause() { console.log('half written') Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20000) } const target = 'state.json' const path = mode === 'safe' ? 'state.json.tmp' : target const fd = openSync(path, 'w') // 'w' empties the file first writeSync(fd, text.slice(0, half)) if (when === 'stop') pause() writeSync(fd, text.slice(half)) fsyncSync(fd) // ask the OS to push the bytes to disk closeSync(fd) if (mode === 'safe') renameSync(path, target) console.log('done')
torn.ts starts a writer, kills it when it reports half way, and then tries to parse state.json.
import { spawn } from 'node:child_process' import { readFileSync, writeFileSync } from 'node:fs' import { existsSync, rmSync } from 'node:fs' function readState(): string { try { const s = JSON.parse(readFileSync('state.json', 'utf8')) return `valid, version ${s.version}, ${s.orders.length} orders` } catch (e) { const why = (e as Error).message.split(' at ')[0] return `broken: ${why}` } } // Start a writer, kill it as soon as it reports it is half way. function crashDuring(mode: string): Promise<void> { return new Promise((resolve) => { const child = spawn(process.execPath, ['writer.ts', mode, 'stop']) child.stdout.on('data', (d) => { if (String(d).includes('half written')) child.kill() }) child.on('exit', () => resolve()) }) }
for (const mode of ['unsafe', 'safe']) { rmSync('state.json.tmp', { force: true }) const v1 = { version: 1, orders: [] } writeFileSync('state.json', JSON.stringify(v1)) console.log(`${mode}: before the crash -> ${readState()}`) await crashDuring(mode) console.log(`${mode}: after the crash -> ${readState()}`) const left = existsSync('state.json.tmp') console.log(`${mode}: leftover temp file: ${left}`) } const finish = spawn(process.execPath, ['writer.ts', 'safe', 'finish']) await new Promise((resolve) => finish.on('exit', resolve)) console.log(`safe, no crash: -> ${readState()}`)
Check yourself
Why does a crash in the middle of writeFileSync damage the file?
- The write first truncates the file, then writes the new bytes in steps.
- A stop between the steps leaves part of the new content or none of it, and the old content is already gone.
In the temp-file method, which step is the commit point?
- The rename. Before it, readers see the whole old file. After it, they see the whole new file.
What does fsync add that rename alone does not give?
- It makes the temp file's bytes reach the storage device before the rename.
- Without it, a power loss after the rename could leave the real name pointing at a file with missing bytes.
Part 4 · Duplicated data, missing rules, ad hoc questions
The same fact in two places
Files rarely stay alone. The order code has one file, the billing code has another, and both store the customer's phone number. Each file is then a copy of the same fact.
Copies drift. When the number changes, someone must update every copy, and nothing reminds them. When one is missed, the data disagrees with itself: the same customer has two phone numbers, and no program can tell which is right. This kind of duplication is called redundancy, and the disagreement it causes is an inconsistency.
A second gap is rules. A rule such as "quantity must be positive" is called a constraint. A file has no place to state one. Every program that writes the file would need to check it, and one forgotten check lets a bad record in for good.
import { writeFileSync, readFileSync } from 'node:fs' // Two files that both carry the customer's phone number. const orders = [ { id: 1, customer: 'Meera', phone: '0900011122', qty: 2 }, { id: 2, customer: 'Meera', phone: '0900011122', qty: 1 }, ] const invoices = [ { invoice: 'INV-1', customer: 'Meera', phone: '0900011122' }, ] writeFileSync('orders2.json', JSON.stringify(orders)) writeFileSync('invoices.json', JSON.stringify(invoices)) // Meera changes her number. The orders code updates its file only. const fresh = JSON.parse(readFileSync('orders2.json', 'utf8')) for (const o of fresh) o.phone = '0900033344' writeFileSync('orders2.json', JSON.stringify(fresh)) const a = JSON.parse(readFileSync('orders2.json', 'utf8'))[0].phone const b = JSON.parse(readFileSync('invoices.json', 'utf8'))[0].phone console.log(`orders file says ${a}, invoices file says ${b}`) // Nothing stops a nonsense record either. const bad = JSON.parse(readFileSync('orders2.json', 'utf8')) bad.push({ id: 3, customer: 'Arjun', phone: '0900055566', qty: -4 }) writeFileSync('orders2.json', JSON.stringify(bad)) console.log('saved an order with qty -4 without any complaint')
orders file says 0900033344, invoices file says 0900011122 saved an order with qty -4 without any complaint
A new question means new code
The third gap is questions. Suppose someone asks for the number of items ordered per city. The city is not in the order file. It sits in a customer file, so you would load both, match customers to orders by hand, group the results and sort them. Next week the question changes and you write that code again.
A database system offers a language for questions, and a place to state the rules and keep each fact once. The next block runs the same data in PGlite, a PostgreSQL engine that runs inside Node. Results are printed with a small helper, show, which lays rows out as an aligned table and prints NULL for a missing value.
import { PGlite } from '@electric-sql/pglite' import { show } from '../show.ts' const db = new PGlite() await db.exec(` CREATE TABLE customers ( customer_id int PRIMARY KEY, name text NOT NULL, city text NOT NULL, phone text NOT NULL ); CREATE TABLE orders ( order_id int PRIMARY KEY, customer_id int NOT NULL REFERENCES customers (customer_id), qty int NOT NULL CHECK (qty > 0) ); INSERT INTO customers (customer_id, name, city, phone) VALUES (1, 'Meera', 'Pune', '0900011122'), (2, 'Arjun', 'Chennai', '0900055566'); INSERT INTO orders (order_id, customer_id, qty) VALUES (1, 1, 2), (2, 1, 1), (3, 2, 5); `)
try { await db.query( `INSERT INTO orders (order_id, customer_id, qty) VALUES ($1, $2, $3)`, [4, 2, -4]) } catch (e) { const err = e as { code: string; constraint: string } console.log(`rejected: ${err.code}, constraint ${err.constraint}`) } // One phone number, stored once, so changing it changes it everywhere. await db.query('UPDATE customers SET phone = $1 WHERE customer_id = $2', ['0900033344', 1]) show((await db.query(` SELECT o.order_id, c.name, c.phone FROM orders o JOIN customers c USING (customer_id) ORDER BY o.order_id`)).rows) // A new question needs no new code, only a new query. const r = await db.query(` SELECT c.city, SUM(o.qty) AS items FROM orders o JOIN customers c USING (customer_id) GROUP BY c.city ORDER BY items DESC`) show(r.rows)
rejected: 23514, constraint orders_qty_check order_id | name | phone ---------+-------+----------- 1 | Meera | 0900033344 2 | Meera | 0900033344 3 | Arjun | 0900055566 (3 rows) city | items --------+------ Chennai | 5 Pune | 3 (2 rows)
The error code 23514 is PostgreSQL's code for a failed CHECK constraint.
What each gap maps to
The bad row was refused by the database, with a code a program can test. The phone number is stored once, in the customers table, so one update changed it for both of Meera's orders: the join shows the new number on orders 1 and 2. Orders do not hold a copy of the phone. They hold the customer id, and the join looks the number up when the question is asked. The new question needed one query and no loops.
The values also travel as parameters, $1, $2 and $3, separate from the SQL text. The database receives the statement and the values apart, so a value can never be read as part of the command. This is called a parameterised query, and it is the normal way to send values from code.
| Failure with files | What a database system provides |
|---|---|
| Lost updates | Concurrency control: locks and snapshots, covered in a later chapter |
| Torn writes | A write-ahead log and crash recovery |
| Duplicated data | Keys and foreign keys, so each fact is stored once and referenced |
| Missing rules | Constraints such as CHECK, NOT NULL and UNIQUE |
| A new question, new code | A query language, SQL |
A file is still the right tool for some jobs, such as logs, exports and configuration. The point is not that files are bad. It is that once several programs, several writers and several questions arrive, you are rebuilding a database system by hand, with fewer guarantees.
| Term | Meaning |
|---|---|
| Lost update | A write based on an old read that overwrites a newer write |
All chapters · Previous: The Database Interview: Rounds, Scoring and a Study Plan