← All writing

Checking 503 Million Keys in a 1 TiB Key-Value Database on S3, Without Storing the Answers

How a Go stress test checks every read of a 1 TiB key-value database on S3-compatible storage without storing the expected answers. Zero wrong answers in 29.5 hours.

A throughput number says how fast. It does not say how right.

IsleDB at 1 TiB: 0 wrong answers, 503 million keys, 1.94 TiB written, 24 MiB/s writes, 465 ms p99 point reads, 29.5-hour run.
The 1 TiB run in six numbers. This article is about the first one.

Throughput is easy to measure. Whether the answers were right is the hard part.

How do we know a database gave the right answer 400 times a second for 29 hours?

A benchmark answers a different question. It writes a lot of data, reads some of it back, and reports bytes per second and a latency percentile. That is what it is for. But it also means that if the database returned yesterday’s value for a key, or dropped a key in the middle of a scan, the throughput graph would look exactly the same.

For IsleDB, a key-value database that keeps all of its data in object storage such as Amazon S3, both questions had to be answered in the same run. The target was a stress test: a 1 TiB dataset under a write load that never stops, with readers running the whole time. It ran against an S3-compatible store with the latency of a real one added to every request. A number like “24 MiB/s” from that run only means something if every read behind it was checked.

So the stress test needed a second system next to the database, one built for correctness and not for speed. It has to know, for any key, at any moment a reader could be looking at, exactly what the answer must be.

This article follows how that correctness checker was built in Go, one problem at a time, and then what it reported at 1 TiB.

What is being tested: IsleDB in a minute

IsleDB is a key-value database written in Go. It is an LSM tree whose files live in an object storage bucket, such as Amazon S3, Google Cloud Storage or Azure Blob Storage, instead of on a local disk. There is no storage cluster and no replica to manage. The bucket is the database.

Three kinds of process share that bucket, and nothing else:

  • One writer takes puts and deletes. It collects whatever arrives for a short interval, 250 ms by default, and saves each group to the bucket as one immutable file. A write is durable once its group is saved.
  • Any number of readers serve point reads and range scans. A reader is not told about new writes. It loads the newest state of the database from the bucket on its own timer, about once a second, and keeps what it reads in a local cache.
  • One maintenance process merges the many small files into fewer large ones, which is compaction, and deletes the files nothing needs any more.
One writer saves groups of writes to an object storage bucket. Any number of readers load the newest state from the bucket about once a second. One maintenance process merges small files into larger ones and deletes old ones.
One writer, any number of readers and one maintenance process, sharing only the bucket.

Two things about this design matter for a test.

A reader is always a little behind the writer, on purpose. And the files under a reader are constantly being rewritten and deleted by another process while the reader may still be using them.

Both are places a wrong answer can come from. A reader can stay on an old state for too long. A compaction can drop a newer value, or bring back a key that was deleted. A file can be removed while a reader still needs it. None of these shows up as an error. The read succeeds and returns the wrong thing.

That is the kind of failure the checker has to catch.

First attempt: remember everything that was written

Let’s start with the obvious design.

Keep a map. Every time the test writes a key, store the value it wrote. Every time it reads a key, compare the answer with the map.

expected := map[string][]byte{}

func put(key string, value []byte) {
	db.Put(key, value)
	expected[key] = value
}

func check(key string) {
	got := db.Get(key)
	if !bytes.Equal(got, expected[key]) {
		fail(key)
	}
}

This works for a unit test. It stops working long before 1 TiB, for two reasons.

The first is size. The run ends with 503 million keys and values that average about 2.5 KB. A map of the values is a second copy of the database. A map of only a version number per key is still half a billion entries, tens of gigabytes of memory once the map overhead is counted, and it has to survive for 29 hours.

The second reason is more serious, and no amount of memory fixes it.

A reader does not see a write the moment it commits. It is up to a second behind. So when a read comes back, the correct answer is not “the latest value written”. It is “the value at the version of the database this reader was looking at”.

The map holds one answer per key. The reader can legitimately return an older one.

The question is not what the key holds now. It is what the key held at the moment the reader was looking.

