Peter Mattis on B-Trees, Distributed Databases, and Writing Database-Grade Code with AI

Open on YouTube ↗
Overview

Peter Mattis co-created GIMP in college, helped build Gmail's original storage backend, was on the founding team of Google's Colossus file system, and co-founded Cockroach Labs, where he is CTO. By his own account he has been a prolific coder for 30 years: about 100,000 lines of production code in his peak pre-AI years. He then largely stopped coding between 2022 and 2024, and has returned with AI coding agents. In this conversation he says his current output is "a bit insane," and that it is database-quality code rather than throwaway prototypes.

32 min read

The conversation runs from his early projects through Google's storage infrastructure and the design of CockroachDB, then turns to how AI changed his work: why agents need firm direction on testing, what he expects to happen to code review, and why he thinks domain experts gain the most from these tools.

2:55

From Mechanical Engineering to GIMP

Mattis got into computers through games, and through a house that always had machines like the Apple II Plus and Apple IIGS; his mother had done programming at IBM. He typed in BASIC programs from books and magazines without really understanding them. He still started college as a mechanical engineering major, following his father, because he didn't think "there was any money in computers." In his first semester the engineering homework ran to six pages per problem, while a CS course he took at the same time seemed easy even though almost everyone else was failing it. He switched majors.

GIMP began because he and his roommate, Spencer (later his Cockroach Labs co-founder), were bored with a course, possibly a compilers course. Mattis had done journalism in high school, knew some computer graphics, and wanted to build something like Photoshop. They worked it out as they went, reading papers where they could. Mattis also wrote much of the graphics library, GTK, which has since evolved enormously. He argues you need some naivety to start a project like that: "if you know how hard it's going to be, you would never start it." Once you begin, the work snowballs.

He tells one story as a lesson for founders. A couple of weeks before their first public release, someone posted on a graphics Usenet group about their own graphics program, which apparently did everything GIMP did and more. The two students decided to release anyway. They never heard from that person again. His advice now: if you have an idea, a dozen other people have probably had it and a couple may be working on it, but most never follow through. Don't be put off by a pre-announcement, and treat competition as something to enjoy, not fear. He says the same applies to what Cockroach Labs is building now.

