github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/website/content/docs/concepts/consensus.mdx (about)

     1  ---
     2  layout: docs
     3  page_title: Consensus Protocol
     4  description: |-
     5    Nomad uses a consensus protocol to provide Consistency as defined by CAP.
     6    The consensus protocol is based on Raft: In search of an Understandable
     7    Consensus Algorithm. For a visual explanation of Raft, see The Secret Lives of
     8    Data.
     9  ---
    10  
    11  # Consensus Protocol
    12  
    13  Nomad uses a [consensus protocol](<https://en.wikipedia.org/wiki/Consensus_(computer_science)>)
    14  to provide [Consistency (as defined by CAP)](https://en.wikipedia.org/wiki/CAP_theorem).
    15  The consensus protocol is based on
    16  ["Raft: In search of an Understandable Consensus Algorithm"](https://raft.github.io/raft.pdf).
    17  For a visual explanation of Raft, see [The Secret Lives of Data](http://thesecretlivesofdata.com/raft).
    18  
    19  ~> **Advanced Topic!** This page covers technical details of
    20  the internals of Nomad. You do not need to know these details to effectively
    21  operate and use Nomad. These details are documented here for those who wish
    22  to learn about them without having to go spelunking through the source code.
    23  
    24  ## Raft Protocol Overview
    25  
    26  Raft is a consensus algorithm that is based on
    27  [Paxos](https://en.wikipedia.org/wiki/Paxos_%28computer_science%29). Compared
    28  to Paxos, Raft is designed to have fewer states and a simpler, more
    29  understandable algorithm.
    30  
    31  There are a few key terms to know when discussing Raft:
    32  
    33  - **Log** - The primary unit of work in a Raft system is a log entry. The problem
    34    of consistency can be decomposed into a _replicated log_. A log is an ordered
    35    sequence of entries. We consider the log consistent if all members agree on
    36    the entries and their order.
    37  
    38  - **FSM** - [Finite State Machine](https://en.wikipedia.org/wiki/Finite-state_machine).
    39    An FSM is a collection of finite states with transitions between them. As new logs
    40    are applied, the FSM is allowed to transition between states. Application of the
    41    same sequence of logs must result in the same state, meaning behavior must be deterministic.
    42  
    43  - **Peer set** - The peer set is the set of all members participating in log replication.
    44    For Nomad's purposes, all server nodes are in the peer set of the local region.
    45  
    46  - **Quorum** - A quorum is a majority of members from a peer set: for a set of size `n`,
    47    quorum requires at least `⌊(n/2)+1⌋` members.
    48    For example, if there are 5 members in the peer set, we would need 3 nodes
    49    to form a quorum. If a quorum of nodes is unavailable for any reason, the
    50    cluster becomes _unavailable_ and no new logs can be committed.
    51  
    52  - **Committed Entry** - An entry is considered _committed_ when it is durably stored
    53    on a quorum of nodes. Once an entry is committed it can be applied.
    54  
    55  - **Leader** - At any given time, the peer set elects a single node to be the leader.
    56    The leader is responsible for ingesting new log entries, replicating to followers,
    57    and managing when an entry is considered committed.
    58  
    59  Raft is a complex protocol and will not be covered here in detail (for those who
    60  desire a more comprehensive treatment, the full specification is available in this
    61  [paper](https://raft.github.io/raft.pdf)).
    62  We will, however, attempt to provide a high level description which may be useful
    63  for building a mental model.
    64  
    65  Raft nodes are always in one of three states: follower, candidate, or leader. All
    66  nodes initially start out as a follower. In this state, nodes can accept log entries
    67  from a leader and cast votes. If no entries are received for some time, nodes
    68  self-promote to the candidate state. In the candidate state, nodes request votes from
    69  their peers. If a candidate receives a quorum of votes, then it is promoted to a leader.
    70  The leader must accept new log entries and replicate to all the other followers.
    71  In addition, if stale reads are not acceptable, all queries must also be performed on
    72  the leader.
    73  
    74  Once a cluster has a leader, it is able to accept new log entries. A client can
    75  request that a leader append a new log entry (from Raft's perspective, a log entry
    76  is an opaque binary blob). The leader then writes the entry to durable storage and
    77  attempts to replicate to a quorum of followers. Once the log entry is considered
    78  _committed_, it can be _applied_ to a finite state machine. The finite state machine
    79  is application specific; in Nomad's case, we use
    80  [MemDB](https://github.com/hashicorp/go-memdb) to maintain cluster state.
    81  
    82  Obviously, it would be undesirable to allow a replicated log to grow in an unbounded
    83  fashion. Raft provides a mechanism by which the current state is snapshotted and the
    84  log is compacted. Because of the FSM abstraction, restoring the state of the FSM must
    85  result in the same state as a replay of old logs. This allows Raft to capture the FSM
    86  state at a point in time and then remove all the logs that were used to reach that
    87  state. This is performed automatically without user intervention and prevents unbounded
    88  disk usage while also minimizing time spent replaying logs. One of the advantages of
    89  using MemDB is that it allows Nomad to continue accepting new transactions even while
    90  old state is being snapshotted, preventing any availability issues.
    91  
    92  Consensus is fault-tolerant up to the point where quorum is available.
    93  If a quorum of nodes is unavailable, it is impossible to process log entries or reason
    94  about peer membership. For example, suppose there are only 2 peers: A and B. The quorum
    95  size is also 2, meaning both nodes must agree to commit a log entry. If either A or B
    96  fails, it is now impossible to reach quorum. This means the cluster is unable to add
    97  or remove a node or to commit any additional log entries. This results in
    98  _unavailability_. At this point, manual intervention would be required to remove
    99  either A or B and to restart the remaining node in bootstrap mode.
   100  
   101  A Raft cluster of 3 nodes can tolerate a single node failure while a cluster
   102  of 5 can tolerate 2 node failures. The recommended configuration is to either
   103  run 3 or 5 Nomad servers per region. This maximizes availability without
   104  greatly sacrificing performance. The [deployment table](#deployment_table) below
   105  summarizes the potential cluster size options and the fault tolerance of each.
   106  
   107  In terms of performance, Raft is comparable to Paxos. Assuming stable leadership,
   108  committing a log entry requires a single round trip to half of the cluster.
   109  Thus, performance is bound by disk I/O and network latency.
   110  
   111  ## Raft in Nomad
   112  
   113  Only Nomad server nodes participate in Raft and are part of the peer set. All
   114  client nodes forward requests to servers. The clients in Nomad only need to know
   115  about their allocations and query that information from the servers, while the
   116  servers need to maintain the global state of the cluster.
   117  
   118  Since all servers participate as part of the peer set, they all know the current
   119  leader. When an RPC request arrives at a non-leader server, the request is
   120  forwarded to the leader. If the RPC is a _query_ type, meaning it is read-only,
   121  the leader generates the result based on the current state of the FSM. If
   122  the RPC is a _transaction_ type, meaning it modifies state, the leader
   123  generates a new log entry and applies it using Raft. Once the log entry is committed
   124  and applied to the FSM, the transaction is complete.
   125  
   126  Because of the nature of Raft's replication, performance is sensitive to network
   127  latency. For this reason, each region elects an independent leader and maintains
   128  a disjoint peer set. Data is partitioned by region, so each leader is responsible
   129  only for data in their region. When a request is received for a remote region,
   130  the request is forwarded to the correct leader. This design allows for lower latency
   131  transactions and higher availability without sacrificing consistency.
   132  
   133  ## Consistency Modes
   134  
   135  Although all writes to the replicated log go through Raft, reads are more
   136  flexible. To support various trade-offs that developers may want, Nomad
   137  supports 2 different consistency modes for reads.
   138  
   139  The two read modes are:
   140  
   141  - `default` - Raft makes use of leader leasing, providing a time window
   142    in which the leader assumes its role is stable. However, if a leader
   143    is partitioned from the remaining peers, a new leader may be elected
   144    while the old leader is holding the lease. This means there are 2 leader
   145    nodes. There is no risk of a split-brain since the old leader will be
   146    unable to commit new logs. However, if the old leader services any reads,
   147    the values are potentially stale. The default consistency mode relies only
   148    on leader leasing, exposing clients to potentially stale values. We make
   149    this trade-off because reads are fast, usually strongly consistent, and
   150    only stale in a hard-to-trigger situation. The time window of stale reads
   151    is also bounded since the leader will step down due to the partition.
   152  
   153  - `stale` - This mode allows any server to service the read regardless of if
   154    it is the leader. This means reads can be arbitrarily stale but are generally
   155    within 50 milliseconds of the leader. The trade-off is very fast and scalable
   156    reads but with stale values. This mode allows reads without a leader meaning
   157    a cluster that is unavailable will still be able to respond.
   158  
   159  ## Deployment Table ((#deployment_table))
   160  
   161  Below is a table that shows quorum size and failure tolerance for various
   162  cluster sizes. The recommended deployment is either 3 or 5 servers. A single
   163  server deployment is _**highly**_ discouraged as data loss is inevitable in a
   164  failure scenario.
   165  
   166  <table>
   167    <thead>
   168      <tr>
   169        <th>Servers</th>
   170        <th>Quorum Size</th>
   171        <th>Failure Tolerance</th>
   172      </tr>
   173    </thead>
   174    <tbody>
   175      <tr>
   176        <td>1</td>
   177        <td>1</td>
   178        <td>0</td>
   179      </tr>
   180      <tr>
   181        <td>2</td>
   182        <td>2</td>
   183        <td>0</td>
   184      </tr>
   185      <tr class="warning">
   186        <td>3</td>
   187        <td>2</td>
   188        <td>1</td>
   189      </tr>
   190      <tr>
   191        <td>4</td>
   192        <td>3</td>
   193        <td>1</td>
   194      </tr>
   195      <tr class="warning">
   196        <td>5</td>
   197        <td>3</td>
   198        <td>2</td>
   199      </tr>
   200      <tr>
   201        <td>6</td>
   202        <td>4</td>
   203        <td>2</td>
   204      </tr>
   205      <tr>
   206        <td>7</td>
   207        <td>4</td>
   208        <td>3</td>
   209      </tr>
   210    </tbody>
   211  </table>