Overview of the Patterns

by Unmesh Joshi and Martin Fowler

As discussed in the last chapter, distributing data means at least one of two things: partitioning and replication. To start our journey through the patterns in this book, we’ll focus on replication first.

Imagine a very minimal data record that captures how many widgets we have in four locations ( Figure 2.1 ).

Images

Figure 2.1 An example data record

We replicate it on three nodes: Jupiter, Saturn, and Neptune ( Figure 2.2 ).

Images

Figure 2.2 Replicated data record

Keeping Data Resilient on a Single Server

The first area of potential inconsistency appears with no distribution at all. Consider a case where the data for Boston, London, and Pune are held on different files. In this case, performing a transfer of 40 widgets means changing bos.json to reduce its count to 10 and changing pnq.json to increase its count to 115. But what happens if Neptune crashes after changing Boston’s file but before updating Pune’s? In that case we would have inconsistent data, destroying 40 widgets ( Figure 2.3 ).

Images

Figure 2.3 Node crash causes inconsistency

An effective solution to this is Write-Ahead Log ( Figure 2.4 ). With this, the message handler first writes all the information about the required update to a log file. This is a single write, so is simple to ensure it’s done atomically. Once the write is done, the handler can acknowledge to its caller that it has handled the request. Then the handler, or other component, can read the log entry and carry out the updates to the underlying files.

Images

Figure 2.4 Using WAL

Should Neptune crash after updating Boston, the log should contain enough information for Neptune, when it restarts, to figure out what happened and restore the data to a consistent state, as shown in Figure 2.5 . (In this case it would store the previous values in the log before any updates are made to the data file.)

Images

Figure 2.5 Recovery using WAL

The log gives us resilience because, for a known prior state, the linear sequence of changes determines the state after the log is executed. This property is important for resilience in a single node scenario but, as we’ll see, it’s also very valuable for replication. If multiple nodes start at the same state, and they all play the same log entries, we know they will end up at the same state too.

Databases use a Write-Ahead Log, as discussed in the above example, to implement transactions.

Competing Updates

Suppose two different users, Alice and Bob, are connecting to two different cluster nodes to execute their requests. Alice wants to move 30 widgets from Boston to London, while Bob wants to move 40 widgets from Boston to Pune ( Figure 2.6 ).

Images

Figure 2.6 Competing updates

How should the cluster resolve this? We can’t have any node just decide to do an update because we’d quickly run into inconsistency hell as we try to figure out how to get Boston to store antimatter widgets. One of the most straightforward approaches is Leader and Followers , where one of the nodes is marked as the leader, and the others are considered followers. In this situation, the leader handles all updates and broadcasts those updates to the followers. Let’s say Neptune is the leader in this cluster. Then, Jupiter will forward Alice’s A1 request to Neptune ( Figure 2.7 ).

Images

Figure 2.7 Leader handling all the updates

Neptune now gets both update requests, so it has the sole discretion as to how to deal with them. It can process the first one it receives (Bob’s B1) and reject A1 ( Figure 2.8 ).

Images

Figure 2.8 Leader rejecting requests for insufficient widgets

Dealing with the Leader Failing

That’s what happens most of the time—when all goes well. But the point of getting a distributed system to work is what happens when things don’t go well. Here’s a different case. Neptune receives B1 and sends out its replication messages. But it is unable to contact Saturn. It could replicate only to Jupiter. At this point it loses all connectivity with the other two nodes. This leaves Jupiter and Saturn connected together, but disconnected from their leader ( Figure 2.9 ).

Images

Figure 2.9 Leader failure

So now what do these nodes do? For a start, how do they even find out what’s broken? Neptune can’t send Jupiter and Saturn a message saying the connection is broken . . . because the connection is broken. Nodes need a way to find out when connections to their colleagues break. They do this with a HeartBeat —or, more strictly, with the absence of a heartbeat.

A heartbeat is a regular message sent between nodes, just to indicate they are alive and communicating. Heartbeat does not necessarily require a distinct message type. When cluster nodes are already engaged in communication, such as when replicating data, the existing messages can serve the purpose of heartbeats. If Saturn doesn’t receive a heartbeat from Neptune for a period of time, Saturn marks Neptune as down. Since Neptune is the leader, Saturn now calls for an election for a new leader ( Figure 2.10 ).

Images

Figure 2.10 Leader sending heartbeats

The heartbeat gives us a way to know that Neptune has disconnected, so now we can turn to the problem of how to deal with Bob’s request. We need to ensure that once Neptune has confirmed the update to Bob, even if Neptune crashes, the followers can elect a new leader with B1 applied to their data. But we also need to deal with more complication than that, as Neptune may have received multiple messages. Consider the case where there are messages from both Alice (A1) and Bob (B1) handled by Neptune. Neptune successfully replicates them both with Jupiter but is unable to contact Saturn before it crashes, as shown in Figure 2.11 .

Images

Figure 2.11 Leader failure—incomplete replication

In this case, how do Jupiter and Saturn deal with the fact that they have different states?

The answer is essentially the same as discussed earlier for resilience on a single node. If Neptune writes changes into a Write-Ahead Log and treats replication as copying those log entries to its followers, then its followers will be able to figure out what the correct state is by examining the log entries ( Figure 2.12 ).

Images

Figure 2.12 Leader failure—incomplete replication—using log

When Jupiter and Saturn elect a new leader, they can tell that Jupiter’s log has later index entries, and Saturn can apply those log entries to itself to gain a consistent state with Jupiter.

This is also why Neptune can reply to Bob that the update was accepted, even though it hadn’t heard back from Saturn. As long as a Majority Quorum —that is, a majority—of the nodes in the cluster have successfully replicated the log messages, Neptune can be sure that the cluster will maintain consistency even if the leader disconnects.