Second attempt: accept any recent answer

The usual fix is to loosen the check.

Keep the last few versions of every key and accept any of them. A read is correct if it returns the newest value, or the one before it, or the one before that.

Simple enough. But look at what this check can no longer see.

A stale read is one where the reader returns an older version than it should. That is exactly the bug an object-storage database is most likely to have: a cache that was not invalidated, a reader holding on to an old view, a compaction that brought back an overwritten value. And “an older version” is exactly what the loosened check accepts.

A check that allows a range of answers is blind to the one failure it most needs to catch.

So the range has to go. For every read, the checker must name one correct answer. To do that it needs two things:

  1. what was written to every key, in every round of the workload;
  2. which of those writes the reader could see when it answered.

The rest of the design is about getting both without storing either per key.

The workload as a function: a deterministic schedule

The first one can be removed completely.

A test does not have to remember what it wrote if what it writes is never a choice. Suppose the whole workload is a pure function: given a round number and a key, it says whether that round writes the key, and what it writes. Then nothing needs to be stored. Anything the test wants to know about the past, it computes again.

A round, a key index and a seed go into the schedule, which computes whether the round writes the key, what it leaves and which batch carried it. A grid of rounds against keys shows any cell can be computed.
A round, an index and a seed are enough to compute what was written.

In the harness this is the Schedule. Keys are numbered from 0, and the number is called the index. The workload runs in rounds:

  • Round 0 inserts every key.
  • Each later round rewrites a share of the keys that exist, deletes some of those instead, and inserts some new ones.

Whether a round touches a key is a hash of the round and the index:

// Writes reports whether round writes idx: inserts it, updates it or
// deletes it.
func (s *Schedule) Writes(round uint32, idx uint64) bool {
	e := s.existing(round)
	switch {
	case idx >= s.Keys(round):
		return false // not inserted yet
	case round == 0 || idx >= e:
		return true // this round inserts it
	}
	share := s.UpdatePermille
	if s.Hot != nil && s.Hot(idx) {
		share = s.HotPermille
	}
	h := mix64(idx*0xd1b54a32d192ed03 ^ uint64(round)<<40 ^ s.Seed ^ 0x8cb92ba72f3d8dd7)
	return share >= 1000 || h%1000 < share
}

mix64 is the splitmix64 finalizer, a few shifts and multiplies. With UpdatePermille set to 50, about 5% of the keys pass the test in each round, and a different 5% every round, because the round is part of the hash.

Deletes work the same way with a second hash. And the version a round writes is simply the round number.

Now the history of any key can be replayed in a loop:

// Last returns the last round at or before round that writes idx.
func (s *Schedule) Last(round uint32, idx uint64) (uint32, bool) {
	for r := int64(round); r >= 0; r-- {
		if s.Writes(uint32(r), idx) {
			return uint32(r), true
		}
	}
	return 0, false
}

Eleven rounds means at most eleven hashes per key. No map, no lookups, and the answer is the same on every machine and in every process that knows the seed.

A key that can be run backwards: a Feistel permutation

A point read is now easy to reason about. A scan is not.

When a scan of a key range returns ten keys, checking those ten is not enough. The dangerous failure is the eleventh key that should have been there and was not. To catch a missing key, the checker has to list every key that belongs in the range, in order, and compare.

With sequential keys that is trivial, but sequential keys are the easy case for an LSM tree. Every new file lands after the previous one and compaction has little to do. The test needs keys that land at random places across the keyspace, so that every new file overlaps almost everything below it.

Hashing the index gives random placement. But a hash cannot be reversed. Given a key range, there is no way to ask a hash “which indexes land in here?” without trying all 503 million.

What we want is a function that scatters like a hash and can still be run backwards. A function like that, where every input has exactly one output and every output has exactly one input, is a permutation.

Block ciphers have needed exactly this for decades, because whatever they scramble has to be unscrambled again. One of the oldest ways to build one is the Feistel network, the construction behind DES. The harness borrows it, not for secrecy, but because it mixes well and can be undone.

One round