GIMP also shaped his career. The very first Google logo was made in GIMP, according to Mattis, and in 2001 Larry Page or Sergey Brin (he isn't sure which) looked him up and invited him to interview. Google was three years old. He turned it down because he lived in San Francisco and didn't want to commute to Mountain View. After a year at a startup that wasn't going anywhere, Google called again. He joined on April 1, 2002, with smaller stock options than the first offer, though he says he did fine. He also remembers people telling him they learned to program by reading GIMP's source, code he wrote 30 years ago when he "wasn't nearly as good a software engineer."

9:28

Building Gmail's Backend

At Google he joined an internal email project code-named Caribou, which became Gmail. A prototype built on Google's existing search and retrieval systems already existed and was then completely rewritten. Mattis worked on the rewrite: the backend for message threading, message storage, and indexing. He was on the project for about three years, through its launch on April 1, 2004. The date made the product look like an April Fool's joke.

The host recalled that free email accounts then offered around 10 MB. Mattis thought Hotmail or Yahoo Mail was at about 4 MB. Gmail offered roughly a gigabyte, and search came back almost instantly. Internally, he says, the launch was described as "a shock and awe campaign for the industry." Feasibility came from building on GFS, the Google File System, together with Google's search and retrieval expertise. Threading was a deliberate decision from the start, which he says was unusual for email then.

B-trees were part of the threading design. When a message arrived, the system used the search index to match its subject or message ID to a thread ID, and B-trees also tracked things like per-thread unread counts. He thinks it was his second B-tree implementation; he now counts about a dozen. He says all that code has since been rewritten.

On economics, the team estimated a per-user cost of "a couple dollars per year" and asked whether it could still be offered free. The answer took "a little bit of a leap of faith." Mattis credits Paul Buchheit, whom he says was not on his part of the work, with building ads into Gmail in one night by reusing existing ad functionality, which grew into a large business. Mattis wasn't involved in the invite-only launch either, but he recalls concern about load and says the invite system did two things: it throttled growth and it made invites something people wanted.

15:00

Google3, BUILD Files, and the Road to Bazel

Around the same time Mattis worked part-time on Google's build system. Google had a monorepo. The first version predated him, and by the time he arrived it was "Google 2," built around a single huge Makefile (possibly with some sub-makefiles) that was showing strain. Mattis laid some of the groundwork for Google3, alongside many others.

His idea was that Makefiles are like assembly language for dependencies: they can express everything, but writing them by hand is error-prone, and it's easy to miss a dependency. Google3 introduced BUILD files in a stripped-down Python dialect. A generator compiled them into a monolithic Makefile that nobody had to write by hand. Later, engineers realized the Makefile step could be dropped by implementing the dependency-update engine directly. That became Blaze internally, then Bazel externally, and engineers who went from Google to Facebook built Buck. The host noted that these systems matter for large codebases because they open up caching and other performance levers, and Mattis agreed.

17:29

Colossus and Erasure Coding

His storage work on Gmail, plus an unsuccessful research storage project, got him invited to the founding team of Colossus, GFS's successor. As far as he knows, it still exists at Google in some later form.

He compares Colossus to something like S3 from the outside: a flat namespace with little hierarchy, not a POSIX file system, and at first without full directories or permissions. Files are stored on a fleet of servers writing to hard drives (now SSDs), and replicated so that crashes don't lose data.

He calls erasure coding "a big breakthrough" for Colossus. Colossus used Reed-Solomon, though Mattis notes better codes now exist. GFS stored three full copies of everything. With Reed-Solomon, he recalls overhead around 2x, and he wasn't certain of the exact parameters. The result used less space and offered more redundancy. For a mental model he cites a scheme he thinks S3 has discussed publicly: split data into nine chunks such that any five can reconstruct it, so any four can be lost. Often the first five chunks are the data itself and the other four are parity, though he said he had forgotten some details. He admits he never fully understood the math, Galois fields and so on, and regrets not taking more math. But the math was proven decades earlier for communication networks, so the team's work was the engineering needed to make it run in a storage system.

The other big problem was scale. Mattis recalls GFS topping out around a thousand machines per cluster, and Google wanted ten thousand. The single GFS master holding metadata (file names, and for each file its list of 64 MB chunks, which the master scanned periodically for repair work) was a bottleneck. The team chose to put Colossus metadata in Bigtable. But Bigtable was GFS's biggest user and was supposed to run on Colossus, so there was a circular dependency. The solution was layered: a foundational Bigtable that didn't use Colossus, Colossus storing its metadata in that Bigtable, and ordinary Bigtable running on Colossus. Mattis says he is proud of this design and "a little bit embarrassed by" it. It ran for years before being replaced at some point he doesn't know. His lesson: use what you already have to get off the ground and remove it later. Building a proper metadata layer from scratch would have delayed Colossus.

24:00

Latency, Hardware, and "Speed of Light Numbers"

The host asked how distributed file systems deliver high throughput, high availability, and low latency together. Mattis's answer was that latency in these systems isn't actually very low. He says services like S3 and Google Cloud Storage (built on Colossus) have excellent throughput, but first-read latency is around 20–30 ms when data sits on hard disks. SSDs bring that down, though not to what state-of-the-art SSDs can do.

He is struck by how fast hardware has improved. By his figures, a hard-drive read is 5–10 ms, and an SSD read over NVMe is 30–50 microseconds. Network round trips were milliseconds when Colossus was built; within a zone at Google or Amazon he puts them around 100 microseconds now. "The hardware guys have really done a good job."

The host brought up Simon Eskildsen of Turbopuffer and "napkin math": design from what the hardware can theoretically do, not from what a human will notice. Mattis calls these "speed of light numbers." Human-facing design can think about 100 ms of tolerable delay, or about 4 ms per frame in games. Storage systems have to be designed for machine speeds. Sometimes the limit really is the speed of light, as with cross-zone and cross-region latency over fiber.

That led to a tangent. Mattis says the fastest way to send data across the globe is to send it up to space, bounce it between Starlink satellites, and bring it down on the other side, because light is slower in fiber than in near-vacuum. For shorter distances, such as New York to Chicago in high-frequency trading, he says the distance isn't long enough for satellites to pay off, and firms use microwave links instead.

He then turned to single machines. Getting top performance from multithreaded programs means avoiding synchronization, partly with lock-free programming but mainly by arranging work so locks aren't needed. It also means paying attention to the whole cache hierarchy: registers, L1, L2, L3, memory, disk. High-frequency trading firms think about this constantly. In his view most software ignores it and gradually gets slower.

30:10

Rethinking Standard Data Structures: B-Tree Maps and Swiss Tables in Go

Mattis loves data structures, and two of his side projects improved widely used libraries.

The first was at Google. A colleague working on Gaia, the internal system that maps logins and user IDs to user metadata, noticed that STL maps, which are balanced binary trees, were using a lot of memory and showing up in profiles. Every node traversed in a binary tree is a different cache line, and for a map from a 4-byte integer ID, two pointers per node is a lot of overhead. The colleague considered skip lists, which Mattis also recommends studying. Mattis thought the problem looked like a B-tree and built one that matched almost all of STL map's semantics. The exception was pointer stability, since inserting into a B-tree node shifts elements. If you don't need that property, the B-tree is both faster, thanks to spatial locality, and smaller, because it has fewer pointers.

His short explanation of B-trees: the best way to store about eight sorted items is a sorted array, not a tree, and a linear scan is often faster than binary search. When a ninth item arrives, split into two nodes of four and five and add a parent pointing to both. Recurse from there. He jokes that everyone should implement one, then says nobody should anymore, because tools can now write it with all the many optimizations included.

The host said they had assumed standard libraries are already as fast as they can be. Mattis's reply was that these improvements came from engineers who saw something odd in a profile and asked why. At the time, Google didn't have a dedicated team for internal libraries; engineers contributed to a shared codebase from their own projects.

The second project came years later, from outside Google, in Go. Mattis follows research on data structures. Hash tables are usually taught with chaining (linked lists per bucket) and open addressing (probing further slots). He read about Swiss tables, which he believes came from Google's Swiss office, though he wasn't sure. Several people had tried Swiss-table implementations for Go's built-in map, but Go's runtime map was already heavily optimized and hard to beat. Mattis worked on it on and off, then made real progress on a long flight to Bangalore for a business trip, getting some benchmarks to run faster. He combined ideas from others on the Go issue tracker, got help from the runtime team, and reached an implementation that was faster on most benchmarks, though not all. Cockroach Labs used it. Mattis stresses that putting it into the runtime was "a whole other level." The Go team took it over and finished it. He also mentions a colleague who contributed a fast CRC implementation based on Intel papers, as an example of outsiders contributing to the language.

Leaving Google: Viewfinder and an Acqui-hire

After Colossus, Mattis worked for a while on Google Goggles, which he calls a technology "before its time"; the Android phones then weren't powerful enough. He felt he might be stagnating and left to start Viewfinder, a mobile photo-sharing startup around 2012, alongside Instagram. He says they never worked out go-to-market or viral growth. Square acqui-hired the team for its engineers and got the IP, which he doesn't think Square ever used. The company had raised little money and repaid its investors roughly in full, maybe with a small haircut. That mattered to him: investors expect losses, "but you kind of feel bad."

44:16

From Spanner to CockroachDB

Mattis explains the difference between Colossus and Spanner, a sister project. Colossus is a distributed storage system for large, append-only files from 64 MB to gigabytes, which can't be updated in place. A database stores huge numbers of small, typed rows and columns, which is a different engineering problem. Distributed databases usually sit on a distributed storage system, as Spanner sits on Colossus. Colossus's append-only design pushed Spanner toward immutable files and log-structured merge trees. Google didn't invent LSM trees but popularized them with LevelDB, which came out of the Bigtable and Spanner work and led to RocksDB. Mattis later wrote Cockroach Labs' own LSM engine, Pebble.

The idea for CockroachDB came up at Viewfinder. Mattis, Spencer, and Ben Darnell (also a Google alum who joined Viewfinder) disliked the databases available compared with Google's internal Bigtable and Spanner. He mentions HBase and Riak. They sketched a design but set it aside: "guys, we're doing a mobile photo sharing site, we shouldn't build a distributed database." He adds that perhaps they should have pivoted. At Square they saw the same data-storage problems, and Spencer persuaded management to let him work on it part-time, then brought in Mattis and Darnell. Once it drew outside attention, they spun it out.

Viewfinder had avoided VC money, and Mattis says he wouldn't recommend that. The VCs he has worked with are "some of the sharpest people" he has met and offer market perspective that technical founders especially lack. Cockroach Labs raised money soon after a short Bay Area roadshow.

The name was Spencer's. Cockroaches are thought to be unkillable and to survive a nuclear apocalypse, and that was the goal for the database. (GIMP's name, Mattis adds, came from Pulp Fiction.) He describes a recent campaign called "performance under adversity," which he says showed an existing capability: run a workload, kill a node or sometimes a whole region, and the system keeps going. He says customers have reported data-center fires in which everything else went down and CockroachDB kept running.