Multiple Failures Need a Generation Clock

We assumed here that Jupiter and Saturn can figure out whose log is most up to date. But things can get trickier. Let’s say Neptune accepted a request from Bob to move 40 widgets from Boston to Pune but failed before replicating it ( Figure 2.13 ).

Images

Figure 2.13 Leader fails before replication.

Jupiter is elected as a new leader, and accepts a request from Alice to move 30 widgets from Boston to London. But it also crashes before replicating the request to other nodes ( Figure 2.14 ).

Images

Figure 2.14 New leader fails before replication.

In a while, Neptune and Jupiter come back, but before they can talk, Saturn crashes. Neptune is elected as a leader. Neptune checks with itself and Jupiter for the log entries. It will see two separate requests at index 1, the one from Bob which it had accepted and the one from Alice that Jupiter has accepted. Neptune can’t tell which one it should pick ( Figure 2.15 ).

Images

Figure 2.15 Leader needs to resolve existing log entries.

To solve this kind of situation, we use a Generation Clock . This is a number that increments with each leadership election. It is a key requirement of Leader and Followers .

Looking at the previous scenario again, Neptune was leader for generation 1. It adds Bob’s entry in its log marking it with its generation ( Figure 2.16 ).

Images

Figure 2.16 Leader adds generation to log entries.

When Jupiter gets elected as a leader, it increments the generation to 2. So when it adds Alice’s entry to its log, it’s marked for generation 2 ( Figure 2.17 ).

Images

Figure 2.17 New leader increments generation.

Now, when Neptune is again elected as a leader, it will be for generation 3. Before it starts serving the client requests, it checks the logs of all the available nodes for entries which are not replicated on the Majority Quorum . We call these entries as “uncommitted,” as they are not yet applied to data. We will see how each node figures out which entries are incompletely replicated in a while. But once the leader knows about these entries, it completes the replication for those entries. In case of conflict, it safely picks up the entry with higher generation ( Figure 2.18 ).

Images

Figure 2.18 Conflicting log entries are resolved based on generation.

After selecting the entry with the latest generation, Neptune overwrites the uncommitted entry in its own log with its current generation number and replicates with Jupiter.

Every node tracks the latest generation it knows of the leader. This is helpful in another problem that might occur, as Figure 2.19 demonstrates. When Jupiter became leader, the previous leader, Neptune, might not have crashed, but just temporarily disconnected. It might come back online and send the requests to Jupiter and Saturn. If Jupiter and Saturn have elected a new leader and accepted requests from Alice, what should they do when they suddenly start getting requests from Neptune? Generation Clock is useful in this case as well. Every request is sent to cluster nodes, along with the generation clock. So every node can always choose the requests with the higher generation and reject the ones with the lower generation.

Images

Figure 2.19 Generation helps detecting stale requests from old leader.

Log Entries Cannot Be Committed until They Are Accepted by a Majority Quorum

As seen above, entries like B1 can be overwritten if they haven’t been successfully replicated to a Majority Quorum of nodes in the cluster. So the leader cannot apply the request to its data store after just appending to its own log—it has to wait until it gets enough acknowledgments from other nodes first. When an update is added to a local log, it is uncommitted , until the leader has had replies from a Majority Quorum of other nodes, at which point it becomes committed . In the case of the example above, Neptune cannot commit B1 until it hears that at least one other node has accepted it, at which point that other node, plus Neptune itself, makes two out of three nodes—a majority and thus a Majority Quorum.

When Neptune, the leader, receives an update, either from a user (Bob) directly or via a follower, it adds the uncommitted update to its log and then sends replication messages to the other nodes. Once Saturn (for example) replies, that means two nodes have accepted the update, Neptune and Saturn. This is two out of three nodes, which is the majority and thus a Majority Quorum. At that point Neptune can commit the update ( Figure 2.20 ).

Images

Figure 2.20 Log entries are committed once they are accepted by a Majority Quorum.

The importance of the Majority Quorum is that it applies to decision by the cluster. Should a node fail, any leadership election must involve a Majority Quorum of nodes. Since any committed updates have also been sent to a Majority Quorum of nodes, we can be sure that committed updates will be visible during the election.

If Neptune receives Bob’s update (B1), replicates, gets an acknowledgment from Saturn, and then crashes, Saturn still has a copy of B1. If the nodes then elect Jupiter as the leader, Jupiter must apply any uncommitted updates—that is, B1—before it can start accepting new ones ( Figure 2.21 ).

Images

Figure 2.21 New leader commits uncommitted log entries.

When the log is large, moving the log across nodes for leader election can be costly. The most commonly used algorithm for Replicated Log , Raft [ Ongaro2014 ], optimizes this by electing the leader with the most up-to-date log. In the above example this would elect Saturn as the leader.

Followers Commit Based on a High-Water Mark

As we’ve seen, leaders commit when they get acknowledgments from a Majority Quorum —but when do followers commit their log entries? In the three node example we’ve been using, it’s obvious. Since we know the leader must have added the log entry before it replicates, any node knows that it can commit since it and the leader form a Majority Quorum. But that isn’t true for larger clusters. In a five-node cluster, a single follower and a leader are only two of five.

A High-Water Mark solves this conundrum. Simply put, the High-Water Mark is maintained by the leader and is equal to the index of the latest update to be committed. The leader then adds the High-Water Mark to its HeartBeat . Whenever a follower receives a HeartBeat, it knows it can commit all its log entries up to the High-Water Mark.

Let’s look at an example of this ( Figure 2.22 ). Bob sends a request (B1) to Neptune. Neptune replicates the request to Jupiter and Saturn. Jupiter acknowledges first, allowing Neptune to increase its High-Water Mark to 1, execute the update against its data store, and return success to Bob. Saturn’s acknowledgment is late, and since it’s not higher than the High-Water Mark, Neptune takes no action on it.