Split the number into two halves, a left half L and a right half R. Then do one small step:

  1. Feed R into a function F. Here F is the same mix64 hash as before, with a per-round key, cut down to the width of a half.
  2. XOR the result into L.
  3. Swap the halves.
new L = R
new R = L xor F(R)
Forward: the right half R is copied to become the new left half, and the left half L is XORed with F of R to become the new right half. Backward: the new left half still holds R, so F of R is computed again and XORed out of the new right half to recover L.
One round forward, and the same round undone.

Why it can be undone

F is a hash. It cannot be reversed, and it does not have to be.

Look at what the round does to R: nothing. R is copied into the output as the new left half. So whoever holds the output still holds R, can compute F(R) a second time, and can XOR it out of the other half. XOR undoes itself, so what remains is the original L.

R = new L
L = new R xor F(new L)

That is the whole trick. The function in the middle can be as messy as we like. The structure around it makes the round reversible anyway.

One round alone is not much of a shuffle, because half of the bits come out unchanged. So the step is repeated, and each time the half that was left alone is the one that gets mixed. The harness uses four rounds with four different keys. A cipher would want more. For scattering keys, four is plenty.

A small example

Take 8 keys. Their indexes need 3 bits, but the two halves must be the same width, so the network works on 4 bits: two halves of 2 bits each, and 16 possible positions.

Here is index 5, which is 0101, going through the four rounds of a network seeded with 42:

Round L R F(R) new L new R
0 01 01 00 01 01
1 01 01 10 01 11
2 01 11 01 11 00
3 11 00 01 00 10

The result is 0010, so index 5 lands at position 2. Running the four rounds in reverse order from 0010 gives 0101 back.

Doing the same for all eight indexes:

index     0   1   2   3   4   5   6   7
position  7  11   3   6  10   2  15  14

key order: 5, 2, 3, 0, 4, 1, 7, 6

The keys were inserted as 0, 1, 2 and so on, and they ended up in an order with no pattern to it. Eight of the sixteen positions hold a key. The other eight are empty, and the checker skips them.

The same thing happens at full size. The 1 TiB run has about 525 million keys once every insert is counted. That needs 29 bits, rounded up to 30 to keep the halves equal, which gives about a billion positions with roughly half of them used.

The code

In Go the two directions are a few lines each:

func (f feistel) round(i int, x uint64) uint64 {
	return mix64(x^f.keys[i]) & f.halfMask
}

func (f feistel) encrypt(x uint64) uint64 {
	l, r := x>>f.halfBits, x&f.halfMask
	for i := range 4 {
		l, r = r, l^f.round(i, r)
	}
	return l<<f.halfBits | r
}

func (f feistel) decrypt(y uint64) uint64 {
	l, r := y>>f.halfBits, y&f.halfMask
	for i := 3; i >= 0; i-- {
		l, r = r^f.round(i, l), l
	}
	return l<<f.halfBits | r
}

encrypt turns an index into a position. decrypt runs the rounds in the opposite order and turns a position back into its index.

From a position to a key

A key is 16 bytes: the position in the first 8, then the index itself. The position decides where the key sorts. The index is carried along so the checker can read it straight off any key a scan returns, and confirm that the first 8 bytes really are that index’s position. A key that fails this was never written by the test.

Eight indexes in insert order mapped by a permutation to scattered positions in key order. Three positions are highlighted as a scan range, and the indexes that belong in it are listed in order.
The permutation scatters the keys, and can still say what belongs in a range. Drawn without the empty positions.

Inserting in index order now writes to random places in the keyspace, as hashing would. But to list the keys in a range, the checker walks the positions in that range in order and decrypts each one back to its index:

for p := start; p < end; p++ {
	idx := s.f.decrypt(p)
	if idx >= s.n {
		continue // no key at this position
	}
	yield(idx)
}

So a scan page is checked in both directions. Every key it returned must be right, and every key the walk produces must be on the page, in the same order.

A hash can tell us where a key goes. Only a permutation can tell us what belongs in a range.

A value that describes itself

One more piece removes a whole class of confusion.

