# DBMS Engineering Coding Style

Ten checkable rules for writing database code, from the DBMS Engineering Group. Inspired by Gerard Holzmann's Power of Ten (NASA/JPL) and TigerBeetle's TigerStyle.

Source: https://style.dbms.engineering

## 1. Keep control flow simple

A corrupt page lists itself as its own child. Recursion follows it down, and down, until the stack gives up.

Write loops and branches a reader can follow from top to bottom. Do not use recursion, even to walk a tree.

**Why.** Trees are everywhere in a database, and recursion is the natural way to walk one. It also lets a corrupt child pointer turn a lookup into a stack overflow. A loop with a maximum height fails with an error you chose.

**Check.** The call graph has no cycles. Every tree walk names its maximum height.

```rust
const LEVEL_MAX: u32 = 8;

fn find_leaf(pool: &Pool, root: PageId, key: Key) -> Result<PageId, Error> {
    let mut page_id = root;
    for _ in 0..LEVEL_MAX {
        let page = pool.read(page_id)?;
        if page.is_leaf() {
            return Ok(page_id);
        }
        page_id = page.child_for(key);
    }
    // Fan-out 100 reaches 10^16 entries in 8 levels.
    // A deeper tree has a cycle.
    Err(Error::TreeTooDeep)
}
```

- **Power of Ten:** Rule 1: simple control flow, with no goto, setjmp, longjmp or recursion.
- **TigerStyle:** Simple, explicit control flow, and no recursion.
- **What we changed:** We name the case that tempts database engineers most: walking a tree.

## 2. Put a limit on everything

Traffic doubles on a Friday evening. The queue says yes to everyone, until the machine says no.

Give every loop, queue, batch, retry and buffer a maximum. When the limit is reached, push back on the caller.

**Why.** A queue without a limit has one anyway: the machine's memory. You meet it under peak load, when it is hardest to recover. A limit written in the code shows up in tests, and it turns overload into a clear answer.

**Check.** Every queue has a named capacity constant and a test that fills it.

```rust
const IN_FLIGHT_MAX: u32 = 64;

fn submit(&mut self, read: Read) -> Result<(), QueueFull> {
    assert!(self.in_flight <= IN_FLIGHT_MAX);
    if self.in_flight == IN_FLIGHT_MAX {
        return Err(QueueFull); // The caller decides what waits.
    }
    self.ring.push(read);
    self.in_flight += 1;
    Ok(())
}
```

- **Power of Ten:** Rule 2: every loop has a fixed upper bound that a tool can prove.
- **TigerStyle:** Put a limit on everything, because everything has one.
- **What we changed:** We extend the bound to retries and in-flight I/O, and require back-pressure.

## 3. Allocate memory at startup

The transaction is halfway done when the allocator says there is nothing left. Now what?

Reserve memory for pages, sort runs and connections when the process starts. After that, reuse it.

**Why.** A database should know how much memory it needs before it accepts a query. Reserving it up front removes a class of failures halfway through a transaction, along with the latency of allocation on hot paths.

**Check.** A test allocator counts calls after startup. On the read and write paths, the count stays at zero.

```rust
fn new(frame_count: u32) -> BufferPool {
    assert!(frame_count >= FRAME_COUNT_MIN);
    assert!(frame_count <= FRAME_COUNT_MAX);

    // The pool makes no other allocation.
    let frames: Box<[Frame]> = (0..frame_count)
        .map(|_| Frame::empty())
        .collect();

    BufferPool { frames, clock_hand: 0 }
}
```

- **Power of Ten:** Rule 3: no dynamic memory allocation after initialization.
- **TigerStyle:** All memory is allocated statically at startup.
- **What we changed:** We require it on read and write paths. Planning and setup code may allocate.

## 4. Keep functions under 70 lines

The bug is on line 94. The condition that causes it is on line 11. Your screen shows 50 lines.

A function fits on one screen. Let the parent make the decisions and let small helpers do the work.

**Why.** Most review mistakes happen at the edge of the screen, where the condition is out of sight and its effect is not. Splitting by decision keeps the state machine in one place and makes each helper easy to test.

**Check.** A lint fails the build at line 71.

```rust
fn execute(&mut self, batch: &Batch) -> Result<(), Error> {
    assert!(batch.len() > 0);
    assert!(batch.len() <= BATCH_MAX);

    // The parent decides. Each helper does one thing.
    for operation in batch.operations() {
        match operation {
            Operation::Insert(row) => self.insert(row)?,
            Operation::Delete(key) => self.delete(key)?,
            Operation::Seek(key) => self.seek(key)?,
        }
    }
    Ok(())
}
```

- **Power of Ten:** Rule 4: no function longer than a printed page, about 60 lines.
- **TigerStyle:** A hard limit of 70 lines. Decisions move up, loops move down.
- **What we changed:** We keep TigerStyle's number and its advice on how to split.