Images

Figure 2.22 Leader tracks High-Water Mark.

Neptune now gets three requests from Alice (A1, A2, and A3). Neptune puts all of these into its log and starts sending replication messages. The link between Neptune and Saturn, however, gets tangled and Saturn doesn’t get them ( Figure 2.23 ).

Images

Figure 2.23 Nodes missing replication of log entries

After the first two messages, Neptune coincidentally sends out heartbeats, which alert followers to update their High-Water Mark. Jupiter acknowledges A1, allowing Neptune to update its High-Water Mark to 2, execute the update, and notify Alice. But then Neptune crashes before it’s able to replicate A3, as shown in Figure 2.24 .

Images

Figure 2.24 The High-Water Mark is propagated using HeartBeat.

At this point, here are the states of the nodes:

| | Jupiter | Saturn | Neptune | | --- | --- | --- | --- | | gen | 1 | 1 | 1 | | hwm | 1 | 0 | 2 | | log | B1 A1 A2 | B1 | B1 A1 A2 A3 |

Jupiter and Saturn fail to get HeartBeat from Neptune and thus hold an election for a new leader. Jupiter wins and gathers log entries. In doing this it accepts that A2 reached Majority Quorum and sets its High-Water Mark to 3. Jupiter replicates its log to Saturn, and when Saturn gets a HeartBeat with High-Water Mark of 3 it’s able to update its High-Water Mark and execute the updates against its store ( Figure 2.25 ).

Images

Figure 2.25 New leader replicates missing log entries and High-Water Mark.

Now, the state of the nodes is:

| | Jupiter | Saturn | Neptune | | --- | --- | --- | --- | | gen | 2 | 2 | 1 | | hwm | 3 | 3 | 2 | | log | B1 A1 A2 | B1 A1 A2 | B1 A1 A2 A3 |

At this point Alice times out of her A3 request and resends it (A3.2), which routes to Jupiter as the new leader. Just as this happens, Neptune starts back up again. Neptune tries to replicate A3, and is told that there’s a new generation of leader, so Neptune accepts that it’s now a follower of Jupiter and discards its log down to its High-Water Mark. Jupiter sends replication messages for A2 and A3.2. Once Jupiter gets an acknowledgment for A3.2, it can update its High-Water Mark, execute the update, and respond to Alice ( Figure 2.26 ).

Images

Figure 2.26 Old leader discards conflicting log entries.

Saturn and Neptune will update their states on the next HeartBeat from Jupiter.

Leaders Use a Series of Queues to Remain Responsive to Many Clients

A leader has to handle a lot of requests from many clients. Each request takes a fair bit of processing that happens in multiple stages. Requests need to be parsed to understand the request and its payload. Updates need to be persisted to a Write-Ahead Log , which means a write to a durable store, and in this context “durable” means “slow.” Requests may also be acknowledgments from followers for a replication request—for these, the leader needs to find the request, check to see if it’s reached Majority Quorum and, if so, update the High-Water Mark .

We need to ensure that these operations don’t run into problems with multiple threads trying to update the same data at once. Each entry on the Write-Ahead Log needs to be written and processed in full before we start to write another. We don’t want clients to wait for other clients to finish their work. At the same time, we do not want other processing stages to be blocked while all of this is going on.

For these reasons, we use a Singular Update Queue . Most programming languages these days will have some form of in-memory queue object that handles requests from multiple threads. Singular Update Queue builds on this by allowing client threads to write simple entries onto such an in-memory queue. A separate processing thread takes entries from this work queue, and carries out the processing we discussed above. This way the system remains responsive to clients, but also keeps the processing of requests in a saner, single-threaded world.