50:04

Who Needs a Distributed Database, and Why Sharding Belongs in the Database

Mattis says companies often call after a disaster. He describes a large bank, which he didn't think he could name, that suffered a serious region-wide outage from a weather event. The CEO then issued a mandate that such failures couldn't happen again, and it flowed down the organization. Other customers hit capacity limits: one early customer on AWS reached the largest instance available. The standard next step is manual sharding into 10, 20, or 100 shards, which Google itself did for a while. Cockroach Labs' view is that the application developer then becomes a database developer "and they're doing it poorly," reimplementing distributed transactions and indexes. The company believes that burden belongs to the database.

On sharding, the simplest form works like a hash table: hash each user into one of a fixed number of shards. When a shard fills up, resharding may mean remapping everything, much like doubling a hash table and copying every entry. Consistent hashing, which he associates with Cassandra, reduces this so a new node takes only part of each shard's data. CockroachDB follows Bigtable, Spanner, and HBase instead. It treats all keys as one ordered keyspace, splits it into contiguous ranges, and keeps an index mapping ranges to nodes. "You squint," Mattis says, "and everything's either a B-tree or a hash table," and that range index looks a lot like a B-tree. B-trees also sit under most secondary indexes in databases. He cites the 1970s-era paper "The Ubiquitous B-Tree" and says nearly every data system he has worked on has contained B-trees somewhere.