Every value begins with a 20-byte header: the index of the key it belongs to, the version, its total length, and a CRC-32C of the bytes that follow. The rest is incompressible bytes generated from the seed, the index and the version.

+---------+---------+--------+--------+-------------------------+
| index   | version | length | CRC32C | seeded random bytes     |
| 8 bytes | 4 bytes | 4      | 4      | 100 B to 16 KiB         |
+---------+---------+--------+--------+-------------------------+

Even the length is a function of the index and the version, so the checker knows how long a value must be before it sees it.

This means a value can be validated on its own, before any question of versions. If the header’s index is not the key’s index, the database returned another key’s value. If the length or checksum is wrong, the value is damaged. And when the value passes, the header says which version the reader returned, so the comparison with the expected version is one integer against another.

The one thing that cannot be computed: when a write committed

So far nothing has been stored. The schedule knows what every round writes to every key.

But the second question is still open: which of those writes could the reader see?

That depends on when each write committed, and when is not something the test decides. The database does. The writer groups whatever arrives and saves it to object storage together, and only the writer knows which group a write ended up in.

IsleDB exposes this as a revision, a number that only grows. Every save gives the database a new one.

  • The writer answers each write with the revision it committed at.
  • Every read answers with the revision it was served from.
  • A read at a revision at or past a write’s revision includes that write.

This is the one fact the harness has to record. It keeps a ledger: for every batch it sends, the revision the writer answered.

batch 0        -> revision 3
batch 1        -> revision 3
batch 2        -> revision 4
...

One 64-bit number per batch. A batch is 16 writes, so the 1 TiB run sent roughly 55 million of them, and the whole ledger fits in under half a gigabyte of memory.

That is the entire stored state of the checker. Not what the keys hold. Only when each batch became visible.

Compute everything the test controls. Record only what the database decides.

What should a read see at revision R?

Both halves are now in place, and they meet in one small function.

A read comes back for key idx, served at revision rev. Walk the rounds from the newest back to the first. Skip the rounds that did not write this key. For the first round that did, ask the schedule which batch carried it, and ask the ledger when that batch committed. If it committed at or below rev, that round’s write is what the reader must have seen.

for r := int64(top); r >= 0; r-- {
	round := uint32(r)
	if !s.Writes(round, idx) {
		continue // the round left it as the one before left it
	}
	e := m.Ledger.Get(s.BatchOf(round, idx))
	if e.Revision != 0 && e.Revision <= rev {
		return s.After(round, idx) // present at this version, or deleted
	}
}
return absent
A revision timeline for one key written by rounds 0, 3 and 7, committed at revisions 120, 480 and 910. A read answered at revision 700 must see version 3. Reads above the settled revision of 800 wait.
One key, three writes, and the single state a read at revision 700 may return.

Two computed answers and one array lookup per round. The result is a single state: the key is present at one specific version, or it is absent.

There is one rule in the load that makes this sound. A round only starts once every batch of the round before it has committed. So two writes of the same key are never in flight together, and “the newest round whose batch committed at or below rev” always has one answer.

A read can arrive before its answer is known

There is a race hiding in that function.

Suppose a batch has been sent and the writer has saved it at revision 900, but the response has not reached the harness yet. A reader refreshes, sees revision 900, and answers a read from it. The harness looks in the ledger, finds no revision for that batch, and concludes the key should still hold its old value.

The database is right and the checker is wrong.

The fix is to know how far the ledger can be trusted. When a batch is about to be sent, the ledger notes the highest revision seen so far. That batch can only commit above it. The lowest such mark among the batches still in flight is the settled revision: everything at or below it is fully recorded.

// Settled returns the highest revision at which every batch visible is in
// the ledger: no attempt in flight can commit at or below it.
func (l *Ledger) Settled() uint64 {
	l.flightMu.Lock()
	defer l.flightMu.Unlock()
	if floor, ok := l.flight[l.oldest]; ok {
		return floor
	}
	return math.MaxUint64
}

A read answered above the settled revision is not checked yet. It waits in a queue until the ledger catches up, and then it is checked like any other.

