Permalink
Newer
Older
100644 1293 lines (1072 sloc) 62 KB
1
# About
2
This document is an updated version of the original design documents
3
by Spencer Kimball from early 2014.
4
5
# Overview
6
7
Cockroach is a distributed key:value datastore (SQL and structured
8
data layers of cockroach have yet to be defined) which supports **ACID
9
transactional semantics** and **versioned values** as first-class
10
features. The primary design goal is **global consistency and
11
survivability**, hence the name. Cockroach aims to tolerate disk,
12
machine, rack, and even **datacenter failures** with minimal latency
13
disruption and **no manual intervention**. Cockroach nodes are
14
symmetric; a design goal is **homogenous deployment** (one binary) with
15
minimal configuration.
16
17
Cockroach implements a **single, monolithic sorted map** from key to
18
value where both keys and values are byte strings (not unicode).
19
Cockroach **scales linearly** (theoretically up to 4 exabytes (4E) of
20
logical data). The map is composed of one or more ranges and each range
21
is backed by data stored in [RocksDB](http://rocksdb.org/) (a
22
variant of LevelDB), and is replicated to a total of three or more
23
cockroach servers. Ranges are defined by start and end keys. Ranges are
24
merged and split to maintain total byte size within a globally
25
configurable min/max size interval. Range sizes default to target `64M` in
26
order to facilitate quick splits and merges and to distribute load at
27
hotspots within a key range. Range replicas are intended to be located
28
in disparate datacenters for survivability (e.g. `{ US-East, US-West,
29
Japan }`, `{ Ireland, US-East, US-West}`, `{ Ireland, US-East, US-West,
30
Japan, Australia }`).
31
32
Single mutations to ranges are mediated via an instance of a distributed
33
consensus algorithm to ensure consistency. We’ve chosen to use the
34
[Raft consensus
35
algorithm](https://ramcloud.stanford.edu/wiki/download/attachments/11370504/raft.pdf).
36
All consensus state is stored in RocksDB.
37
38
A single logical mutation may affect multiple key/value pairs. Logical
39
mutations have ACID transactional semantics. If all keys affected by a
40
logical mutation fall within the same range, atomicity and consistency
41
are guaranteed by Raft; this is the **fast commit path**. Otherwise, a
42
**non-locking distributed commit** protocol is employed between affected
43
ranges.
44
45
Cockroach provides [snapshot isolation](http://en.wikipedia.org/wiki/Snapshot_isolation) (SI) and
46
serializable snapshot isolation (SSI) semantics, allowing **externally
47
consistent, lock-free reads and writes**--both from a historical
48
snapshot timestamp and from the current wall clock time. SI provides
49
lock-free reads and writes but still allows write skew. SSI eliminates
50
write skew, but introduces a performance hit in the case of a
51
contentious system. SSI is the default isolation; clients must
52
consciously decide to trade correctness for performance. Cockroach
53
implements [a limited form of linearizability](#linearizability),
54
providing ordering for any observer or chain of observers.
55
56
Similar to
57
[Spanner](http://static.googleusercontent.com/media/research.google.com/en/us/archive/spanner-osdi2012.pdf)
58
directories, Cockroach allows configuration of arbitrary zones of data.
59
This allows replication factor, storage device type, and/or datacenter
60
location to be chosen to optimize performance and/or availability.
61
Unlike Spanner, zones are monolithic and don’t allow movement of fine
62
grained data on the level of entity groups.
63
64
A
65
[Megastore](http://www.cidrdb.org/cidr2011/Papers/CIDR11_Paper32.pdf)-like
66
message queue mechanism is also provided to 1) efficiently sideline
67
updates which can tolerate asynchronous execution and 2) provide an
68
integrated message queuing system for asynchronous communication between
69
distributed system components.
70
71
# Architecture
72
73
Cockroach implements a layered architecture. The highest level of
74
abstraction is the SQL layer (currently unspecified in this document).
75
It depends directly on the [*structured data
76
API*](#structured-data-api), which provides familiar relational concepts
77
such as schemas, tables, columns, and indexes. The structured data API
78
in turn depends on the [distributed key value store](#key-value-api),
79
which handles the details of range addressing to provide the abstraction
80
of a single, monolithic key value store. The distributed KV store
81
communicates with any number of physical cockroach nodes. Each node
82
contains one or more stores, one per physical device.
83
84
![Architecture](media/architecture.png)
85
86
Each store contains potentially many ranges, the lowest-level unit of
87
key-value data. Ranges are replicated using the Raft consensus protocol.
88
The diagram below is a blown up version of stores from four of the five
89
nodes in the previous diagram. Each range is replicated three ways using
90
raft. The color coding shows associated range replicas.
91
92
![Ranges](media/ranges.png)
93
94
Each physical node exports a RoachNode service. Each RoachNode exports
95
one or more key ranges. RoachNodes are symmetric. Each has the same
96
binary and assumes identical roles.
97
98
Nodes and the ranges they provide access to can be arranged with various
99
physical network topologies to make trade offs between reliability and
100
performance. For example, a triplicated (3-way replica) range could have
101
each replica located on different:
102
103
- disks within a server to tolerate disk failures.
104
- servers within a rack to tolerate server failures.
105
- servers on different racks within a datacenter to tolerate rack power/network failures.
106
- servers in different datacenters to tolerate large scale network or power outages.
107
108
Up to `F` failures can be tolerated, where the total number of replicas `N = 2F + 1` (e.g. with 3x replication, one failure can be tolerated; with 5x replication, two failures, and so on).
109
110
# Cockroach Client
111
112
In order to support diverse client usage, Cockroach clients connect to
113
any node via HTTPS using protocol buffers or JSON. The connected node
114
proxies involved client work including key lookups and write buffering.
115
116
# Keys
117
118
Cockroach keys are arbitrary byte arrays. If textual data is used in
119
keys, utf8 encoding is recommended (this helps for cleaner display of
120
values in debugging tools). User-supplied keys are encoded using an
121
ordered code. System keys are either prefixed with null characters (`\0`
122
or `\0\0`) for system tables, or take the form of
123
`<user-key><system-suffix>` to sort user-key-range specific system
124
keys immediately after the user keys they refer to. Null characters are
125
used in system key prefixes to guarantee that they sort first.
126
127
# Versioned Values
128
129
Cockroach maintains historical versions of values by storing them with
130
associated commit timestamps. Reads and scans can specify a snapshot
131
time to return the most recent writes prior to the snapshot timestamp.
132
Older versions of values are garbage collected by the system during
133
compaction according to a user-specified expiration interval. In order
134
to support long-running scans (e.g. for MapReduce), all versions have a
135
minimum expiration.
136
137
Versioned values are supported via modifications to RocksDB to record
138
commit timestamps and GC expirations per key.
139
May 29, 2015
140
Each range maintains a small (i.e. latest 10s of read timestamps),
141
*in-memory* cache from key to the latest timestamp at which the
142
key was read. This *read timestamp cache* is updated everytime a key
143
is read. The cache’s entries are evicted oldest timestamp first, updating
May 29, 2015
144
the low water mark of the cache appropriately. If a new range replica leader
145
is elected, it sets the low water mark for the cache to the current
Jun 1, 2015
146
wall time + ε (ε = 99th percentile clock skew).
148
# Lock-Free Distributed Transactions
149
150
Cockroach provides distributed transactions without locks. Cockroach
151
transactions support two isolation levels:
152
153
- snapshot isolation (SI) and
154
- *serializable* snapshot isolation (SSI).
155
156
*SI* is simple to implement, highly performant, and correct for all but a
157
handful of anomalous conditions (e.g. write skew). *SSI* requires just a touch
158
more complexity, is still highly performant (less so with contention), and has
159
no anomalous conditions. Cockroach’s SSI implementation is based on ideas from
160
the literature and some possibly novel insights.
161
162
SSI is the default level, with SI provided for application developers
163
who are certain enough of their need for performance and the absence of
164
write skew conditions to consciously elect to use it. In a lightly
165
contended system, our implementation of SSI is just as performant as SI,
166
requiring no locking or additional writes. With contention, our
167
implementation of SSI still requires no locking, but will end up
168
aborting more transactions. Cockroach’s SI and SSI implementations
169
prevent starvation scenarios even for arbitrarily long transactions.
170
171
See the [Cahill paper](https://drive.google.com/file/d/0B9GCVTp_FHJIcEVyZVdDWEpYYXVVbFVDWElrYUV0NHFhU2Fv/edit?usp=sharing)
172
for one possible implementation of SSI. This is another [great paper](http://cs.yale.edu/homes/thomson/publications/calvin-sigmod12.pdf).
173
For a discussion of SSI implemented by preventing read-write conflicts
174
(in contrast to detecting them, called write-snapshot isolation), see
175
the [Yabandeh paper](https://drive.google.com/file/d/0B9GCVTp_FHJIMjJ2U2t6aGpHLTFUVHFnMTRUbnBwc2pLa1RN/edit?usp=sharing),
176
which is the source of much inspiration for Cockroach’s SSI.
177
178
Each Cockroach transaction is assigned a random priority and a
179
"candidate timestamp" at start. The candidate timestamp is the
180
provisional timestamp at which the transaction will commit, and is
181
chosen as the current clock time of the node coordinating the
182
transaction. This means that a transaction without conflicts will
183
usually commit with a timestamp that, in absolute time, precedes the
184
actual work done by that transaction.
185
May 22, 2015
186
In the course of coordinating a transaction between one or more
187
distributed nodes, the candidate timestamp may be increased, but will
188
never be decreased. The core difference between the two isolation levels
189
SI and SSI is that the former allows the transaction's candidate
190
timestamp to increase and the latter does not.
192
**Hybrid Logical Clock**
193
194
Each cockroach node maintains a hybrid logical clock (HLC) as discussed
195
in the [Hybrid Logical Clock paper](http://www.cse.buffalo.edu/tech-reports/2014-04.pdf).
196
HLC time uses timestamps which are composed of a physical component (thought of
197
as and always close to local wall time) and a logical component (used to
198
distinguish between events with the same physical component). It allows us to
199
track causality for related events similar to vector clocks, but with less
200
overhead. In practice, it works much like other logical clocks: When events
201
are received by a node, it informs the local HLC about the timestamp supplied
202
with the event by the sender, and when events are sent a timestamp generated by
203
the local HLC is attached.
204
205
For a more in depth description of HLC please read the paper. Our
206
implementation is [here](https://github.com/cockroachdb/cockroach/blob/master/util/hlc/hlc.go).
207
208
Cockroach picks a Timestamp for a transaction using HLC time. Throughout this
209
document, *timestamp* always refers to the HLC time which is a singleton
210
on each node. The HLC is updated by every read/write event on the node, and
211
the HLC time >= walltime. A read/write timestamp received in a cockroach request
212
from another node is not only used to version the operation, but also updates
213
the HLC on the node. This is useful in guaranteeing that all data read/written
214
on a node is at a timestamp < next HLC time.
216
Transactions are executed in two phases:
217
218
1. Start the transaction by writing a new entry to the system
219
transaction table (keys prefixed by *\0tx*) with state “PENDING”. In
220
parallel write an "intent" value for each datum being written as part
221
of the transaction. These are normal MVCC values, with the addition of
222
a special flag (i.e. “intent”) indicating that the value may be
223
committed after the transaction itself commits. In addition,
224
the transaction id (unique and chosen at tx start time by client)
225
is stored with intent values. The tx id is used to refer to the
226
transaction table when there are conflicts and to make
227
tie-breaking decisions on ordering between identical timestamps.
228
Each node returns the timestamp used for the write (which is the
229
original candidate timestamp in the absence of read/write conflicts);
230
the client selects the maximum from amongst all write timestamps as the
231
final commit timestamp.
233
2. Commit the transaction by updating its entry in the system
234
transaction table (keys prefixed by *\0tx*). The value of the
235
commit entry contains the candidate timestamp (increased as
236
necessary to accommodate any latest read timestamps). Note that
237
the transaction is considered fully committed at this point and
238
control may be returned to the client.
239
240
In the case of an SI transaction, a commit timestamp which was
241
increased to accommodate concurrent readers is perfectly
242
acceptable and the commit may continue. For SSI transactions,
243
however, a gap between candidate and commit timestamps
244
necessitates transaction restart (note: restart is different than
245
abort--see below).
246
247
After the transaction is committed, all written intents are upgraded
248
in parallel by removing the “intent” flag. The transaction is
249
considered fully committed before this step and does not wait for
250
it to return control to the transaction coordinator.
251
252
In the absence of conflicts, this is the end. Nothing else is necessary
253
to ensure the correctness of the system.
254
255
**Conflict Resolution**
256
257
Things get more interesting when a reader or writer encounters an intent
258
record or newly-committed value in a location that it needs to read or
259
write. This is a conflict, usually causing either of the transactions to
260
abort or restart depending on the type of conflict.
261
262
***Transaction restart:***
263
264
This is the usual (and more efficient) type of behaviour and is used
265
except when the transaction was aborted (for instance by another
266
transaction).
267
In effect, that reduces to two cases; the first being the one outlined
268
above: An SSI transaction that finds upon attempting to commit that
269
its commit timestamp has been pushed. The second case involves a transaction
270
actively encountering a conflict, that is, one of its readers or writers
271
encounter data that necessitate conflict resolution
272
(see transaction interactions below).
273
274
When a transaction restarts, it changes its priority and/or moves its
275
timestamp forward depending on data tied to the conflict, and
276
begins anew reusing the same tx id. The prior run of the transaction might
277
have written some write intents, which need to be deleted before the
278
transaction commits, so as to not be included as part of the transaction.
279
These stale write intent deletions are done during the reexecution of the
280
transaction, either implicitly, through writing new intents to
281
the same keys as part of the reexecution of the transaction, or explicitly,
282
by cleaning up stale intents that are not part of the reexecution of the
283
transaction. Since most transactions will end up writing to the same keys,
284
the explicit cleanup run just before committing the transaction is usually
285
a NOOP.
286
287
***Transaction abort:***
288
289
This is the case in which a transaction, upon reading its transaction
290
table entry, finds that it has been aborted. In this case, the
291
transaction can not reuse its intents; it returns control to the client
292
before cleaning them up (other readers and writers would clean up
293
dangling intents as they encounter them) but will make an effort to
294
clean up after itself. The next attempt (if applicable) then runs as a
295
new transaction with **a new tx id**.
296
297
***Transaction interactions:***
298
299
There are several scenarios in which transactions interact:
300
301
- **Reader encounters write intent or value with newer timestamp far
302
enough in the future**: This is not a conflict. The reader is free
303
to proceed; after all, it will be reading an older version of the
304
value and so does not conflict. Recall that the write intent may
305
be committed with a later timestamp than its candidate; it will
306
never commit with an earlier one. **Side note**: if a SI transaction
307
reader finds an intent with a newer timestamp which the reader’s own
308
transaction has written, the reader always returns that intent's value.
309
310
- **Reader encounters write intent or value with newer timestamp in the
311
near future:** In this case, we have to be careful. The newer
312
intent may, in absolute terms, have happened in our read's past if
313
the clock of the writer is ahead of the node serving the values.
314
In that case, we would need to take this value into account, but
315
we just don't know. Hence the transaction restarts, using instead
316
a future timestamp (but remembering a maximum timestamp used to
317
limit the uncertainty window to the maximum clock skew). In fact,
318
this is optimized further; see the details under "choosing a time
319
stamp" below.
320
321
- **Reader encounters write intent with older timestamp**: the reader
322
must follow the intent’s transaction id to the transaction table.
323
If the transaction has already been committed, then the reader can
324
just read the value. If the write transaction has not yet been
325
committed, then the reader has two options. If the write conflict
326
is from an SI transaction, the reader can *push that transaction's
327
commit timestamp into the future* (and consequently not have to
328
read it). This is simple to do: the reader just updates the
329
transaction’s commit timestamp to indicate that when/if the
330
transaction does commit, it should use a timestamp *at least* as
331
high. However, if the write conflict is from an SSI transaction,
332
the reader must compare priorities. If the reader has the higher priority,
333
it pushes the transaction’s commit timestamp (that
334
transaction will then notice its timestamp has been pushed, and
335
restart). If it has the lower or same priority, it retries itself using as
336
a new priority `max(new random priority, conflicting txn’s
337
priority - 1)`.
339
- **Writer encounters uncommitted write intent**:
340
If the other write intent has been written by a transaction with a lower
341
priority, the writer aborts the conflicting transaction. If the write
342
intent has a higher or equal priority the transaction retries, using as a new
343
priority *max(new random priority, conflicting txn’s priority - 1)*;
344
the retry occurs after a short, randomized backoff interval.
346
- **Writer encounters newer committed value**:
347
The committed value could also be an unresolved write intent made by a
348
transaction that has already committed. The transaction restarts. On restart,
349
the same priority is reused, but the candidate timestamp is moved forward
350
to the encountered value's timestamp.
352
- **Writer encounters more recently read key**:
353
The *read timestamp cache* is consulted on each write at a node. If the write’s
354
candidate timestamp is earlier than the low water mark on the cache itself
355
(i.e. its last evicted timestamp) or if the key being written has a read
356
timestamp later than the write’s candidate timestamp, this later timestamp
357
value is returned with the write. A new timestamp forces a transaction
358
restart only if it is serializable.
360
**Transaction management**
361
362
Transactions are managed by the client proxy (or gateway in SQL Azure
363
parlance). Unlike in Spanner, writes are not buffered but are sent
364
directly to all implicated ranges. This allows the transaction to abort
365
quickly if it encounters a write conflict. The client proxy keeps track
366
of all written keys in order to resolve write intents asynchronously upon
367
transaction completion. If a transaction commits successfully, all intents
368
are upgraded to committed. In the event a transaction is aborted, all written
369
intents are deleted. The client proxy doesn’t guarantee it will resolve intents.
370
371
In the event the client proxy restarts before the pending transaction is
372
committed, the dangling transaction would continue to live in the
373
transaction table until aborted by another transaction. Transactions
374
heartbeat the transaction table every five seconds by default.
375
Transactions encountered by readers or writers with dangling intents
376
which haven’t been heartbeat within the required interval are aborted.
377
In the event the proxy restarts after a transaction commits but before
378
the asynchronous resolution is complete, the dangling intents are upgraded
379
when encountered by future readers and writers and the system does
380
not depend on their timely resolution for correctness.
381
382
An exploration of retries with contention and abort times with abandoned
383
transaction is
384
[here](https://docs.google.com/document/d/1kBCu4sdGAnvLqpT-_2vaTbomNmX3_saayWEGYu1j7mQ/edit?usp=sharing).
385
386
**Transaction Table**
387
388
Please see [proto/data.proto](https://github.com/cockroachdb/cockroach/blob/master/proto/data.proto) for the up-to-date structures, the best entry point being `message Transaction`.
389
390
**Pros**
391
392
- No requirement for reliable code execution to prevent stalled 2PC
393
protocol.
394
- Readers never block with SI semantics; with SSI semantics, they may
395
abort.
396
- Lower latency than traditional 2PC commit protocol (w/o contention)
397
because second phase requires only a single write to the
398
transaction table instead of a synchronous round to all
399
transaction participants.
400
- Priorities avoid starvation for arbitrarily long transactions and
401
always pick a winner from between contending transactions (no
402
mutual aborts).
403
- Writes not buffered at client; writes fail fast.
404
- No read-locking overhead required for *serializable* SI (in contrast
405
to other SSI implementations).
406
- Well-chosen (i.e. less random) priorities can flexibly give
407
probabilistic guarantees on latency for arbitrary transactions
408
(for example: make OLTP transactions 10x less likely to abort than
409
low priority transactions, such as asynchronously scheduled jobs).
410
411
**Cons**
412
413
- Reads from non-leader replicas still require a ping to the leader to
414
update *read timestamp cache*.
415
- Abandoned transactions may block contending writers for up to the
416
heartbeat interval, though average wait is likely to be
417
considerably shorter (see [graph in link](https://docs.google.com/document/d/1kBCu4sdGAnvLqpT-_2vaTbomNmX3_saayWEGYu1j7mQ/edit?usp=sharing)).
418
This is likely considerably more performant than detecting and
419
restarting 2PC in order to release read and write locks.
420
- Behavior different than other SI implementations: no first writer
421
wins, and shorter transactions do not always finish quickly.
422
Element of surprise for OLTP systems may be a problematic factor.
423
- Aborts can decrease throughput in a contended system compared with
424
two phase locking. Aborts and retries increase read and write
425
traffic, increase latency and decrease throughput.
426
427
**Choosing a Timestamp**
428
429
A key challenge of reading data in a distributed system with clock skew
430
is choosing a timestamp guaranteed to be greater than the latest
431
timestamp of any committed transaction (in absolute time). No system can
432
claim consistency and fail to read already-committed data.
433
434
Accomplishing consistency for transactions (or just single operations)
435
accessing a single node is easy. The timestamp is assigned by the node
436
itself, so it is guaranteed to be at a greater timestamp than all the
437
existing timestamped data on the node.
438
439
For multiple nodes, the timestamp of the node coordinating the
440
transaction `t` is used. In addition, a maximum timestamp `t+ε` is
441
supplied to provide an upper bound on timestamps for already-committed
442
data (`ε` is the maximum clock skew). As the transaction progresses, any
443
data read which have timestamps greater than `t` but less than `t+ε`
444
cause the transaction to abort and retry with the conflicting timestamp
445
t<sub>c</sub>, where t<sub>c</sub> \> t. The maximum timestamp `t+ε` remains
446
the same. This implies that transaction restarts due to clock uncertainty
447
can only happen on a time interval of length `ε`.
449
We apply another optimization to reduce the restarts caused
450
by uncertainty. Upon restarting, the transaction not only takes
451
into account t<sub>c<sub>, but the timestamp of the node at the time
452
of the uncertain read t<sub>node<sub>. The larger of those two timestamps
453
t<sub>c<sub> and t<sub>node<sub> (likely equal to the latter) is used
454
to increase the read timestamp. Additionally, the conflicting node is
455
marked as “certain”. Then, for future reads to that node within the
456
transaction, we set `MaxTimestamp = Read Timestamp`, preventing further
457
uncertainty restarts.
458
459
Correctness follows from the fact that we know that at the time of the read,
460
there exists no version of any key on that node with a higher timestamp than
461
t<sub>node<sub>. Upon a restart caused by the node, if the transaction
462
encounters a key with a higher timestamp, it knows that in absolute time,
463
the value was written after t<sub>node</sub> was obtained, i.e. after the
464
uncertain read. Hence the transaction can move forward reading an older version
465
of the data (at the transaction's timestamp). This limits the time uncertainty
466
restarts attributed to a node to at most one. The tradeoff is that we might
467
pick a timestamp larger than the optimal one (> highest conflicting timestamp),
468
resulting in the possibility of a few more conflicts.
469
470
We expect retries will be rare, but this assumption may need to be
471
revisited if retries become problematic. Note that this problem does not
472
apply to historical reads. An alternate approach which does not require
473
retries makes a round to all node participants in advance and
474
chooses the highest reported node wall time as the timestamp. However,
475
knowing which nodes will be accessed in advance is difficult and
476
potentially limiting. Cockroach could also potentially use a global
477
clock (Google did this with [Percolator](https://www.usenix.org/legacy/event/osdi10/tech/full_papers/Peng.pdf)),
478
which would be feasible for smaller, geographically-proximate clusters.
479
480
# Linearizability
481
482
First a word about [***Spanner***](http://research.google.com/archive/spanner.html).
483
By combining judicious use of wait intervals with accurate time signals,
484
Spanner provides a global ordering between any two non-overlapping transactions
485
(in absolute time) with \~14ms latencies. Put another way:
486
Spanner guarantees that if a transaction T<sub>1</sub> commits (in absolute time)
487
before another transaction T<sub>2</sub> starts, then T<sub>1</sub>'s assigned commit
488
timestamp is smaller than T<sub>2</sub>'s. Using atomic clocks and GPS receivers,
489
Spanner reduces their clock skew uncertainty to \< 10ms (`ε`). To make
490
good on the promised guarantee, transactions must take at least double
491
the clock skew uncertainty interval to commit (`2ε`). See [*this
492
article*](http://www.cs.cornell.edu/~ie53/publications/DC-col51-Sep13.pdf)
493
for a helpful overview of Spanner’s concurrency control.
494
495
Cockroach could make the same guarantees without specialized hardware,
496
at the expense of longer wait times. If servers in the cluster were
497
configured to work only with NTP, transaction wait times would likely to
498
be in excess of 150ms. For wide-area zones, this would be somewhat
499
mitigated by overlap from cross datacenter link latencies. If clocks
500
were made more accurate, the minimal limit for commit latencies would
501
improve.
502
503
However, let’s take a step back and evaluate whether Spanner’s external
504
consistency guarantee is worth the automatic commit wait. First, if the
505
commit wait is omitted completely, the system still yields a consistent
506
view of the map at an arbitrary timestamp. However with clock skew, it
507
would become possible for commit timestamps on non-overlapping but
508
causally related transactions to suffer temporal reverse. In other
509
words, the following scenario is possible for a client without global
510
ordering:
511
512
- Start transaction T<sub>1</sub> to modify value `x` with commit time *s<sub>1</sub>*
513
514
- On commit of T<sub>1</sub>, start T<sub>2</sub> to modify value `y` with commit time
515
\> s<sub>2</sub>
516
517
- Read `x` and `y` and discover that s<sub>1</sub> \> s<sub>2</sub> (**!**)
518
519
The external consistency which Spanner guarantees is referred to as
520
**linearizability**. It goes beyond serializability by preserving
521
information about the causality inherent in how external processes
522
interacted with the database. The strength of Spanner’s guarantee can be
523
formulated as follows: any two processes, with clock skew within
524
expected bounds, may independently record their wall times for the
525
completion of transaction T<sub>1</sub> (T<sub>1</sub><sup>end</sup>) and start of transaction
526
T<sub>2</sub> (T<sub>2</sub><sup>start</sup>) respectively, and if later
527
compared such that T<sub>1</sub><sup>end</sup> \< T<sub>2</sub><sup>start</sup>,
528
then commit timestamps s<sub>1</sub> \< s<sub>2</sub>.
529
This guarantee is broad enough to completely cover all cases of explicit
530
causality, in addition to covering any and all imaginable scenarios of implicit
531
causality.
532
533
Our contention is that causality is chiefly important from the
534
perspective of a single client or a chain of successive clients (*if a
535
tree falls in the forest and nobody hears…*). As such, Cockroach
536
provides two mechanisms to provide linearizability for the vast majority
537
of use cases without a mandatory transaction commit wait or an elaborate
538
system to minimize clock skew.
539
540
1. Clients provide the highest transaction commit timestamp with
541
> successive transactions. This allows node clocks from previous
542
> transactions to effectively participate in the formulation of the
543
> commit timestamp for the current transaction. This guarantees
544
> linearizability for transactions committed by this client.
545
>
546
> Newly launched clients wait at least 2 \* ε from process start
547
> time before beginning their first transaction. This preserves the
548
> same property even on client restart, and the wait will be
549
> mitigated by process initialization.
550
>
551
> All causally-related events within Cockroach maintain
552
> linearizability. Message queues, for example, guarantee that the
553
> receipt timestamp is greater than send timestamp, and that
554
> delivered messages may not be reaped until after the commit wait.
555
556
2. Committed transactions respond with a commit wait parameter which
557
> represents the remaining time in the nominal commit wait. This
558
> will typically be less than the full commit wait as the consensus
559
> write at the coordinator accounts for a portion of it.
560
>
561
> Clients taking any action outside of another Cockroach transaction
562
> (e.g. writing to another distributed system component) can either
563
> choose to wait the remaining interval before proceeding, or
564
> alternatively, pass the wait and/or commit timestamp to the
565
> execution of the outside action for its consideration. This pushes
566
> the burden of linearizability to clients, but is a useful tool in
567
> mitigating commit latencies if the clock skew is potentially
568
> large. This functionality can be used for ordering in the face of
569
> backchannel dependencies as mentioned in the
570
> [AugmentedTime](http://www.cse.buffalo.edu/~demirbas/publications/augmentedTime.pdf)
571
> paper.
572
573
Using these mechanisms in place of commit wait, Cockroach’s guarantee can be
574
formulated as follows: any process which signals the start of transaction
575
T<sub>2</sub> (T<sub>2</sub><sup>start</sup>) after the completion of
576
transaction T<sub>1</sub> (T<sub>1</sub><sup>end</sup>), will have commit
577
timestamps such thats<sub>1</sub> \< s<sub>2</sub>.
578
579
# Logical Map Content
580
581
Logically, the map contains a series of reserved system key / value
582
pairs covering accounting, range metadata, node accounting and
583
permissions before the actual key / value pairs for non-system data
584
(e.g. the actual meat of the map).
585
586
- `\0\0meta1` Range metadata for location of `\0\0meta2`.
587
- `\0\0meta1<key1>` Range metadata for location of `\0\0meta2<key1>`.
588
- ...
589
- `\0\0meta1<keyN>`: Range metadata for location of `\0\0meta2<keyN>`.
590
- `\0\0meta2`: Range metadata for location of first non-range metadata key.
591
- `\0\0meta2<key1>`: Range metadata for location of `<key1>`.
592
- ...
593
- `\0\0meta2<keyN>`: Range metadata for location of `<keyN>`.
594
- `\0acct<key0>`: Accounting for key prefix key0.
595
- ...
596
- `\0acct<keyN>`: Accounting for key prefix keyN.
597
- `\0node<node-address0>`: Accounting data for node 0.
598
- ...
599
- `\0node<node-addressN>`: Accounting data for node N.
600
- `\0perm<key0><user0>`: Permissions for user0 for key prefix key0.
601
- ...
602
- `\0perm<keyN><userN>`: Permissions for userN for key prefix keyN.
603
- `\0tree_root`: Range key for root of range-spanning tree.
604
- `\0tx<tx-id0>`: Transaction record for transaction 0.
605
- ...
606
- `\0tx<tx-idN>`: Transaction record for transaction N.
607
- `\0zone<key0>`: Zone information for key prefix key0.
608
- ...
609
- `\0zone<keyN>`: Zone information for key prefix keyN.
610
- `<>acctd<metric0>`: Accounting data for Metric 0 for empty key prefix.
611
- ...
612
- `<>acctd<metricN>`: Accounting data for Metric N for empty key prefix.
613
- `<key0>`: `<value0>` The first user data key.**
614
- ...
615
- `<keyN>`: `<valueN>` The last user data key.**
616
617
There are some additional system entries sprinkled amongst the
618
non-system keys. See the Key-Prefix Accounting section in this document
619
for further details.
620
621
# Node Storage
622
623
Nodes maintain a separate instance of RocksDB for each disk. Each
624
RocksDB instance hosts any number of ranges. RPCs arriving at a
625
RoachNode are multiplexed based on the disk name to the appropriate
626
RocksDB instance. A single instance per disk is used to avoid
627
contention. If every range maintained its own RocksDB, global management
628
of available cache memory would be impossible and writers for each range
629
would compete for non-contiguous writes to multiple RocksDB logs.
630
631
In addition to the key/value pairs of the range itself, various range
632
metadata is maintained.
633
634
- range-spanning tree node links
635
636
- participating replicas
637
638
- consensus metadata
639
640
- split/merge activity
641
642
A really good reference on tuning Linux installations with RocksDB is
643
[here](http://docs.basho.com/riak/latest/ops/advanced/backends/leveldb/).
644
645
# Range Metadata
646
647
The default approximate size of a range is 64M (2\^26 B). In order to
648
support 1P (2\^50 B) of logical data, metadata is needed for roughly
649
2\^(50 - 26) = 2\^24 ranges. A reasonable upper bound on range metadata
650
size is roughly 256 bytes (3\*12 bytes for the triplicated node
651
locations and 220 bytes for the range key itself*). 2\^24 ranges \* 2\^8
652
B would require roughly 4G (2\^32 B) to store--too much to duplicate
653
between machines. Our conclusion is that range metadata must be
654
distributed for large installations.
655
656
To keep key lookups relatively fast in the presence of distributed metadata,
657
we store all the top-level metadata in a single range (the first range). These
658
top-level metadata keys are known as *meta1* keys, and are prefixed such that
659
they sort to the beginning of the key space. Given the metadata size of 256
660
bytes given above, a single 64M range would support 64M/256B = 2\^18 ranges,
661
which gives a total storage of 64M \* 2\^18 = 16.7T. To support the 1P quoted
662
above, we need two levels of indirection, where the first level addresses the
663
second, and the second addresses user data. With two levels of indirection, we
664
can address 2\^(18 + 18) = 2\^36 ranges; each range addresses 2\^26 B, and
665
altogether we address 2\^(36+26) B = 2\^62 B = 4E of user data.
666
667
For a given user-addressable `key1`, the associated *meta1* record is found
668
at the successor key to `key1` in the *meta1* space. Since the *meta1* space
669
is sparse, the successor key is defined as the next key which is present. The
670
*meta1* record identifies the range containing the *meta2* record, which is
671
found using the same process. The *meta2* record identifies the range
672
containing `key1`, which is again found the same way (see examples below).
674
Concretely, metadata keys are prefixed by `\0\0meta{1,2}`; the two null
675
characters provide for the desired sorting behaviour. Thus, `key1`'s
676
*meta1* record will reside at the successor key to `\0\0\meta1<key1>`.
677
678
Note: we append the end key of each range to meta[12] records because
679
the RocksDB iterator only supports a Seek() interface which acts as a
680
Ceil(). Using the start key of the range would cause Seek() to find the
681
key *after* the meta indexing record we’re looking for, which would
682
result in having to back the iterator up, an option which is both less
683
efficient and not available in all cases.
684
685
The following example shows the directory structure for a map with
686
three ranges worth of data. Ellipses indicate additional key/value pairs to
687
fill an entire range of data. Except for the fact that splitting ranges
688
requires updates to the range metadata with knowledge of the metadata layout,
689
the range metadata itself requires no special treatment or bootstrapping.
690
691
**Range 0** (located on servers `dcrama1:8000`, `dcrama2:8000`,
692
`dcrama3:8000`)
693
694
- `\0\0meta1\xff`: `dcrama1:8000`, `dcrama2:8000`, `dcrama3:8000`
695
- `\0\0meta2<lastkey0>`: `dcrama1:8000`, `dcrama2:8000`, `dcrama3:8000`
696
- `\0\0meta2<lastkey1>`: `dcrama4:8000`, `dcrama5:8000`, `dcrama6:8000`
697
- `\0\0meta2\xff`: `dcrama7:8000`, `dcrama8:8000`, `dcrama9:8000`
698
- ...
699
- `<lastkey0>`: `<lastvalue0>`
700
701
**Range 1** (located on servers `dcrama4:8000`, `dcrama5:8000`,
702
`dcrama6:8000`)
703
704
- ...
705
- `<lastkey1>`: `<lastvalue1>`
706
707
**Range 2** (located on servers `dcrama7:8000`, `dcrama8:8000`,
708
`dcrama9:8000`)
709
710
- ...
711
- `<lastkey2>`: `<lastvalue2>`
712
713
Consider a simpler example of a map containing less than a single
714
range of data. In this case, all range metadata and all data are
715
located in the same range:
716
717
**Range 0** (located on servers `dcrama1:8000`, `dcrama2:8000`,
718
`dcrama3:8000`)*
719
720
- `\0\0meta1\xff`: `dcrama1:8000`, `dcrama2:8000`, `dcrama3:8000`
721
- `\0\0meta2\xff`: `dcrama1:8000`, `dcrama2:8000`, `dcrama3:8000`
722
- `<key0>`: `<value0>`
723
- `...`
724
725
Finally, a map large enough to need both levels of indirection would
726
look like (note that instead of showing range replicas, this
727
example is simplified to just show range indexes):
728
729
**Range 0**
730
731
- `\0\0meta1<lastkeyN-1>`: Range 0
732
- `\0\0meta1\xff`: Range 1
733
- `\0\0meta2<lastkey1>`: Range 1
734
- `\0\0meta2<lastkey2>`: Range 2
735
- `\0\0meta2<lastkey3>`: Range 3
736
- ...
737
- `\0\0meta2<lastkeyN-1>`: Range 262143
738
739
**Range 1**
740
741
- `\0\0meta2<lastkeyN>`: Range 262144
742
- `\0\0meta2<lastkeyN+1>`: Range 262145
743
- ...
744
- `\0\0meta2\xff`: Range 500,000
745
- ...
746
- `<lastkey1>`: `<lastvalue1>`
747
748
**Range 2**
749
750
- ...
751
- `<lastkey2>`: `<lastvalue2>`
752
753
**Range 3**
754
755
- ...
756
- `<lastkey3>`: `<lastvalue3>`
757
758
**Range 262144**
759
760
- ...
761
- `<lastkeyN>`: `<lastvalueN>`
762
763
**Range 262145**
764
765
- ...
766
- `<lastkeyN+1>`: `<lastvalueN+1>`
767
768
Note that the choice of range `262144` is just an approximation. The
769
actual number of ranges addressable via a single metadata range is
770
dependent on the size of the keys. If efforts are made to keep key sizes
771
small, the total number of addressable ranges would increase and vice
772
versa.
773
774
From the examples above it’s clear that key location lookups require at
775
most three reads to get the value for `<key>`:
776
777
1. lower bound of `\0\0meta1<key>`
778
2. lower bound of `\0\0meta2<key>`,
779
3. `<key>`.
780
781
For small maps, the entire lookup is satisfied in a single RPC to Range 0. Maps
782
containing less than 16T of data would require two lookups. Clients cache both
783
levels of range metadata, and we expect that data locality for individual
784
clients will be high. Clients may end up with stale cache entries. If on a
785
lookup, the range consulted does not match the client’s expectations, the
786
client evicts the stale entries and possibly does a new lookup.
787
788
# Range-Spanning Binary Tree
789
790
A crucial enhancement to the organization of range metadata is to
791
augment the bi-level range metadata lookup with a minimum spanning tree,
792
implemented as a left-leaning red-black tree over all ranges in the map.
793
This tree structure allows the system to start at any key prefix and
794
efficiently traverse an arbitrary key range with minimal RPC traffic,
795
minimal fan-in and fan-out, and with bounded time complexity equal to
796
`2*log N` steps, where `N` is the total number of ranges in the system.
797
798
Unlike the range metadata rows prefixed with `\0\0meta[1|2]`, the
799
metadata for the range-spanning tree (e.g. parent range and left / right
800
child ranges) is stored directly at the ranges as non-map metadata. The
801
metadata for each node of the tree (e.g. links to parent range, left
802
child range, and right child range) is stored with the range metadata.
803
In effect, the tree metadata is stored implicitly. In order to traverse
804
the tree, for example, you’d need to query each range in turn for its
805
metadata.
806
807
Any time a range is split or merged, both the bi-level range lookup
808
metadata and the per-range binary tree metadata are updated as part of
809
the same distributed transaction. The total number of nodes involved in
810
the update is bounded by 2 + log N (i.e. 2 updates for meta1 and
811
meta2, and up to log N updates to balance the range-spanning tree).
812
The range corresponding to the root node of the tree is stored in
Apr 23, 2015
813
*\0tree_root*.
814
815
As an example, consider the following set of nine ranges and their
816
associated range-spanning tree:
817
818
R0: `aa - cc`, R1: `*cc - lll`, R2: `*lll - llr`, R3: `*llr - nn`, R4: `*nn - rr`, R5: `*rr - ssss`, R6: `*ssss - sst`, R7: `*sst - vvv`, R8: `*vvv - zzzz`.
819
820
![Range Tree](media/rangetree.png)
821
822
The range-spanning tree has many beneficial uses in Cockroach. It makes
823
the problem of efficiently aggregating accounting information of
824
potentially vast ranges of data tractable. Imagine a subrange of data
825
over which accounting is being kept. For example, the *photos* table in
826
a public photo sharing site. To efficiently keep track of data about the
827
table (e.g. total size, number of rows, etc.), messages can be passed
828
first up the tree and then down to the left until updates arrive at the
829
key prefix under which accounting is aggregated. This makes worst case
830
number of hops for an update to propagate into the accounting totals
831
2 \* log N. A 64T database will require 1M ranges, meaning 40 hops
832
worst case. In our experience, accounting tasks over vast ranges of data
833
are most often map/reduce jobs scheduled with coarse-grained
834
periodicity. By contrast, we expect Cockroach to maintain statistics
835
with sub 10s accuracy and with minimal cycles and minimal IOPs.
836
837
Another use for the range-spanning tree is to push accounting, zones and
838
permissions configurations to all ranges. In the case of zones and
839
permissions, this is an efficient way to pass updated configuration
840
information with exponential fan-out. When adding accounting
841
configurations (i.e. specifying a new key prefix to track), the
842
implicated ranges are transactionally scanned and zero-state accounting
843
information is computed as well. Deleting accounting configurations is
844
similar, except accounting records are deleted.
845
846
Last but *not* least, the range-spanning tree provides a convenient
847
mechanism for planning and executing parallel queries. These provide the
848
basis for
849
[Dremel](http://static.googleusercontent.com/media/research.google.com/en/us/pubs/archive/36632.pdf)-like
850
query execution trees and it’s easy to imagine supporting a subset of
851
SQL or even javascript-based user functions for complex data analysis
852
tasks.
853
854
# Raft - Consistency of Range Replicas
855
856
Each range is configured to consist of three or more replicas. The
857
replicas in a range maintain their own instance of a distributed
858
consensus algorithm. We use the [*Raft consensus
859
algorithm*](https://ramcloud.stanford.edu/wiki/download/attachments/11370504/raft.pdf)
860
as it is simpler to reason about and includes a reference implementation
861
covering important details. Every write to replicas is logged twice.
862
Once to RocksDB’s internal log and once to levedb itself as part of the
863
Raft consensus log.
864
[ePaxos](https://www.cs.cmu.edu/~dga/papers/epaxos-sosp2013.pdf) has
865
promising performance characteristics for WAN-distributed replicas, but
866
it does not guarantee a consistent ordering between replicas.
867
868
Raft elects a relatively long-lived leader which must be involved to
869
propose writes. It heartbeats followers periodically to keep their logs
870
replicated. In the absence of heartbeats, followers become candidates
871
after randomized election timeouts and proceed to hold new leader
872
elections. Cockroach weights random timeouts such that the replicas with
873
shorter round trip times to peers are more likely to hold elections
874
first. Although only the leader can propose a new write, and as such
875
must be involved in any write to the consensus log, any replica can
876
service reads if the read is for a timestamp which the replica knows is
877
safe based on the last committed consensus write and the state of any
878
pending transactions.
879
880
Only the leader can propose a new write, but Cockroach accepts writes at
881
any replica. The replica merely forwards the write to the leader.
882
Instead of resending the write, the leader has only to acknowledge the
883
write to the forwarding replica using a log sequence number, as though
884
it were proposing it in the first place. The other replicas receive the
885
full write as though the leader were the originator.
886
887
Having a stable leader provides the choice of replica to handle
888
range-specific maintenance and processing tasks, such as delivering
889
pending message queues, handling splits and merges, rebalancing, etc.
890
891
# Splitting / Merging Ranges
892
893
RoachNodes split or merge ranges based on whether they exceed maximum or
894
minimum thresholds for capacity or load. Ranges exceeding maximums for
895
either capacity or load are split; ranges below minimums for *both*
896
capacity and load are merged.
897
898
Ranges maintain the same accounting statistics as accounting key
899
prefixes. These boil down to a time series of data points with minute
900
granularity. Everything from number of bytes to read/write queue sizes.
901
Arbitrary distillations of the accounting stats can be determined as the
902
basis for splitting / merging. Two sensical metrics for use with
903
split/merge are range size in bytes and IOps. A good metric for
904
rebalancing a replica from one node to another would be total read/write
905
queue wait times. These metrics are gossipped, with each range / node
906
passing along relevant metrics if they’re in the bottom or top of the
907
range it’s aware of.
908
909
A range finding itself exceeding either capacity or load threshold
910
splits. To this end, the range leader computes an appropriate split key
911
candidate and issues the split through Raft. In contrast to splitting,
912
merging requires a range to be below the minimum threshold for both
913
capacity *and* load. A range being merged chooses the smaller of the
914
ranges immediately preceding and succeeding it.
915
916
Splitting, merging, rebalancing and recovering all follow the same basic
917
algorithm for moving data between roach nodes. New target replicas are
918
created and added to the replica set of source range. Then each new
919
replica is brought up to date by either replaying the log in full or
920
copying a snapshot of the source replica data and then replaying the log
921
from the timestamp of the snapshot to catch up fully. Once the new
922
replicas are fully up to date, the range metadata is updated and old,
923
source replica(s) deleted if applicable.
924
925
**Coordinator** (leader replica)
926
927
```
928
if splitting
Apr 23, 2015
929
SplitRange(split_key): splits happen locally on range replicas and
930
only after being completed locally, are moved to new target replicas.
931
else if merging
932
Choose new replicas on same servers as target range replicas;
933
add to replica set.
934
else if rebalancing || recovering
935
Choose new replica(s) on least loaded servers; add to replica set.
936
```
937
938
**New Replica**
939
940
*Bring replica up to date:*
941
942
```
943
if all info can be read from replicated log
944
copy replicated log
945
else
946
snapshot source replica
947
send successive ReadRange requests to source replica
948
referencing snapshot
949
950
if merging
951
combine ranges on all replicas
952
else if rebalancing || recovering
953
remove old range replica(s)
954
```
955
956
RoachNodes split ranges when the total data in a range exceeds a
957
configurable maximum threshold. Similarly, ranges are merged when the
958
total data falls below a configurable minimum threshold.
959
960
**TBD: flesh this out**.
961
962
Ranges are rebalanced if a node determines its load or capacity is one
963
of the worst in the cluster based on gossipped load stats. A node with
964
spare capacity is chosen in the same datacenter and a special-case split
965
is done which simply duplicates the data 1:1 and resets the range
966
configuration metadata.
967
968
# Message Queues
969
970
Each range maintains an array of incoming message queues, referred to
971
here as **inboxes**. Additionally, each range maintains and *processes*
972
an array of outgoing message queues, referred to here as **outboxes**.
973
Both inboxes and outboxes are assigned to keys; messages can be sent or
974
received on behalf of any key. Inboxes and outboxes can contain any
975
number of pending messages.
976
977
Messages can be *deliverable*, or *executable.*
978
979
Deliverable messages are defined by Value objects - simple byte arrays -
980
that are delivered to a key’s inbox, awaiting collection by a client
981
invoking the ReapQueue operation. These are typically used by client
982
applications wishing to be notified of changes to an entry for further
983
processing, such as expensive offline operations like sending emails,
984
SMSs, etc.
985
986
Executable messages are *outgoing-only*, and are instances of
987
PutRequest,IncrementRequest, DeleteRequest, DeleteRangeRequest
May 29, 2015
988
or AccountingRequest. Rather than being delivered to a key’s inbox, are
989
executed when encountered. These are primarily useful when updates that
990
are nominally part of a transaction can tolerate asynchronous execution
991
(e.g. eventual consistency), and are otherwise too busy or numerous to
992
make including them in the original [distributed] transaction efficient.
993
Examples may include updates to the accounting for successive key
994
prefixes (potentially busy) or updates to a full-text index (potentially
995
numerous).
996
997
These two types of messages are enqueued in different outboxes too - see
998
key formats below.
999
1000
At commit time, the range processing the transaction places messages
1001
into a shared outbox located at the start of the range metadata. This is
1002
effectively free as it’s part of the same consensus write for the range
1003
as the COMMIT record. Outgoing messages are processed asynchronously by
1004
the range. To make processing easy, all outboxes are co-located at the
1005
start of the range. To make lookup easy, all inboxes are located
1006
immediately after the recipient key. The leader replica of a range is
1007
responsible for processing message queues.
1008
1009
A dispatcher polls a given range’s *deliverable message outbox*
1010
periodically (configurable), and delivers those messages to the target
1011
key’s inbox. The dispatcher is also woken up whenever a new message is
1012
added to the outbox. A separate executor also polls the range’s
1013
*executable message outbox* periodically as well (again, configurable),
May 31, 2015
1014
and executes those commands. The executor, too, is woken up whenever a
1015
new message is added to the outbox.
1016
1017
Formats follow in the table below. Notice that inbox messages for a
1018
given key sort by the `<outbox-timestamp>`. This doesn’t provide a
1019
precise ordering, but it does allow clients to scan messages in an
1020
approximate ordering of when they were originally lodged with senders.
1021
NTP offers walltime deltas to within 100s of milliseconds. The
1022
`<sender-range-key>` suffix provides uniqueness.
1023
1024
**Outbox**
1025
`<sender-range-key>deliverable-outbox:<recipient-key><outbox-timestamp>`
1026
`<sender-range-key>executable-outbox:<recipient-key><outbox-timestamp>`
1027
1028
**Inbox**
1029
`<recipient-key>inbox:<outbox-timestamp><sender-range-key>`
1030
1031
Messages are processed and then deleted as part of a single distributed
1032
transaction. The message will be executed or delivered exactly once,
1033
regardless of failures at either sender or receiver.
1034
1035
Delivered messages may be read by clients via the ReapQueue operation.
1036
This operation may only be used as part of a transaction. Clients should
1037
commit only after having processed the message. If the transaction is
1038
committed, scanned messages are automatically deleted. The operation
1039
name was chosen to reflect its mutating side effect. Deletion of read
1040
messages is mandatory because senders deliver messages asynchronously
1041
and a delay could cause insertion of messages at arbitrary points in the
1042
inbox queue. If clients require persistence, they should re-save read
1043
messages manually; the ReapQueue operation can be incorporated into
1044
normal transactional updates.
1045
1046
# Node Allocation (via Gossip)
1047
1048
New nodes must be allocated when a range is split. Instead of requiring
1049
every RoachNode to know about the status of all or even a large number
1050
of peer nodes --or-- alternatively requiring a specialized curator or
1051
master with sufficiently global knowledge, we use a gossip protocol to
1052
efficiently communicate only interesting information between all of the
1053
nodes in the cluster. What’s interesting information? One example would
1054
be whether a particular node has a lot of spare capacity. Each node,
1055
when gossiping, compares each topic of gossip to its own state. If its
1056
own state is somehow “more interesting” than the least interesting item
1057
in the topic it’s seen recently, it includes its own state as part of
1058
the next gossip session with a peer node. In this way, a node with
1059
capacity sufficiently in excess of the mean quickly becomes discovered
1060
by the entire cluster. To avoid piling onto outliers, nodes from the
1061
high capacity set are selected at random for allocation.
1062
1063
The gossip protocol itself contains two primary components:
1064
1065
- **Peer Selection**: each node maintains up to N peers with which it
1066
regularly communicates. It selects peers with an eye towards
1067
maximizing fanout. A peer node which itself communicates with an
1068
array of otherwise unknown nodes will be selected over one which
1069
communicates with a set containing significant overlap. Each time
1070
gossip is initiated, each nodes’ set of peers is exchanged. Each
1071
node is then free to incorporate the other’s peers as it sees fit.
1072
To avoid any node suffering from excess incoming requests, a node
1073
may refuse to answer a gossip exchange. Each node is biased
1074
towards answering requests from nodes without significant overlap
1075
and refusing requests otherwise.
1076
1077
Peers are efficiently selected using a heuristic as described in
1078
[Agarwal & Trachtenberg (2006)](https://drive.google.com/file/d/0B9GCVTp_FHJISmFRTThkOEZSM1U/edit?usp=sharing).
1079
1080
**TBD**: how to avoid partitions? Need to work out a simulation of
1081
the protocol to tune the behavior and see empirically how well it
1082
works.
1083
1084
- **Gossip Selection**: what to communicate. Gossip is divided into
1085
topics. Load characteristics (capacity per disk, cpu load, and
1086
state [e.g. draining, ok, failure]) are used to drive node
1087
allocation. Range statistics (range read/write load, missing
1088
replicas, unavailable ranges) and network topology (inter-rack
1089
bandwidth/latency, inter-datacenter bandwidth/latency, subnet
1090
outages) are used for determining when to split ranges, when to
1091
recover replicas vs. wait for network connectivity, and for
1092
debugging / sysops. In all cases, a set of minimums and a set of
1093
maximums is propagated; each node applies its own view of the
1094
world to augment the values. Each minimum and maximum value is
1095
tagged with the reporting node and other accompanying contextual
1096
information. Each topic of gossip has its own protobuf to hold the
1097
structured data. The number of items of gossip in each topic is
1098
limited by a configurable bound.
1099
1100
For efficiency, nodes assign each new item of gossip a sequence
1101
number and keep track of the highest sequence number each peer
1102
node has seen. Each round of gossip communicates only the delta
1103
containing new items.
1104
1105
# Node Accounting
1106
1107
The gossip protocol discussed in the previous section is useful to
1108
quickly communicate fragments of important information in a
1109
decentralized manner. However, complete accounting for each node is also
1110
stored to a central location, available to any dashboard process. This
1111
is done using the map itself. Each node periodically writes its state to
1112
the map with keys prefixed by `\0node`, similar to the first level of
1113
range metadata, but with an ‘`node`’ suffix. Each value is a protobuf
1114
containing the full complement of node statistics--everything
1115
communicated normally via the gossip protocol plus other useful, but
1116
non-critical data.
1117
1118
The range containing the first key in the node accounting table is
1119
responsible for gossiping the total count of nodes. This total count is
1120
used by the gossip network to most efficiently organize itself. In
1121
particular, the maximum number of hops for gossipped information to take
1122
before reaching a node is given by `ceil(log(node count) / log(max
1123
fanout)) + 1`.
1124
1125
# Key-prefix Accounting, Zones & Permissions
1126
1127
Arbitrarily fine-grained accounting and permissions are specified via
1128
key prefixes. Key prefixes can overlap, as is necessary for capturing
1129
hierarchical relationships. For illustrative purposes, let’s say keys
1130
specifying rows in a set of databases have the following format:
1131
1132
`<db>:<table>:<primary-key>[:<secondary-key>]`
1133
1134
In this case, we might collect accounting or specify permissions with
1135
key prefixes:
1136
1137
`db1`, `db1:user`, `db1:order`,
1138
1139
Accounting is kept for the entire map by default.
1140
1141
## Accounting
1142
to keep accounting for a range defined by a key prefix, an entry is created in
1143
the accounting system table. The format of accounting table keys is:
1144
1145
`\0acct<key-prefix>`
1146
1147
In practice, we assume each RoachNode capable of caching the
1148
entire accounting table as it is likely to be relatively small.
1149
1150
Accounting is kept for key prefix ranges with eventual consistency
1151
for efficiency. Updates to accounting values propagate through the
1152
system using the message queue facility if the accounting keys do
1153
not reside on the same range as ongoing activity (true for all but
1154
the smallest systems). There are two types of values which
1155
comprise accounting: counts and occurrences, for lack of better
1156
terms. Counts describe system state, such as the total number of
1157
bytes, rows, etc. Occurrences include transient performance and
1158
load metrics. Both types of accounting are captured as time series
1159
with minute granularity. The length of time accounting metrics are
1160
kept is configurable. Below are examples of each type of
1161
accounting value.
1162
1163
**System State Counters/Performance**
1164
1165
- Count of items (e.g. rows)
1166
- Total bytes
1167
- Total key bytes
1168
- Total value length
1169
- Queued message count
1170
- Queued message total bytes
1171
- Count of values \< 16B
1172
- Count of values \< 64B
1173
- Count of values \< 256B
1174
- Count of values \< 1K
1175
- Count of values \< 4K
1176
- Count of values \< 16K
1177
- Count of values \< 64K
1178
- Count of values \< 256K
1179
- Count of values \< 1M
1180
- Count of values \> 1M
1181
- Total bytes of accounting
1182
1183
1184
**Load Occurences**
1185
1186
Get op count
1187
Get total MB
1188
Put op count
1189
Put total MB
1190
Delete op count
1191
Delete total MB
1192
Delete range op count
1193
Delete range total MB
1194
Scan op count
1195
Scan op MB
1196
Split count
1197
Merge count
1198
1199
Because accounting information is kept as time series and over many
1200
possible metrics of interest, the data can become numerous. Accounting
1201
data are stored in the map near the key prefix described, in order to
1202
distribute load (for both aggregation and storage).
1203
1204
Accounting keys for system state have the form:
1205
`<key-prefix>|acctd<metric-name>*`. Notice the leading ‘pipe’
1206
character. It’s meant to sort the root level account AFTER any other
1207
system tables. They must increment the same underlying values as they
1208
are permanent counts, and not transient activity. Logic at the
1209
RoachNode takes care of snapshotting the value into an appropriately
1210
suffixed (e.g. with timestamp hour) multi-value time series entry.
1211
1212
Keys for perf/load metrics:
1213
`<key-prefix>acctd<metric-name><hourly-timestamp>`.
1214
1215
`<hourly-timestamp>`-suffixed accounting entries are multi-valued,
1216
containing a varint64 entry for each minute with activity during the
1217
specified hour.
1218
1219
To efficiently keep accounting over large key ranges, the task of
1220
aggregation must be distributed. If activity occurs within the same
1221
range as the key prefix for accounting, the updates are made as part
1222
of the consensus write. If the ranges differ, then a message is sent
1223
to the parent range to increment the accounting. If upon receiving the
1224
message, the parent range also does not include the key prefix, it in
1225
turn forwards it to its parent or left child in the balanced binary
1226
tree which is maintained to describe the range hierarchy. This limits
1227
the number of messages before an update is visible at the root to `2*log N`,
1228
where `N` is the number of ranges in the key prefix.
1229
1230
## Zones
1231
zones are stored in the map with keys prefixed by
1232
`\0zone` followed by the key prefix to which the zone
1233
configuration applies. Zone values specify a protobuf containing
1234
the datacenters from which replicas for ranges which fall under
1235
the zone must be chosen.
1236
1237
Please see [proto/config.proto](https://github.com/cockroachdb/cockroach/blob/master/proto/config.proto) for up-to-date data structures used, the best entry point being `message ZoneConfig`.
1238
1239
If zones are modified in situ, each RoachNode verifies the
1240
existing zones for its ranges against the zone configuration. If
1241
it discovers differences, it reconfigures ranges in the same way
1242
that it rebalances away from busy nodes, via special-case 1:1
1243
split to a duplicate range comprising the new configuration.
1244
1245
### Permissions
1246
permissions are stored in the map with keys prefixed by *\0perm* followed by
1247
the key prefix and user to which the specified permissions apply. The format of
1248
permissions keys is:
1249
1250
`\0perm<key-prefix><user>`
1251
1252
Permission values are a protobuf containing the permission details;
1253
please see [proto/config.proto](https://github.com/cockroachdb/cockroach/blob/master/proto/config.proto) for up-to-date data structures used, the best entry point being `message PermConfig`.
1254
1255
A default system root permission is assumed for the entire map
1256
with an empty key prefix and read/write as true.
1257
1258
When determining whether or not to allow a read or a write a key
1259
value (e.g. `db1:user:1` for user `spencer`), a RoachNode would
1260
read the following permissions values:
1261
1262
```
1263
\0perm<db1:user:1>spencer
1264
\0perm<db1:user>spencer
1265
\0perm<db1>spencer
1266
\0perm<>spencer
1267
```
1268
1269
If any prefix in the hierarchy provides the required permission,
1270
the request is satisfied; otherwise, the request returns an
1271
error.
1272
1273
The priority for a user permission is used to order requests at
1274
Raft consensus ranges and for choosing an initial priority for
1275
distributed transactions. When scheduling operations at the Raft
1276
consensus range, all outstanding requests are ordered by key
1277
prefix and each assigned priorities according to key, user and
1278
arrival time. The next request is chosen probabilistically using
1279
priorities to weight the choice. Each key can have multiple
1280
priorities as they’re hierarchical (e.g. for /user/key, one
1281
priority for root ‘/’, and one for ‘/user/key’). The most general
1282
priority is used first. If two keys share the most general, then
1283
they’re compared with the next most general if applicable, and so on.
1284
1285
# Key-Value API
1286
1287
see the protobufs in [proto/](https://github.com/cockroachdb/cockroach/blob/master/proto),
1288
in particular [proto/api.proto](https://github.com/cockroachdb/cockroach/blob/master/proto/api.proto) and the comments within.
1289
1290
# Structured Data API
1291
1292
A preliminary design can be found in the [Go source documentation](http://godoc.org/github.com/cockroachdb/cockroach/structured).