55:35

Transactions, Consistency, and Raft

Mattis explains ACID. Durability means committed data survives crashes. Atomicity means a set of changes either all commit or all abort, which makes errors much easier for applications to handle. Isolation is where the real difficulty lies: transactions should run as concurrently as possible but appear to have happened in some serial order. Linearizability is the gold standard, and serializability is the step below it. Weaker levels allow anomalies such as the textbook bank example, where a $100 balance check lets the same $100 be withdrawn twice. He says these produce "very egregious bugs" in balances, shopping carts, and many other places.

Eventual consistency, where a write to a primary may not yet show up on a secondary, is faster but moves the burden to the application developer. CockroachDB offers strong consistency: you read what you wrote, whichever node you read from. When the host asked whether that means writing to every replica, Mattis said yes, and the engineering challenge is doing it fast. He sees this as a pattern across computing, with systems growing more sophisticated so applications stay simple, and compares it to graphics, which went from drawing individual pixels to GPUs rendering billions of triangles.

On consensus, he calls Raft an alternative to Paxos, which was notoriously hard to implement. Consensus is impossible with two replicas: after a crash, neither side can tell whether a write reached the other. It needs at least three. Writes go to all replicas, and reads normally come from one. The majority "consensus read" happens during recovery after a failure. CockroachDB typically uses three replicas, five for some system tables, and customers can choose five or seven, with more replicas costing more storage and more time. Spreading replicas across regions adds speed-of-light latency of tens to hundreds of milliseconds or more. Mattis's general rule for distributed databases is to avoid chatty round trips: issue reads in one parallel batch, then write. Alternating reads and writes accumulates latency.

"Mission critical" to him means "tier zero" systems: trading systems, banking, and also DoorDash, which he names as a customer, and shopping carts where downtime can cost hundreds of thousands to millions of dollars an hour. At Google, he says, the rule was that Gmail and Search could not go down. The bigger cost is reputational: "grandma won't be able to pay her rent." The company has "some hundreds" of people, perhaps 110 engineers and about 150 in R&D, and revenue he describes as growing steadily. Building a distributed database takes years of stabilization, quality work, performance work, and enterprise integration.

1:06:24

Stepping Away from Code, Then Coming Back