Nothing is skipped. And a read still waiting when the run ends is not forgiven. It is reported as a failure of its own kind.

The uncomfortable case: nobody knows if the write happened

Networks lose responses. A request can reach the writer and be saved, and the answer can still be lost on the way back. The checker has to live with that from the client’s side.

A batch is sent. The connection drops before the answer arrives. Did it commit?

There are two situations.

If the writer had already given the request a write ID, the harness asks about that ID until the writer settles it one way or the other. It keeps asking through writer restarts, because giving up early would let a late commit land on top of the next round’s write of the same keys.

If the connection was lost before any ID came back, there is nothing to ask about. The harness sends the batch again, and marks it in the ledger: an earlier attempt may have committed at a revision nobody saw.

For such a batch, and only for such a batch, a read below its recorded revision has two allowed states: the one before the write and the one after it. The next round also waits a full minute, so that the lost attempt has no chance left to commit late.

This is the only place where the checker accepts more than one answer. It is not a tolerance that was chosen for convenience. It is the exact set of states the client cannot tell apart, and it applies to the keys of that one batch.

Eight ways to be wrong

With one exact answer per read, a mismatch can be named precisely.

Failure Meaning
missing A key that must be there was not returned
stale An older version than the newest at that revision
future A version not yet written at that revision
resurrected A key deleted at that revision came back
corrupt A value that fails its own header or checksum
unexpected A key that no index produces
order Scan results out of order or repeated
unsettled A read the ledger never settled by the end

Each failure is written as one line with the key, the revision, what was seen, what was allowed, and every batch that ever wrote that key with its revision. That is enough to start debugging without running anything again.

A run with a single failure exits non-zero.

Test the database from the outside: a black-box harness

Everything so far could have been written as a Go test inside the IsleDB repository, calling the library directly. It was written the other way on purpose.

The harness imports nothing from IsleDB. It starts the real isledb writer, isledb reader and isledb maintenance binaries, and talks to them over their HTTP APIs, the way an application would.

This buys three things.

Any version can be tested. The harness builds the database from a release tag, a branch or a commit in a temporary worktree and runs the same workload against it. Two versions can be compared on equal terms, and a version from before a change can be run again to see if a problem was already there.

The database cannot grade itself. Between each process and the object store sits a small proxy. It adds 15 to 40 ms of latency to every request, so a request costs roughly what it would against a real object store, and it counts every byte uploaded. Write amplification is computed from what storage saw, not from the database’s own counters.

Processes can be hurt. Because the roles are separate processes behind proxies, a spec can kill the writer in the middle of a load, restart maintenance at a different version, or tell a proxy to forward a request and lose the answer.

A slow read must not hide: avoiding coordinated omission

One more detail decides whether the latency numbers can be trusted.

A simple load generator runs a loop: send a read, wait for the answer, send the next. If the database stalls for two seconds, the loop sends nothing for two seconds. It records one slow read, and all the reads that would have arrived during the stall are never sent, so they never show up in the percentiles. This is called coordinated omission, and it makes a stalling system look fast. The p99 article explains why the tail is where this matters.

The harness paces reads open loop. Every read has a time it is due, whether or not a worker is free. Response time is counted from the due time, so time spent waiting in line is part of the number. A read that is more than five seconds overdue is dropped and counted, so the report shows reads offered against reads achieved.

Running the stress test at 1 TiB

With the checker in place, the benchmark itself is short to describe.

  1. Load, 12.3 hours. Insert 1 TiB at a steady 24 MiB/s.
  2. Settle and verify. Let compaction finish, then read back every key.
  3. Update, 11.7 hours. Ten rounds. Each one rewrites 5% of the keys, and 30% of the keys in one hot tenth of the keyspace. A tenth of what it writes are deletes, and each round adds 2% new keys.
  4. Settle and verify again, this time over all 503 million keys.

While writes were running, readers sent 300 reads a second across the whole keyspace, one in ten of them a scan of 1 to 100 keys, and another 100 a second for recently written keys.

There was one writer, one reader and one maintenance process, on IsleDB v0.22.0, against an S3-compatible server behind the latency proxy.