## 5. Assert what must be true

One bit flips on a disk in a quiet data center. Nobody notices. Your checksum does.

Average at least two assertions per function. Check each page before it is written, and verify it again when it is read.

**Why.** An assertion catches a mistake in our code at the moment it happens. Bad data from a disk is different: hardware does that, so the read path returns an error the system can repair. Checking at both ends tells the two apart.

**Check.** Assertion density is reported in review. Every on-disk structure has a write check and a read check.

```rust
fn write_page(&mut self, page: &Page) -> Result<(), Error> {
    // A failure here is our mistake, so we stop.
    assert!(page.id != PageId::NONE);
    assert!(page.checksum == crc32(page.body()));
    self.disk.write(page)
}

fn read_page(&self, id: PageId) -> Result<Page, Error> {
    let page = self.disk.read(id)?;
    // A failure here is a disk error, so a replica can repair it.
    if page.checksum != crc32(page.body()) {
        return Err(Error::Corrupt(id));
    }
    if page.id != id {
        return Err(Error::Misdirected(id));
    }
    Ok(page)
}
```

- **Power of Ten:** Rule 5: at least two assertions per function, with a recovery action.
- **TigerStyle:** Assert in pairs: check the same property on two code paths.
- **What we changed:** We separate programmer errors, which assert, from disk errors, which return.

## 6. Keep every value close

One counter says 1,000 rows. Another says 999. Both are certain.

Declare a variable where it is first used, in the smallest scope that works. Keep one copy of each fact.

**Why.** When a value is wrong, you have to read every line that could have changed it. A small scope makes that a short list. A second copy of a fact, such as a cached row count, is a second chance to be wrong.

**Check.** Lints flag unused and shadowed variables. Reviewers ask what else holds the same fact.

```rust
fn insert(&mut self, row: &[u8]) -> Result<Slot, PageFull> {
    if self.free_bytes() < row.len() + SLOT_SIZE {
        return Err(PageFull);
    }

    // No other code can change this offset.
    let offset = self.free_end() - row.len();
    self.bytes[offset..offset + row.len()].copy_from_slice(row);
    Ok(self.push_slot(offset, row.len()))
}
```

- **Power of Ten:** Rule 6: declare data at the smallest possible scope.
- **TigerStyle:** Shrink scope, and do not duplicate or alias variables.
- **What we changed:** We apply it to stored facts too. A cached count needs an owner.

## 7. Handle every error

The database said “committed”. The disk never agreed to that.

Check every result. Never tell a client a write is durable until the disk has confirmed it.

**Why.** After a failed fsync, Linux may mark the unwritten pages clean. Calling fsync again can then succeed although the data is gone. PostgreSQL changed its behavior after this came to light in 2018. The safe response is to stop and recover from the log.

**Check.** Compiler warnings for unused results are errors. Tests make each system call fail at least once.

```rust
fn commit(&mut self, record: &[u8]) -> Result<(), Error> {
    assert!(record.len() > 0);
    self.file.write_all(record)?;

    if let Err(error) = self.file.sync_data() {
        // Do not try again. The kernel can drop the pages,
        // and a second sync can then succeed without them.
        panic!("wal sync failed: {error}");
    }
    Ok(()) // The client can now know.
}
```

- **Power of Ten:** Rule 7: check every return value and every parameter.
- **TigerStyle:** All errors must be handled.
- **What we changed:** We add the durability promise: no acknowledgement before a confirmed sync.

## 8. Make every byte explicit

You upgrade the compiler, and the compiler moves a field. Last year’s files now mean something else.

Give each field on disk or on the wire a fixed size, offset and byte order. Leave no hidden padding.

**Why.** Files outlive the program that wrote them. If a layout depends on the compiler or the machine, the next version may not be able to read it. Uninitialized padding can also leak old memory into a file.

**Check.** Compile-time assertions fix the size of each structure. Reserved bytes must be zero on read.

```rust
// The file format is little-endian. Encode and decode convert each field.
#[repr(C)]
struct PageHeader {
    checksum: u32,
    version: u16,
    kind: u16,
    page_id: u64,
    lsn: u64,
    slot_count: u16,
    free_start: u16,
    free_end: u16,
    reserved: [u8; 2], // These bytes are always zero.
}

const _: () = assert!(size_of::<PageHeader>() == 32);
```

- **Power of Ten:** Rule 8: limit the preprocessor, so code means what it says.
- **TigerStyle:** Use explicitly sized types, and watch for buffer bleeds.
- **What we changed:** Our largest change. We move the idea from hidden code to hidden bytes.

## 9. Name pages, not addresses

You kept the address. The pool moved on. You are now reading somebody else’s rows.