In CockroachDB's early years all three co-founders wrote a great deal of code. Mattis's peak was about 100,000 lines a year. Around 2019 he decided to replace RocksDB, and the Pebble rewrite was 40,000–50,000 lines from him before others joined. He compares that with an industry figure he cites of about 3,000 lines a month per engineer, roughly 36,000 a year. He also says there is a limit to how much anyone can hold in their head.

For years he was told that CTOs should stop coding and lead from above. He resisted, then agreed at some point, and says the advice was right at the time. From about 2022 to 2024 his output fell. The Go Swiss table was from that period, but he did little on the core product. Being in meetings all day as an executive leaves no room for coding.

AI brought him back. He started with GitHub Copilot and tried Cursor, which he calls "glorified autocomplete," surprisingly good at finishing functions. The company wanted engineers to use these tools, and someone argued that leaders had to use them to guide others: if you don't know how to be a good engineer, it's very hard to manage engineers. The early models weren't quite good enough, but he watched them improve, first Sonnet, then Opus.

The turning point was Thanksgiving last year. For a long time he had wanted a tool to benchmark CockroachDB across a large matrix of configurations: CPUs per node, disks per node, nodes per cluster. It never seemed important enough to prioritize, though he suspected something interesting was there. Over four days, working with an Opus model (4.5 or 4.7, he wasn't sure), "the code just materialized." He stopped typing. He compares it to films where hackers type at impossible speed, except now it works. Last month, he says, he implemented another B-tree: about 10,000 lines of highly optimized Rust in about 30 minutes.

That tool led to more. In the office of the CTO, which is charged with innovation, he was looking at better autoscaling for CockroachDB clusters. Around January he reached what he calls "kind of a research breakthrough," through design discussions with models as well as coding. He describes them as sparring partners that aren't always right but are encyclopedic, and that let you explore ideas very fast. He dislikes their sycophancy: "I hate that sycophancy, it kills me." Since then the company has been working toward a new launch, much of it built by agent-assisted engineers. He estimates close to 100% of engineers use AI to some extent and considers the code very high quality, with caveats he explains below.

He first compared working with agents to management. The host objected that management involves conflict, performance reviews, and other human work. Mattis agreed and refined it: it's more like being a tech lead, or a "hands-on architect," for a 30- to 40-person organization, without the management overhead. You can keep correcting the agents until they get it right, faster than with people. His conclusion is that "you just have to be more ambitious about everything you do."

1:17:31

AI in the Product and Across the Company

Cockroach Labs' thesis, as Mattis puts it, is that nearly all future applications will be written by AI. Some handcrafted software will remain, as people still write assembly, but the share of AI-generated code will approach 100%. Humans may keep supplying agency and vision for many years. He expects a surge in the number of applications, and says the company is building multiple things with that in mind.

Inside the company, an internal platform for mini-applications launched earlier this year, and within a couple of months non-engineers had built 500 to 1,000 apps. HR builds small tools, and the CFO builds dashboards that previously couldn't be made. He adds that his wife needs software she can't build herself, that he has never helped her build it ("my own failing"), and that he expects everyone to get custom software eventually.

1:19:17

His Setup

Mattis used Emacs for 20-plus years, moved to VS Code at a colleague's urging, and ended up with about eight terminal tabs in VS Code running Claude Code. About six weeks before the recording, another colleague pushed him to try the Claude desktop app. It felt awkward at first, and then: "holy crap, this is awesome." He also keeps the Codex desktop app for a second model on critical work. One model writes a design, and the other is asked to adversarially review "what my colleague produced." It isn't perfect, but he finds it worthwhile. He praises Cursor, Factory, and Cognition as well, and says everyone is moving quickly.

He usually uses the best model available and names Fable and Astra. He isn't sure it adds much intelligence, but it saves him deciding case by case, and he would switch only when he needs speed. With the launch close, he tells senior engineers to use the best model. He finds his limit is about five to ten concurrent sessions, and each may run sub-agents: three for some research on the train ride over, sometimes 20, sometimes maybe 100 through features like Anthropic's dynamic workflows. At other times he runs none because he's thinking.

1:23:14

Quality, Testing, and the Future of Code Review

The host noted that quality seems to be declining across the industry and asked how a database company avoids more regressions from more output. Mattis agreed that more lines usually mean more defects. What offsets it, he says, is a firm hand with the agents, and he hopes model providers are listening. Agents "get a little bit lazy on the testing side." You need comprehensive tests and a full range of techniques: property-based testing, metamorphic testing, deterministic simulation testing, and more. Humans are lazy about testing too, himself included; at some point you decide it's enough and ship. He finds it easier to enforce that discipline with agents than with people.

He applies the same thinking to security and performance. Every commit can be reviewed adversarially by one or more security-focused agents. Given recent hacks and leaks, he points out that software has a finite number of bugs, and he expects security and quality to catch up. For him quality includes UX details, and a wrong UX element is now easy to fix, so there's "no excuse." Cockroach Labs' designer skips Figma, works directly in HTML, CSS, and JavaScript, and sometimes opens pull requests to the production UI (not the core database). He says she loves it, and so does everyone else, with no waterfall process.

Mattis was an early member of Google's C++ readability reviewers. He thinks code review was essential before AI. He still looks at most agent-generated code but with less scrutiny, the way you review a senior engineer's PR more lightly than a junior's, and agents are moving toward the senior end. Remaining risks are incomplete tests, missed security practices, and performance regressions. His answer is to add constraints so the wrong thing is hard to do. He suspects, without committing to this year or next, that people will largely stop reading code, as they stopped reading compiler output. Even where someone has to check the assembly, he asks why it should be a human. His example: he wanted a zero-overhead test-time abstraction that compiles out in production, and the model built a check that inspects the decompiled output to confirm only a few extra instructions appear. He would not have built that himself, and now it catches regressions on every change. He thinks models like working inside guardrails like these.

On flow, he says he still gets into the zone, though it is less intense and involves more parallel threads. He starts several experiments that would each have taken a week, reviews progress, and redirects when something looks off. He compares it to being a professor with a swarm of research assistants reporting back in hours, not weeks. Many experiments fail, and "you just got to let go."

1:30:54

The Analogies: Cars, F1, and Sorcerers

Mattis offers several analogies. Coding used to be walking, with some people running efficiently, but everyone moving on their own power. Then a car pulled up. You have to get in without knowing the controls, and you might hit the gas and crash into a tree, but you have to learn to drive. He thinks we are in "the era of the F1 driver," with a large gap between experts who know where the tools break and first-time users. On the idea of the "100x engineer," his sense is that AI stretches the existing spectrum and amplifies prior ability, though he says that isn't exactly true and it helps some people more than others. The host mentioned Boris Cherny and an OpenAI engineer (Tibo) as strong engineers before AI, and Mattis agreed.

Pair programming, with an android at the keyboard, captured how it felt a year ago. His current analogy is domain experts as sorcerers. He cites a ChatGPT session posted by Terence Tao on what he believes was the Jacobian conjecture. He couldn't follow the math, but Tao was clearly talking to the model as a peer and exploring ideas quickly, and it read almost like a foreign language. Knowing the right incantations in the right order produces something real; not knowing them produces "sparkle stuff." Asking a model to "build me a distributed database like CockroachDB" without expertise gets you something "hollow inside." An expert who specifies the storage layer, networking layer, data structures, and runtime concerns can get "something quite magical very, very rapidly."

1:35:50

Advice for Engineers

For mid-level and senior engineers, Mattis says you now have an excellent tutor always available. At Google he learned by reading changes from Jeff Dean (fast, high-performance code) and Sanjay Ghemawat (consistently elegant code), picking things up "via osmosis." Now you can have AI take apart expert code and explain it at any level: a diagram, like you're five, like you're ten, in French. He calls AI, in some sense, a translation tool, and says to keep asking until you understand, then move from learning to contributing by asking why something was built a certain way and what would happen if you changed it.

The host suggested using AI to learn the business domain as well, such as payments at a payments company. Mattis agreed and stressed curiosity: at Google he worked on Gmail but studied how search and Bigtable worked. He stressed personal agency even more. Anyone offering to teach you AI will be out of date, so you have to use the tools constantly yourself. He says he has learned more in the past year than in the previous five combined, and that he got noticeably better as a coder over this one year, as he did each decade before.

He ends with mixed feelings: the moment is "a little bit exhausting right now, but it's very exciting." He got into software to build things, and now he can build faster and drop some of the compromises he used to accept. Visible improvements like better UX and web animations, in his view, are only the surface of changes that go much deeper.