Some programming languages, like Go, 14 have first-class support for this mechanism with channels and goroutines.

  1. [https://go.dev](https://go.dev)

If Alice and Bob both send messages (A1 and B1) to Neptune, they will be handled by different message handling threads on Neptune. Each of these put the mostly raw message onto the work queue. The thread handling the Replicated Log works independently, popping from the head of the queue, unpacking the details, adding to the log, and sending for replication ( Figure 2.27 ).

Images

Figure 2.27 Nodes use queues to decouple processing stages.

When Jupiter acknowledges the replication, its response is handled by a message handler, which just puts the raw message on the work queue. The processing thread picks this message, checks Majority Quorum, marks the log entry as committed, and updates the High-Water Mark ( Figure 2.28 ).

Images

Figure 2.28 Async processing stage committing log entries

In a cluster like this, an update can only be confirmed once a Majority Quorum of nodes accepts the update. But we don’t want to leave the message handler blocked while all this goes on. The message handler can possibly deal with more requests while the cluster replicates and reaches Majority Quorum. So, instead of blocking, we use a Request Waiting List to track waiting requests and respond to clients when their requests are actually executed before each request is put on the work queue.

When the leader receives the request, it adds a callback to Request Waiting List that will contain the behavior of notifying Bob when the request succeeds or fails ( Figure 2.29 ).

Images

Figure 2.29 Client requests are tracked in request waiting list.

When Jupiter acknowledges the update, the executor notifies the Request Waiting List, which invokes the callback, notifying Bob of the success of the request ( Figure 2.30 ).

Images

Figure 2.30 Request waiting list completing client requests

But what if the leader fails before it sends an acknowledgment back to the client? The client then doesn’t know if the cluster managed to commit the request or if the leader’s failure lost the request. In those circumstances, the client will retry its request, but this leads to a second problem—we don’t want to make the same transfer twice.

To avoid executing a retried request again, each cluster node must be an Idempotent Receiver . (An idempotent operation is one that can be executed multiple times with the same effect as if it were executed once. Adding 1 to a variable isn’t idempotent, but setting a variable to a value is.)

To implement idempotency, each client registers itself with the leader before sending any requests. The client registration is also replicated across all the replicas similar to any other request. The registered client assigns a unique number to each request. The server can then use client ID and unique request number to store the responses of the executed requests. This mapping is looked up when a client repeats a request. Instead of executing the request again, the server returns the stored response. Now, even a non-idempotent request, such as transferring 40 widgets, can be handled in an idempotent way.

In our example, Bob registers itself before starting to send any requests. The registration request is replicated in the Replicated Log and a unique client ID is returned to Bob. Each cluster node maintains a table with entries for client IDs ( Figure 2.31 ).

Images

Figure 2.31 Nodes maintain a client request table for registered clients.

Bob now uses client ID, bob , to send the requests. It also assigns a unique number to each request. Here, it sends request 40-BOS-PNQ with request number 1. Whenever the request is executed, the response is stored in the client table ( Figure 2.32 ).

Images

Figure 2.32 Responses are recorded in the client request table.

Neptune fails before sending the response to Bob. Jupiter and Saturn now run a leader election as discussed in the previous section. Jupiter will execute the pending log entries. Once it executes the request 40-BOS-PNQ from Bob, it makes an entry in the client table. At this point, Bob has not received the response, so he retries 40-BOS-PNQ again, with Jupiter. But because Jupiter has already executed the request numbered 1 from Bob, it will return the response already stored. This way, the retried request from Bob is not executed again ( Figure 2.33 ).

Images

Figure 2.33 Retried requests are detected by the new leader.

Given we are replicating an ordered log, nodes have to maintain the order of the entries when there is no guarantee that they will receive messages in the right order.

Given this, any nodes involved in a Replicated Log like Raft are designed to tolerate out-of-order messages, but this adds overhead and degrades performance. So in practice, nodes maintain a Single-Socket Channel between leader and followers, as shown in Figure 2.34 . ZooKeeper or Apache Kafka are good examples of this implementation.

Images

Figure 2.34 Leader maintains a Single-Socket Channel with follower.

Followers Can Handle Read Requests to Reduce Load on the Leader

Replicating updates to followers has a couple of benefits. One is that it provides a hot backup of the leader, allowing a follower to step in should a problem occur. But the main reason to do this with a cluster is Follower Reads : allowing followers to serve read requests. This reduces load on the leader, enabling it to serve write requests more quickly. This benefit doesn’t come for free: The followers will always lag the state of the leader by the amount of time it takes to propagate the log replication. Most of the time, this won’t present an issue, but it is an issue in one common case. Once Bob has made his update, he’s likely to read the new state. Should his read request go to Saturn, there is a risk that it will beat the replication process and Bob will read stale data ( Figure 2.35 ).

Images

Figure 2.35 Followers can return stale values.

In this situation we want to ensure Bob will read data consistent with what he’s written—a property called read-your-writes consistency ( Figure 2.36 ). A way to obtain this is to use Versioned Value , storing a version number with each stored record. When Neptune writes Bob’s update, it increments the version associated with the data, and returns that version to Bob. When Bob reads data, he supplies that version as part of his request. Saturn can then check the version before responding to a read, if necessary waiting until it’s received that version update.

Images

Figure 2.36 Versions are tracked to ensure read-your-writes consistency.

Distributed databases such as MongoDB and CockroachDB use Hybrid Clock to set a version in the Versioned Value to provide this consistency. Other systems, using Replicated Log , can use High-Water Mark . In Raft followers all need to ensure their High-Water Mark is the same as the leader before replying to requests. In Apache Kafka, messages are produced in a log, which is very similar to a Replicated Log. The log index for produced messages is returned to the client on writes, and the client uses it for subsequent reads. If the read request is handled by a follower, it needs to check that it has that log index, similar to the use of Versioned Value discussed above.

A Large Amount of Data Can Be Partitioned over Multiple Nodes

As discussed in the first chapter, there are physical limits for how much data can be handled on a single node. Beyond that, we will need the data to be split up over multiple nodes. The cluster acts as a single database, with its data separated into partitions (also called shards) on different nodes. Since partitioning is done primarily to work around the physical limitations of a single server, it is important that data is as evenly distributed as possible. As the load on the cluster grows, it is common to add more nodes to the cluster. Here are the key requirements for any partitioning scheme:

  • Data should be evenly distributed across all the cluster nodes.

  • It should be possible to know which cluster node stores a particular data record, without making a request to all the nodes.

  • It should be quick and easy to move part of the data to the new nodes.

Almost all data storages can be described as key-value storages. Clients typically store and access data records by some unique identifiers. With a key-value storage, an easy way to achieve the above requirements is to take a hash of each key and map it to a node. Hash values for keys make sure that data is evenly distributed. If the number of partitions is known, a hash can be mapped to its partition simply by

Click here to view code image

partition = hash_of_key % no. of partitions

While the modulo operation is easy to use, changing the number of partitions causes the partition for every record to change, so that adding just one extra node to an existing cluster requires moving all the data records across the cluster. This is definitely a no-no when we are dealing with large amount of data. Instead, a common pattern is to define logical partitions, with many more logical partitions than there are physical nodes. To find a node for a record, you first find the record’s logical partition, and then look up which node that logical partition is sitting on. The logical partition for a record need never change; if we add a node to the cluster, we reassign some of the logical partitions to it, which only moves the records in those logical partitions.

The most straightforward form of using logical partitions is Fixed Partitions .

For example, Akka suggests you should have ten times as many logical partitions (shards) as the number of nodes. Apache Ignite 15 has a default partition count of 1024. That way, mapping of data records to partitions never changes.

  1. [https://ignite.apache.org/docs/latest](https://ignite.apache.org/docs/latest)

Consider a cluster of three nodes: Jupiter, Saturn, and Neptune. We’ll use six logical partitions, which is not very realistic but makes it easier to show how they work. Now, if Bob is adding widgets to a Pune, he will interact with the cluster via a client library running on the client machine. This client library will initialize itself by getting the mapping of partitions to cluster nodes (usually from a Consistent Core as discussed later). The client library will first find the partition for the key pune by a simple modulo operation.

Click here to view code image

int partition = hash("pune")%6

Then it gets the node hosting that partition and forwards the request to that node. In this case, it will send the request to Saturn ( Figure 2.37 ).

Images

Figure 2.37 Routing requests to fixed partitions with modulo operation

If a new node is added, a few partitions can be moved to the new node to balance the load, without needing to change the key-to-partition mapping. Let’s say a new node, Uranus, is added to the cluster while Saturn is heavily loaded, possibly because the partitions it is hosting have more data. In that case, some partitions from Saturn can be moved to Uranus ( Figure 2.38 ).

Images

Figure 2.38 Partitions moved to new nodes to ensure even distribution

Now, the mapping of keys like "pune" to partition is not changing as the value of hash("pune")%6 will remain the same. The client library will only need to update its partition table. It can do that periodically, or when cluster nodes return an error saying they no longer host the given partition.

While the hash of Fixed Partitions is simple to produce, it can be limiting because databases often need to support range queries, such as finding a list of cities starting with “p” to “q”. If a hash of a key is used for mapping to partitions, a range query may need to access records from all partitions. If such queries are common, Key-Range Partitions are a better approach. Key-Range Partitions use the element of the key that appears in common ranges as part of the partition selection algorithm. A simple, indeed naive, example would be to define 26 partitions and map the first letter of the key to each partition. This would allow a p-to-q query to access just two partitions. Generally, the ranges will be slightly broader, such as from “p” to “z”.

The client library will have metadata about the partitions, the key ranges, and the nodes where the partitions are hosted. The library uses this data to determine that the p-to-q range is all on partition p3, and only that specific partition is queried by sending a request to Neptune ( Figure 2.39 ).

Images

Figure 2.39 Key-Range Partitions allow range queries.

One of the difficulties with Key-Range Partitions is that key ranges might not be known up front. So most data systems start with a single partition, and only split that partition once it reaches a particular size. So, unlike Fixed Partitions, the mapping from key to partition will change over time. Partition splitting can be performed in a manner that keeps both partitions on the same node. Data movement across nodes happens only if the partitions are eventually relocated to a different node. HBase is a good example of how key-range partitions are implemented; YugabyteDB and CockroachDB also support Key-Range Partitions.

Partitions Can Be Replicated for Resilience

While partitioning helps distribute load across the cluster, we still need to resolve issues caused by failures. If a cluster node fails, all the partitions hosted on that node are unavailable. Replicating a partition is just like replicating unpartitioned data, so we use the same patterns for replication that we discussed earlier, centered around Replicated Log , as shown in Figure 2.40 .

Images

Figure 2.40 Partitions are replicated for resilience.

A typical partitioned cluster can be hundreds or thousands of logical partitions. You don’t want too much replication, because the more replicas there are, the larger the Majority Quorum will be, and thus the slower the response to updates. Three or five replicas strikes a good balance between failure tolerance and performance.

A Minimum of Two Phases Are Needed to Maintain Consistency across Partitions

Introducing partitions adds further complexity to maintaining consistency when operations span across multiple partitions. Consider Alice’s desire to move 30 widgets from Boston to London. If Boston and London are on different partitions, we have to maintain consistency not just between multiple replicas of the same data, but also between the different partitions. The Replicated Log handles the problem for replicas, but it doesn’t help us maintain the consistency between partitions. This is a common distributed system problem. For example, Apache Kafka runs into this when messages need to be produced on multiple topics atomically. MongoDB faces this problem when multiple partitions need to be updated atomically.

Consistency across partitions can be solved by using Two-Phase Commit . This nominates one of the nodes as a coordinator ( Figure 2.41 ). Typically the node hosting the partition for the first key of the operation is made the coordinator. Let’s say Jupiter hosts the partition for Boston, and Neptune hosts the partition for London. Since Jupiter holds the partition for Boston, this message is routed to Jupiter, which is declared the coordinator. As a coordinator, Jupiter needs to do all the bookkeeping for the state of the transaction. All the information needs to be persisted on disk to make sure that in the event of a failure, Jupiter knows about all the pending transactions. So it maintains a separate Write-Ahead Log to make this information about the ongoing transaction persistent.

Images

Figure 2.41 Coordinator tracks transaction state.

Jupiter tells itself to prepare to reduce Boston’s widget count. It also sends a message to Neptune to add widgets to London, as shown in Figure 2.42 . However, neither change to the data occurs yet.

Images

Figure 2.42 Nodes track pending requests within a transaction.

Jupiter then coordinates with both nodes, itself and Neptune, to commit the transaction. Both data stores send an accepted message back to the coordinator. Only after both data stores have accepted the transaction, the coordinator commits the transaction and sends an OK back to Alice ( Figure 2.43 ).

Images

Figure 2.43 Transaction commits upon acceptance from all the participants.

This example shows what would happen for nonreplicated partitions, but essentially the same process occurs if they are replicated. The difference is that Jupiter and Neptune would each make the change through a Replicated Log.

Everything we have discussed about various failures is true in this case as well. So, each of the participants in a two-phase commit maintains their own Replicated Log. There is a replicated log maintained for coordinator and for each partition.

In Distributed Systems, Ordering Cannot Depend on System Timestamps

Earlier, we saw that we need to use Versioned Value to ensure a client would read values consistent with what they had written. To make it work, it’s essential to determine the order in which updates occur.

On a single node, it is easy to implement this just by maintaining a single counter and incrementing it every time a modification is done to any record. Sequence number usage in RocksDB 16 is a good example of that. Let’s see how this looks for a single node ( Figure 2.44 ). Alice sends a request to Neptune to reduce 40 widgets from Boston. This creates a new version for Boston with the value of 10. Alice then sends a request to add 40 widgets to London. This creates a new version, with version number 3 for London with the value of 60. Alice then reads the snapshot at version 3. It obviously expects to get Boston’s value to be 10, and gets it as expected.

Images

Figure 2.44 Single node snapshot read—using counter for versions

  1. [https://github.com/cockroachdb/pebble/blob/master/docs/rocksdb.md#internal-keys](https://github.com/cockroachdb/pebble/blob/master/docs/rocksdb.md#internal-keys)

When records are stored across multiple nodes, tracking which records are stored before and after other records becomes tricky. How to increment version numbers to make sure versions across nodes track this before-after relationship?

It is natural to think that system timestamps can be used to version records. Later updates will have higher timestamps, so it will naturally track which records are updated before or after the other. But in practice, this is a big problem because, despite the best efforts of time synchronization tools, different nodes will have slightly different clocks. While these differences are tiny in human terms, they are significant when it comes to computer communications. We have to assume that system timestamps are not monotonic, as discussed in the sidebar “ Wall Clocks Are Not Monotonic ” of the Lease pattern.

To see why this is a problem, let’s say records for Boston and London are stored on nodes Jupiter and Neptune respectively. Jupiter’s clock shows time as 19:25, but Neptune’s clock is lagging behind and shows time as 19:20. Let’s say Boston has 50 widgets at timestamp 19:25 and London has 20 widgets at timestamp 19:20 as per Jupiter’s and Neptune’s clocks respectively. (We’re just using time of day in the example, but the actual timestamp would include the date. It would also be UTC to avoid time zone issues.)

Alice sends a message to reduce 40 widgets from Boston. Assuming the clock has progressed 5 seconds, the new version for Boston is created at timestamp 19:30 as per Jupiter’s clock.

Alice then sends a message to Neptune, to add 40 widgets to London. This creates a new version for London at timestamp 19:25 as per Neptune’s clock. As we can see in Figure 2.45 , even though London’s record on Neptune was updated “after” Boston’s record on Jupiter, it got a lower timestamp.

Images

Figure 2.45 Nodes writing with system timestamp as version

Now, Alice wants to read the “latest” values for Boston and London. Alice’s request is handled by Saturn, which uses its own clock to see what the “latest” timestamp is. If its clock is similar to that of Neptune, it will send read requests to Jupiter and Neptune to read values at timestamp 19:25.

Alice will be puzzled because she will see the latest value for London as 60, but Boston’s value from Jupiter will have the old value, 50 ( Figure 2.46 ).

Images

Figure 2.46 Reading with a system timestamp can return stale values.

We can use a Lamport Clock to track the order of requests across cluster nodes without relying on system timestamps. The trick is to use a simple integer counter per node, but pass it along in requests and responses from and to clients.

Let’s take the same example as above. 40 widgets are moved from Boston to London. Both Jupiter and Neptune maintain a simple integer counter. Every time a record is updated, this counter is incremented. But the counter is also passed to the client, which passes it to next operation it does on another node.

Here, when 40 widgets are removed from Boston, the counter at Jupiter is incremented to 2, and a new version for Boston is created at 2. The counter value 2 is passed to Alice. Alice passes it to Neptune when it sends a request to add 40 widgets to London. The important part here is how the counter is incremented on Neptune. Neptune checks its own counter and the one passed to it in the request. It picks the greater value and then increments it to update its own counter. This makes sure that the new version created for London will have a version number of 3 which is greater than the version number for Boston ( Figure 2.47 ).

Images

Figure 2.47 Lamport clock tracks ordering of writes.

One of the issues with basic Lamport Clock is that versions are tracked by integers with no relation to actual timestamps. For a client to ask for a specific snapshot, it will need to somehow ask for the Lamport timestamp values corresponding to that snapshot. The other, more important issue is that when data on two independent servers is modified by two independent clients, there is no way to order those versions. For example, in the following scenario ( Figure 2.48 ), Bob might have added 20 widgets to London before Alice added 40 widgets to Boston. There is no way to tell that by looking at the logical versions. That is why Lamport Clock is said to be partially ordered.

Images

Figure 2.48 Lamport clock values across servers may not indicate order.

Therefore, most databases need to use timestamps as versions, so that users can query data based on actual timestamps of the node processing their requests. To work around the problem with computer clocks, Hybrid Clock , which combines clock time with a Lamport Clock, is used. When nodes send messages, they include the Hybrid Clock which combines the time of the current server with a Lamport Clock counter. When Neptune receives a message with a timestamp ahead of Neptune’s clock, it increments the integer counter part of the Hybrid Clock which ensures its operations sort later than the received message.

With a Hybrid Clock, Alice sends a message to reduce Boston’s holding and Jupiter records that operation with its system timestamp and a counter (19:30, 0) which it returns to Alice. Alice then passes this on to Neptune with its request to increase London. Neptune sees that Alice’s reported timestamp is (19:30, 0), which is ahead of Neptune’s own clock at 19:25. Therefore, Neptune increments the counter, yielding a hybrid timestamp of (19:30, 1), which it uses for its record and acknowledgment to Alice ( Figure 2.49 ).

Images

Figure 2.49 Hybrid Clock uses system timestamp with a counter.

This solves part of the problem. Even though Neptune’s system clock was lagging, the records stored at Neptune after the one stored on Jupiter will have timestamp which is higher. We still have the problem of partial order to solve. If another client, Bob, tries to read and his request is processed by Saturn, whose clock is lagging same as Neptune at 19:25, he would see the old values for both London and Boston. If Alice and Bob now talk to each other, they will find they are seeing different values for the same data.

To prevent this, we use Clock-Bound Wait , which waits before storing the value long enough for all of the cluster’s nodes’ clocks to advance beyond the one assigned to the records.

Consider the example in the previous section. Let’s say the maximum clock skew across cluster nodes is 5 seconds. Every write operation can wait for 5 seconds before the values are stored ( Figure 2.50 ).

Images

Figure 2.50 Jupiter waits before updating the value.

So when the values at 19:30 are stored on Neptune and Jupiter, every node in the cluster is guaranteed to have their clocks showing time higher than 19:30 ( Figure 2.51 ).

Images

Figure 2.51 Neptune waits before updating the value.

Now, if Bob is trying to read the latest value, and his request is initiated on Saturn which has clock lagging same as Neptune, he is guaranteed to get the latest value for Boston—that is, the value written at timestamp 19:30, as Figure 2.52 demonstrates.

Images

Figure 2.52 Read requests get latest values with Clock-Bound Wait.

With this approach, since every node waits for the maximum clock skew, the request initiating on any cluster node is guaranteed to see the latest values irrespective of their own clock values.

The tricky part of this is knowing how much skew there is across all the clocks in the cluster. If we don’t wait long enough, we won’t get the ordering we need, but if we wait too long, we will reduce the throughput of writes too much. Most open source databases use a technique called as “read restart,” as discussed in the section “ Read Restart ” of the Clock-Bound Wait pattern, to avoid waiting in the write operations.

Databases like MongoDB, YugabyteDB, and CockroachDB use Hybrid Clock. While they can’t rely on the clock machinery to give them exact clock skew across cluster nodes, they use Clock-Bound Wait assuming a configurable maximum clock skew. Google developed TrueTime 17 in its data centers to guarantee that the clock skew is no more than 7 ms. This is used by Google’s Spanner 18 databases. AWS has a library called Clock Bound which has a similar API to give clock skew across cluster nodes; at the time of writing, the AWS library, unlike TrueTime, does not give a guarantee on the upper bound.

A Consistent Core Can Manage the Membership of a Data Cluster

A cluster can have hundreds or thousands of nodes. Such a cluster is also dynamic, allowing nodes to be added to handle increasing load or removed due to failures or reductions in traffic. We see large clusters regularly with Apache Kafka or Kubernetes clusters and with databases like MongoDB, Cassandra, CockroachDB, or YugabyteDB. To manage such a cluster, we need to keep track of which nodes are part of the cluster. With partitioned data, we have to track the mapping of keys to logical partitions and partitions to nodes. It’s important that this management is done in a fault-tolerant way, so that failure of one control node doesn’t bring down the whole cluster. Management data also needs strong consistency, otherwise we risk corruption of our data.

As we’ve seen earlier, Replicated Log is an excellent way to achieve this. But a Replicated Log depends on Majority Quorum , which cannot scale to thousands of replicas. Therefore the management of a large cluster is given to a Consistent Core —a small set of nodes whose responsibility is to manage a larger data cluster. The Consistent Core tracks the data cluster membership with Lease and State Watch ( Figure 2.53 ).

  1. [https://cloud.google.com/spanner/docs/true-time-external-consistency](https://cloud.google.com/spanner/docs/true-time-external-consistency)

  2. [https://cloud.google.com/spanner](https://cloud.google.com/spanner)

Images

Figure 2.53 Consistent Core tracks cluster membership.

This requirement is so common in distributed services that some products include the necessary generic functionalities to utilize a Consistent Core, which includes patterns like Lease and State Watch. Examples of such products are Apache ZooKeeper and etcd, which are often utilized as Consistent Core components.

One use of Lease is for node registration and failure detection of cluster nodes. The ephemeral node implementation in Apache ZooKeeper or the lease functionality in etcd are examples of this. Here, Jupiter, a data cluster node, registers with the Consistent Core with its unique ID or name. The node entries are tracked as leases and renewed with periodic HeartBeat ( Figure 2.54 ).

Images

Figure 2.54 Consistent Core tracks Lease.

The leader of the Consistent Core periodically checks leases which are not refreshed. If Jupiter crashes and stops sending HeartBeat, its lease will be removed ( Figure 2.55 ).

Images

Figure 2.55 Lease expires if not renewed.

Leases are replicated, so if a leader fails, the new leader of the Consistent Core will start tracking the leases. Jupiter then needs to connect with the new leader and keep sending the heartbeats.

When a generic Consistent Core like Apache ZooKeeper or etcd is used, a dedicated cluster node, called a cluster controller , uses information stored in etcd or ZooKeeper to take decisions on behalf of the cluster. Apache Kafka’s controller [ Rao2014 ] is a good example of this. Other nodes need to know when this particular node is down so that someone else can take this responsibility. To do this, the data cluster node registers a State Watch with the Consistent Core. The Consistent Core notifies all the interested nodes when a particular node fails.

Let’s say Jupiter plays the role of cluster controller. Neptune wants to know when Jupiter’s lease expires. It registers its interest with the Consistent Core by contacting the core’s leader. When the lease for Jupiter expires, indicating that Jupiter is probably no longer up and running, the leader of the consistent core checks to see if any nodes need to be notified. In this case, Neptune is notified with a “lease-deleted” event ( Figure 2.56 ).

Images

Figure 2.56 Nodes watch cluster state changes using Consistent Core.

Replication messages from leader to followers of the Consistent Core are not shown in the diagram.

It’s important that Neptune receives all its events in the correct order. While the communication protocol can sort all that out, it is usually more efficient for Neptune to connect to the Consistent Core with a Single-Socket Channel .

Apache ZooKeeper and etcd are examples of generic frameworks used by products like Apache Kafka or Kubernetes. Often, it is convenient for clustered software to have their own implementation based on Replicated Log and to do decision making in the Consistent Core itself. Quorum based controller [ McCabe2021 ] for Apache Kafka, the primary cluster of MongoDB, and the master cluster of YugabyteDB are examples of these.

An example of this is when a Consistent Core assigns Fixed Partitions to the cluster nodes. Three nodes, Jupiter, Neptune, and Saturn, register with the consistent core. Once the registration is done, the consistent core maps partitions evenly across the cluster nodes ( Figure 2.57 ).

Images

Figure 2.57 Consistent Core assigns partitions to cluster nodes.

Gossip Dissemination for Decentralized Cluster Management

Some systems, such as Cassandra, lean more towards eventual consistency, and do not want to rely on a centralized Consistent Core . They tolerate some inconsistency in the cluster metadata provided it converges quickly. Metadata, such as the total number of nodes, their network addresses, partitions they host, and so on, still needs to be propagated somehow to everyone. (As we write this, however, there is a proposal to migrate Cassandra to a Consistent Core.)

As discussed in the previous section, there can be thousands of nodes in a cluster. Each node has some information and needs to make sure it reaches every other node. It will incur too much communication overhead if every node talks to every other node. Gossip Dissemination is an interesting way out. At regular intervals, each node picks another node at random and sends it the information it has on the state of the cluster. This style of communication has a nice property. In a cluster with n nodes, this information reaches every node in time proportional to log(n) . Interestingly, this matches how epidemics spread in large communities. The mathematical branch of epidemiology studies how an epidemic or rumors spread in a society. A disease spreads very quickly even if each person comes into contact with only a few individuals at random. An entire population can become infected from very few interactions. Gossip Dissemination is based on these mathematical models. If nodes send information to a few other nodes regularly, even a large cluster will get that information quickly.

Say, we have eight servers, each having information about a color of the planet they are named after ( Figure 2.58 ). We want all these servers to know every color.

Images

Figure 2.58 An example cluster. Each node maintains a color.

To start with, Mercury sends a gossip message to Venus ( Figure 2.59 ).

Images

Figure 2.59 Mercury sending gossip message to Venus

Then Venus sends gossip message to Neptune. It includes everything it has in the gossip message ( Figure 2.60 ).

Images

Figure 2.60 Venus sending gossip message to Neptune

Meanwhile Jupiter sends gossip message to Mars ( Figure 2.61 ).

Images

Figure 2.61 Jupiter sending gossip message to Mars

Uranus gossips to Earth ( Figure 2.62 ).

Images

Figure 2.62 Uranus gossips to Earth.

Earth gossips to Mars ( Figure 2.63 ).

Images

Figure 2.63 Earth gossips to Mars.

When Neptune gossips with Mars, Mars will have colors for Mercury, Venus, Neptune, Earth, Jupiter, and Mars ( Figure 2.64 ).

Images

Figure 2.64 Neptune gossips to Mars.

This happens at regular intervals at each node. Eventually, and rather quickly, all nodes get the same information. HashiCorp Consul 19 has a very nice convergence simulator 20 which shows how quickly information converges with its gossip implementation.

  1. [https://www.consul.io](https://www.consul.io)

  2. [https://www.serf.io/docs/internals/simulator.html](https://www.serf.io/docs/internals/simulator.html)

How is this technique used in real life? One common use is to manage group membership in products like Cassandra. Let’s say there is a large cluster of 100 nodes. We need all the nodes to know about each other. The cluster nodes can achieve this by doing a repeated communication, each time with a random node.

To start with, there is at least one special node, which needs to be known to every node. This node is called the seed node. It can either be configured, or there can be a mechanism to know the seed node at startup. The seed node is just one of the nodes in the cluster—it does not implement any special functionality. It only needs to be known to everyone else.

Every node starts by communicating with the seed node and sending its own address to it. The seed node, like any other node, has a scheduled task to repeatedly send what it knows about others to a randomly selected node.

For example, suppose Neptune is the seed node. When Jupiter starts, it sends its own address to Neptune ( Figure 2.65 ).

Images

Figure 2.65 Jupiter gossips to Neptune.

Then, Saturn starts and sends its own address to Neptune the same way ( Figure 2.66 ).

Images

Figure 2.66 Saturn gossips to Neptune.

All of Jupiter, Saturn, and Neptune repeatedly pick a random node and send it all the information they have. So in a while, Neptune picks up Jupiter and sends it information that it has. Now both Neptune and Jupiter know about Saturn ( Figure 2.67 ).

Images

Figure 2.67 Neptune gossips to Jupiter.

In the next cycle, either Jupiter or Neptune might pick up Saturn and send it all the information they have. Now, Saturn will know about Jupiter ( Figure 2.68 ). At this point, all three nodes know about each other Figure 2.69 ).

Images

Figure 2.68 Jupiter gossips to Saturn.

Images

Figure 2.69 All nodes know about each other.

Gossip Dissemination is a commonly used technique for information dissemination in large clusters. Products like Cassandra, Akka, or Consul use it for managing group membership information in large clusters.

One major limitation of gossip protocols is that they only provide eventual consistency. When stronger consistency is needed, a Consistent Core implementation is preferred. For example, Cassandra moved from gossip protocol to a smaller consistent core [ Tunnicliffe2023 ] to maintain its metadata.

Some systems, like Akka, designate a single cluster node to act as a cluster coordinator without running an explicit leader election. Similar to Consistent Core, an Emergent Leader takes decisions on behalf of the cluster. A common technique is for the nodes to be ordered based on their age in the cluster. The node with the highest age is designated a leader of the cluster to take decisions. Since no explicit election is run, there can be inconsistencies caused by problems like split brain as discussed in the section “ Split Brain ” of the Emergent Leader pattern.