Refer to a page by its ID and pin it while in use. Do not hold a raw pointer into the buffer pool.

**Why.** A frame is borrowed. Once the pool evicts a page, the same address holds a different one, and a saved pointer reads the wrong data without an error. An ID is looked up each time, so it finds the right page or none.

**Check.** Page access goes through a guard that unpins when dropped. Unsafe code needs a written reason.

```rust
fn read_row(&self, id: RowId) -> Result<Row, Error> {
    // The pool cannot evict a pinned page.
    let page = self.pool.pin(id.page)?;
    assert!(page.id() == id.page);

    let row = page.row(id.slot)?;
    Ok(row.to_owned())
    // The guard drops here and unpins the page.
}
```

- **Power of Ten:** Rule 9: one level of dereference, and no function pointers.
- **TigerStyle:** Do not alias variables. Construct large structs in place.
- **What we changed:** We turn pointer discipline into page discipline: IDs and pins.

## 10. Let machines check it daily

It fails once in ten million runs, always on a weekend. With the seed, it fails whenever you like.

Build with every warning on and allow none. Run a simulator that injects faults, and make every failure replay from its seed.

**Why.** The worst database bugs need a crash, a slow disk and bad timing together. You will not write that test by hand. A simulator can try many combinations a day, and a seed turns a rare failure into one you can debug.

**Check.** CI blocks on warnings. Each night runs new seeds. Each failing seed becomes a regression test. Commit and recovery protocols have a checked model.

```sh
set -eu

cargo fmt --check
cargo clippy --all-targets -- --deny warnings
cargo test

# A failure prints its seed. The same seed replays the failure.
cargo run --release --bin simulator -- --seed "$SEED"
```

- **Power of Ten:** Rule 10: all warnings on from day one, and daily static analysis.
- **TigerStyle:** The strictest compiler settings, with the VOPR simulator as a final check.
- **What we changed:** We require replayable seeds, so a newcomer can reproduce any failure.

## Formal verification

- **Property testing.** Does this property hold for many random inputs? It samples inputs, so it can miss the bad one. Use it for: Encoders, page splits and comparators. Tools: [proptest](https://github.com/proptest-rs/proptest).
- **Deterministic simulation.** Does the real system survive faults in many schedules? It samples schedules, but each failure replays. Use it for: Replication, recovery and storage faults. Tools: [VOPR](https://github.com/tigerbeetle/tigerbeetle), [turmoil](https://github.com/tokio-rs/turmoil).
- **Model checking a design.** Can any order of steps in this design break the rule? It checks the model, up to a chosen size. Your code can differ. Use it for: Commit, recovery and consensus protocols. Tools: [TLA+](https://lamport.azurewebsites.net/tla/tla.html), [Alloy](https://alloytools.org).
- **Model checking code.** Can any input, or any thread order, break this function? Loops and threads need a bound, and large code takes too long. Use it for: Page headers, latches and lock-free queues. Tools: [Kani](https://model-checking.github.io/kani/), [Loom](https://github.com/tokio-rs/loom).
- **Deductive proof.** Is this function correct for every input of every size? You write the proof, and it is only as good as the specification. Use it for: Small kernels that everything else trusts. Tools: [Verus](https://github.com/verus-lang/verus), [Dafny](https://dafny.org).

A change to commit, recovery or replication comes with a model. The TLA+ example is at https://style.dbms.engineering/formal/WriteAheadLog.tla

## Comments

Write comments in standard technical English. Say why the code is there, in short sentences with one meaning.

- **Say why.** Before: `// increment retries` After: `// The replica can be behind by one view, so we try again.`
- **Write whole sentences.** Before: `// off by one??` After: `// The last slot holds the footer, so the loop stops before it.`
- **Give numbers and units.** Before: `// wait a bit for disk` After: `// The disk needs at most 5 ms to finish a flush.`
- **Name who acts.** Before: `// page is released` After: `// The guard releases the page when it drops.`
- **Use one word for one thing.** Before: `// put block in slot, then pin buffer` After: `// Load the page into the frame. Then pin the frame.`
- **Leave the jokes out.** Before: `// here be dragons, don't touch` After: `// Both locks are necessary. Without them, two writers can change one page.`

## Credits

- Gerard J. Holzmann, NASA/JPL Laboratory for Reliable Software. "The Power of 10: Rules for Developing Safety-Critical Code." IEEE Computer 39(6), 2006. https://spinroot.com/gerard/pdf/P10.pdf
- TigerBeetle, Inc. TigerStyle. https://tigerstyle.dev
- ASD-STE100 Simplified Technical English, for the comment standard. https://asd-ste100.org/about_STE.html

The source rules are paraphrased. The DBMS Engineering Group is not affiliated with NASA, JPL or TigerBeetle, and neither has reviewed or endorsed this guide.
