Colour theme

DBMS Engineering
Coding Style

How we write code that keeps data.

Inspired by Gerard Holzmann’s Power of Ten at NASA/JPL, and by TigerStyle from TigerBeetle.

Safe, then fast, then clear

When two goals conflict, the earlier one wins. The order comes from TigerStyle, which puts safety before performance and performance before developer experience.

  1. Safe

    Committed data stays committed, through crashes, full disks and our own mistakes.

  2. Fast

    Performance is designed in with arithmetic, then confirmed by measurement.

  3. Clear

    Someone new to the project can read a function and know why it is right.

The ten rules

Each rule opens with something that could go wrong. The illustrations are yours to break, so press everything. Examples are in Rust, but the rules apply in any language.

1 of 10

Keep control flow simple

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

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

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.

Found 42 on level 3. The loop could never have passed 8.

2 of 10

Put a limit on everything

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

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

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.

Caller
Disk

IN_FLIGHT_MAX = 8

6 of 8 reads in flight.

3 of 10

Allocate memory at startup

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

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

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.

Hits
0
Misses
0
Frames
8
Allocations
0

Used since the last sweep

Eight frames, reserved at startup. Read pages and watch the clock hand pick which frame to reuse.

4 of 10

Keep functions under 70 lines

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

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

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.

One function of 118 lines. The last 48 are below the edge of the screen.

5 of 10

Assert what must be true

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

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

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.

44
42
4d
53
Checksum at write
f19978de
Checksum at read
f19978de

The page matches its checksum. Select any bit to damage it, as a failing disk would.

6 of 10

Keep every value close

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

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

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.

Declared at the top. Any of 14 lines may have changed offset before it is used.

7 of 10

Handle every error

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

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

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.

The disk confirmed the write, so the client hears that it is committed.

8 of 10

Make every byte explicit

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

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

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.

0
8
16
24

page_id: u64 at offset 8, 8 bytes. It catches a page written to the wrong place.

9 of 10

Name pages, not addresses

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

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

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.

The query keeps the address of frame 0, which holds page 4 for now.

10 of 10

Let machines check it daily

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

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

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.

72 seeds run. Seed 47 failed, and that number is all you need to see it again.

0 of 10 tried

Every illustration has a button. Press them. Nothing here is in production.

Take me there

Prove the hard parts

Tests try some paths. A model checker tries all of them, within the bounds you set. Here is a write-ahead log. Add a bug and watch the checker find it.

61 states, no way to break it

Two transactions, and a crash allowed at any moment. The checker visited every reachable state just now, in your browser.

Check the design

This is the protocol above in TLA+. Download the specification and its configuration to run it in TLC.

WriteAheadLog.tla

--------------------------- MODULE WriteAheadLog ---------------------------\* This model describes a write-ahead log. Every step can be followed by a crash.CONSTANT TxnVARIABLES log, page, acked, crashedvars == <<log, page, acked, crashed>>Init ==  /\ log = [t \in Txn |-> "none"]  /\ page = [t \in Txn |-> "clean"]  /\ acked = [t \in Txn |-> FALSE]  /\ crashed = FALSEModify(t) ==  /\ ~crashed  /\ log[t] = "none"  /\ log' = [log EXCEPT ![t] = "buffer"]  /\ page' = [page EXCEPT ![t] = "dirty"]  /\ UNCHANGED <<acked, crashed>>\* One sync makes every buffered record durable.Sync ==  /\ ~crashed  /\ \E t \in Txn : log[t] = "buffer"  /\ log' = [t \in Txn |-> IF log[t] = "none" THEN "none" ELSE "disk"]  /\ UNCHANGED <<page, acked, crashed>>WritePage(t) ==  /\ ~crashed  /\ page[t] = "dirty"  /\ log[t] = "disk"  /\ page' = [page EXCEPT ![t] = "disk"]  /\ UNCHANGED <<log, acked, crashed>>Acknowledge(t) ==  /\ ~crashed  /\ ~acked[t]  /\ log[t] = "disk"  /\ acked' = [acked EXCEPT ![t] = TRUE]  /\ UNCHANGED <<log, page, crashed>>\* A crash clears memory. The disk keeps its data.Crash ==  /\ ~crashed  /\ crashed' = TRUE  /\ log' = [t \in Txn |-> IF log[t] = "disk" THEN "disk" ELSE "none"]  /\ page' = [t \in Txn |-> IF page[t] = "disk" THEN "disk" ELSE "clean"]  /\ UNCHANGED ackedNext ==  \/ \E t \in Txn : Modify(t) \/ WritePage(t) \/ Acknowledge(t)  \/ Sync  \/ CrashSpec == Init /\ [][Next]_vars\* After a crash, the disk has the log record of each acknowledged transaction.Durability ==  crashed => \A t \in Txn : acked[t] => log[t] = "disk"\* A page reaches the disk only after its log record.WriteAhead ==  \A t \in Txn : page[t] = "disk" => log[t] = "disk"=============================================================================

Check the code

A correct design can still have a wrong implementation. Kani checks a Rust function against every input within its bounds.

page_header_proof.rs

#[kani::proof]fn header_round_trips() {    // Kani covers all 2^80 inputs without a separate run for each one.    let header = Header {        page_id: kani::any(),    // This field is a u64.        slot_count: kani::any(), // This field is a u16.    };    assert!(Header::decode(&header.encode()) == header);}

When we ask for it

  • A change to commit, recovery or replication comes with a model, and the model has a deliberate bug that the checker catches.
  • The pull request names each property, the bounds, and what the model leaves out.
  • Unsafe or lock-free code comes with a Kani or Loom check.
  • The model lives next to the code and runs in CI, so the two change together.