Data written ~1.94 TiB (1 TiB load plus 10 update rounds)
Keys after the load 437,860,913
Keys at the end 503,227,810
Wrong answers 0
Lost, refused or unresolved writes 0
Full-keyspace verification scans 2, both passed
Write rate 24 MiB/s, never throttled
Reads during load and updates 400/s, none dropped
Point read p99, end to end 465 ms
Commit p50 / p99 314 ms / 688 ms
Space amplification 1.19×
Write amplification 13.1×
Total run time 29.5 hours

Every read was checked

Reads checked per second across the 29.5-hour run: a steady 400 while writes run, lower during the two verification scans.
Reads checked per second: a steady 400 while writes run, lower during the verification scans.

None of the eight failure kinds appeared. No stale value, no deleted key that came back, no key missing from a scan.

The two verification phases are the stronger statement. Each one waits until the reader has caught up with the newest revision written, then scans the entire keyspace in 32 parallel parts and checks every page in both directions. The second one covered all 503 million keys.

Writes stayed flat

Bytes written per second across the run, flat at 24 MiB/s through the load and the update rounds.
Bytes written per second, flat at 24 MiB/s.

Writes held 24 MiB/s from the first minute to the last, and the writer never had to push back on clients.

Commit latency was 314 ms at p50. That needs context. The writer does not save each batch on its own. It groups everything that arrives and saves the group every 250 ms, so a batch waits up to 250 ms for the next flush and then about 100 ms for the save. This does not limit throughput, because the writer keeps accepting batches while a group is being saved. That is how 256 clients held 24 MiB/s while each one waited a third of a second per batch.

Reads did not slow down as the data grew

Read response time per minute from the median to p99.9 across the run, about as fast at 503 million keys as near the start.
Read response time per minute, from the median up to p99.9.
Read p99
Point read, anywhere in the keyspace 465 ms
Point read, recently written key 447 ms
Scan of 1 to 100 keys 1.5 s

These are response times, counted from when each read was due. A read that misses the cache goes to object storage at 15 to 40 ms a request, and a scan usually touches several files, which is where most of the time goes.

What it cost in rewrites

Write amplification across the run, climbing as the tree gets deeper and then flattening near 13.
Write amplification, climbing as the tree gets deeper, then flat.

Write amplification ended at 13.1×: bytes uploaded to object storage for each byte the application wrote. About 2× of that comes from the writer and the rest from compaction. Random keys are the worst case here, and an ordered workload would come in lower.

The run made 93.2 million requests to object storage. At S3 request prices that is about $46 for all 29.5 hours, before the cost of storing the data.

The full results have the remaining graphs, the compaction behaviour and the settings that were changed from their defaults.

What this benchmark does not show

Two things about this run decide how the numbers should be read.

  • It was a clean run. No process was killed and no fault was injected. The harness can do both, but the 1 TiB numbers above are from a run where everything stayed up, with one reader and no shared cache in front of it.
  • It was not AWS S3 itself. The store was an S3-compatible server with latency added. The request count is real. The latency and the price are modeled.

Closing

The checker looks complicated when listed feature by feature. Its shape is small:

round, index
  -> does this round write the key?        computed
  -> what does it write?                   computed
  -> which batch carried it?               computed
  -> when did that batch commit?           recorded, one number per batch
  -> what must a read at revision R see?   exactly one state

Everything the test controls is a function, so it never has to be remembered. The single thing the database decides, the revision of each commit, is the single thing written down.

Compute what the test controls. Record what the database decides. Then every read has exactly one right answer.

Once that is in place, a throughput number stops being a claim about speed alone. It becomes a claim about speed while being right, and that is the claim this run was built to make.

Want to run it?

The harness lives in tools/stress in the IsleDB repository. A local smoke run takes about a minute:

cd tools/stress
go run . run -spec specs/local-smoke.yaml

The 1 TiB run used the mixed profile:

go run . run -spec specs/mixed.yaml -target 1TiB -isledb v0.22.0 -fetch

Start at 100 GiB before trying 1 TiB.

References