MethodThe question it answersWhat it cannot tell youUse it forTools
Property testingDoes this property hold for many random inputs?It samples inputs, so it can miss the bad one.Encoders, page splits and comparators.proptest
Deterministic simulationDoes the real system survive faults in many schedules?It samples schedules, but each failure replays.Replication, recovery and storage faults.VOPRturmoil
Model checking a designCan any order of steps in this design break the rule?It checks the model, up to a chosen size. Your code can differ.Commit, recovery and consensus protocols.TLA+Alloy
Model checking codeCan any input, or any thread order, break this function?Loops and threads need a bound, and large code takes too long.Page headers, latches and lock-free queues.KaniLoom
Deductive proofIs this function correct for every input of every size?You write the proof, and it is only as good as the specification.Small kernels that everything else trusts.VerusDafny

Methods go from the least effort to the most. The first two are testing, which can find bugs but cannot show their absence. TLA+ is the work of Leslie Lamport. For its use in industry, read How Amazon Web Services Uses Formal Methods (Newcombe et al., 2015).

You are the reviewer

Five changes are waiting for your approval. Each one breaks a rule. Catch them before they ship.

change 1 of 5

fn enqueue(&mut self, job: Job) {    self.jobs.push_back(job);}

Which rule does this break?

Write comments in standard technical English

Our readers speak many first languages, and some will read your comment in the middle of an outage. 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.

6 problems

  • basically Start with a capital letter.
  • soon End with a full stop.
  • fast Give a number, a unit or a name.
  • basically Delete it. The sentence means the same without it.
  • magic Use the literal term. Not every reader knows the idiom.
  • are flushed Say who does it, in the active voice, if the actor matters.

Inspired by ASD-STE100 Simplified Technical English, the controlled language for technical documentation, and by TigerStyle, where comments are sentences that say why. This is our own short version. It does not claim STE conformance.

Do the arithmetic first

The rules make code safe. Estimates make it fast. Before writing a component, work out what it asks of the network, disk, memory and CPU. Start with a batch of one, then raise it and watch the flushes.

100,000 tx/s
128 bytes
1 tx

The first limit is disk flushes, at 100× the budget. A batch takes 10 µs to fill.

  • Network12.8 MB/s of 1.25 GB/s, 1%
  • Disk bandwidth128.0 MB/s of 1 GB/s, 13%
  • Disk flushes100,000 /s of 1,000 /s, 100×
  • Memory51.2 MB/s of 20 GB/s, <1%
  • CPU0.50 cores of 8 cores, 6%

Assumes 10× write amplification, four memory copies, 5 µs of CPU per transaction, and one 1 ms flush at a time. Replace these with numbers measured on your hardware.

Sketching these four resources by bandwidth and latency is a TigerStyle practice. The calculator and its budgets are ours.

Where each rule comes from

Both sources are paraphrased here. Read the originals for the full wording and reasoning.

Our rulePower of TenTigerStyleWhat we changed
1. Keep control flow simpleRule 1: simple control flow, with no goto, setjmp, longjmp or recursion.Simple, explicit control flow, and no recursion.We name the case that tempts database engineers most: walking a tree.
2. Put a limit on everythingRule 2: every loop has a fixed upper bound that a tool can prove.Put a limit on everything, because everything has one.We extend the bound to retries and in-flight I/O, and require back-pressure.
3. Allocate memory at startupRule 3: no dynamic memory allocation after initialization.All memory is allocated statically at startup.We require it on read and write paths. Planning and setup code may allocate.
4. Keep functions under 70 linesRule 4: no function longer than a printed page, about 60 lines.A hard limit of 70 lines. Decisions move up, loops move down.We keep TigerStyle's number and its advice on how to split.
5. Assert what must be trueRule 5: at least two assertions per function, with a recovery action.Assert in pairs: check the same property on two code paths.We separate programmer errors, which assert, from disk errors, which return.
6. Keep every value closeRule 6: declare data at the smallest possible scope.Shrink scope, and do not duplicate or alias variables.We apply it to stored facts too. A cached count needs an owner.
7. Handle every errorRule 7: check every return value and every parameter.All errors must be handled.We add the durability promise: no acknowledgement before a confirmed sync.
8. Make every byte explicitRule 8: limit the preprocessor, so code means what it says.Use explicitly sized types, and watch for buffer bleeds.Our largest change. We move the idea from hidden code to hidden bytes.
9. Name pages, not addressesRule 9: one level of dereference, and no function pointers.Do not alias variables. Construct large structs in place.We turn pointer discipline into page discipline: IDs and pins.
10. Let machines check it dailyRule 10: all warnings on from day one, and daily static analysis.The strictest compiler settings, with the VOPR simulator as a final check.We require replayable seeds, so a newcomer can reproduce any failure.

With thanks to the people who wrote it first

The Power of Ten

Gerard J. Holzmann, NASA/JPL Laboratory for Reliable Software, 2006

Ten rules for safety-critical C, kept few enough to remember and strict enough for tools to check. We took the number, the demand that rules be checkable, and the starting point for every rule here.

Read the paperIEEE Computer 39(6)

TigerStyle

TigerBeetle, Inc.

It showed how the Power of Ten applies to a modern database. We took the order of values, the 70-line limit, paired assertions, the resource sketch, and the belief that good style is good design.

tigerstyle.devTIGER_STYLE.md

The DBMS Engineering Group is not affiliated with NASA, JPL or TigerBeetle, and neither has reviewed or endorsed this guide. Any mistakes are ours.

Break a rule in the open

Sometimes a rule is wrong for the code in front of you. Say so in a comment next to the exception, give the reason, and let review decide. If the reason keeps coming up, the rule should change.