Advertisements
Skip to content

paxos, a revelation of distributed consensus when scaling a distributed architecture

paxos

The work that I mainly do in real life is focused on architecting systems and platforms and this has to do a lot with DevOps. I don’t know if this is a good or a bad thing but nevertheless, this is how I spend my days. In today’s environment, that means that I’ve spent a lot of time working on tools that, in one way or another, help other developers deal with distributed systems. In that work, I’ve noticed that there are some really key things that straddle the line between pure math and pure engineering. That’s really interesting to someone like me!
A good example of that is something called paxos. My first exposure to paxos was very interesting. I read the (only) book in Site Reliability Engineering (SRE) and I was exposed to a variety of different concepts that have to do with scaling distributed systems, availability, consistency and more. Paxos was one of the outcomes of this book that I really didn’t expect to learn, but I was amazed by.
Paxos is a system for managing consensus.
In distributed systems, there a collection of hard problems that you constantly need to deal with.
  1. Things fail. You can never count on anything being reliable. Even if you have a perfectly bug-free software, and hardware that never breaks, you’ve still got to deal with the fact that network connections can break, or messages within a network can get lost, or that some bozo might sever your network connection with a bulldozer. (That really happened while I was at Google!)
  2. Given (1), you can never rely on one copy of anything, because that copy might become unavailable due to a failure. So you need to keep multiple copies, and those copies need to be consistent – meaning that at any time, all of the copies agree about their contents.
  3. There’s no way to maintain a single completely consistent view of time between multiple computers. Due to inconsistencies in individual machine performance, and variable network delays, variable storage latency, and several other factors, there’s no canonical way of saying that for two events X and Y, “X happened before Y”. What that means is that when you try to maintain a consistent set of data, you can’t just say “Run all of the events in order”, because while one server maintaining one copy might “know” that X happened before Y, another server maintaining another copy might be just as certain that Y happened before X.
In a world where you can’t count on different agents seeing events in the same order, and where you expect things to be constantly failing, how can you make sure that any distributed system you build ends up with a consistent view of reality?
The answer is a consensus protocol. You need to create a mechanism based on communication between the copies of your system that allows them to maintain a consistent consensus of what the current state of the world is, even in the presence of failures of machines, storage systems, and communications.
paxos is a very elegant, reasonably simple consensus protocol.

Let’s get a bit more precise. Paxos is built on a model of storage. The original application of it was a consistent database, so it’s built around the idea of keeping data consistent. In paxos, the state of the storage is modeled as a sequence of transactions. Each transaction is a pair(t, v), where t is a numeric transaction identifier, and a v is a transaction value.
The state of the system being modeled is a sequence of transaction pairs,[(ti, vi), (tj, vj), ..], where the values are increasing as you progress through the sequence. As time passes, new transaction pairs can be added to the state.
The focus of the paxos protocol is ensuring that in a collection of2n+1participants, all surviving participants will agree on the current value of the state, even if up to participants fail, and even if messages can be delivered in arbitrary order.
Before I go further into the description of paxos, we need to look at the basic assumptions that underlie it. Like any formal model, it’s not defined in terms of real computers. It’s defined in terms of an abstraction that approximates reality. In this case, the approximation is quite good, but we still need to go through the basic assumptions that make up its model of the universe.
  1. Processors (aka participants, servers, computers):
    1. operate at any speed. No two processors necessarily operate at the same speed.
    2. may fail without warning.
    3. may rejoin after recovering from a failure.
    4. are cooperative (in the sense that they do not attempt to cause failures).
  2. Network:
    1. Delivers messages between any pair of processors.
    2. Transmits messages asynchronously.
    3. Delivers messages at arbitrary speeds.
    4. Does not guarantee that messages will be delivered in the order in which they were transmitted.
    5. Does guarantee that a message, if delivered, will be delivered correctly, without any changes.
    6. May fail to deliver a message.
    7. May deliver multiple copies of the same message.
In short, everything can fail at any time; after failure, participants can recover and rejoin the system; and no part of the system acts in an actively adversarial way.
The protocol describes the behavior of the system in terms of a collection of roles. A participant can have more than one role in the system – in fact, in most implementations of paxos, all partipants do have multiple roles. The roles are:
Client
The client is not part of the paxos cluster. It’s an external entity whose actions trigger state changes by makingrequeststo the paxos system. Each state update in paxos is initiated by a client request, and completed by a reply to the client.
Acceptor
An acceptor (also called a voter) is a participant in the maintanence of distributed storage. A state change in a paxos cluster does not occur until a majority (quorum) of acceptors agree upon it.
Proposer
A proposer recieves a request from the client, and attempts to get a quorum of acceptors to agree on it.
Leader
One of the proposers is special. It is the single proposer who most recently had a proposal accepted. In many paxos implementations, there is only one active proposer serving client requests: the only time the other proposers send proposals is when the current leader fails, and a new one needs to be selected.
Learner
The learner is the real service provided by the paxos cluster. Once a proposal is accepted, alearnerprocesses the request from the client, and sends it the result.
In a typical paxos cluster, the client sends requests to a proposer. The proposer sends a proposal to update the state with the new client request and attempts to convince a majority of the acceptors to accept it. Once a majority accepts it, the client request is processed by the learner, and a result is returned to the client.
The meat of paxos the protocol that the proposer gets a majority of acceptors to agree on a proposal, and how that protocol process ensures that the collection of acceptors maintains a consistent state.

The protocol itself is pretty simple. Each round is effectively independent and consists of a process of attempting to reach consensus. Within each round, finding consensus is a two-phase process, where each phase consists of a message sent from a proposer to a group of acceptors, and a reply from the acceptors to the proposer.
  1. Phase One: Prepare/Promise
    • Proposer: A proposer attempts to start setting a new consensus by sending a Prepare(N) message to a quorum of acceptors. It can send to any group of acceptors, so long as that group forms a majority of the acceptors. The prepare message specifies a numeric identifier N for its proposal, which is larger than any proposal that’s been sent by this proposer.
    • Acceptors:
      Each acceptor, upon receiving the proposal, checks if the N-value from the prepare message is greater than any proposal from the current round that it has accepted. If so, it sends a reply called a Promise to the proposer, promising that it will never accept any proposal with a number less than N. If the acceptor has accepted a proposal with number less than in the current round, then it includes the pair consisting of the proposed consensus value and the number of the accepted proposal that proposed .

      The acceptor thus sends a message Promise(N, (v, nv)) (if it has accepted a proposal this round) or Promise(N, null) (if it has not yet accepted a proposal with a number less than N).

      Once it’s sent a promising message, it must not accept any request for a proposal with number less than N. Note though that this does not mean that the acceptor promises to accept the proposal: all it’s doing is promising not to accept any proposal with number less than N! If in receives a message Prepare(N+1), it’s free to promise that – but if it does, it will no longer be able to accept the proposal for N.

      (If N is smaller than the number of any proposal promised or accepted by the acceptor, then in the original version of Paxos, the acceptor does nothing; in some optimizations of the protocol, it replies Reject(nv).)

  2. What this phase does is allow a proposer to determine whether or not a new proposal is even worth considering. If a quorum (majority) of acceptors send promises, then it can move on to phase 2.
  3. Phase Two: Accept!/Accepted
    When a proposer receives promises from a quorum of acceptors, then it moves forward to try to actually commit the proposal. In order to do this, it needs to choose a value for the proposal. If any of the Promise messages contained a value, then the value of this proposal must be set to the value of the highest proposal number in any of the promises. If all of the promises were empty, then the proposer can choose any value that it wants for the proposal.Once the proposer has chosen a value, then it sends a message Accept!(N, V) to a quorum of acceptors. This is typically written with the exclamation point because it’s really a command to the acceptors: they’re being told to accept the proposal if they can.When an acceptor receives an Accept!(N, v) message, if it has not issued a promise for a proposal with a number greater than N, then it must accept the message. It accepts the proposal by sending a message Accepted(N, V) to both the original proposer and all of the learners.When Accepted messages have been received from a quorum of acceptors, the new value V becomes the consensus value for the Paxos cluster, and the new proposal number N is fully committed.
As with so many things, this is easier to understand when you think about an example. One use of Paxos that I’ve worked with is in a cluster scheduling service. In that system:
  • a client is a user attempting to run a new job on the cluster. It sends a request to the scheduler detailing the set of resources that it wants to request.
  • Each duplicate of the scheduler is a proposer, an acceptor, and a learner. There’s one active instance of the scheduler, which is the leader. When a client wants to schedule a job, its request gets sent to the leading scheduler.
  • In the normal non-error case, this works as follows:
    1. When a scheduling request is received, the leader proposes scheduling the job, by sending a message to all of the other schedulers saying that it wants to schedule job N.
    2. The other schedulers, if they haven’t seen a proposal for a job with a number greater than I, make promises to accept that proposal.
    3. The leading scheduler chooses resources for the job, and then sends an Accept! message to the other schedulers.
    4. The other schedulers reply accepting the scheduling. The non-leader schedulers, acting as learnings, record the scheduling information, and the leader actually starts the job.
  • Errors occur when there was some kind of failure. In that case, we don’t necessarily know who the leader is – so we get multiple schedulers trying to act as if they’re the leader. So they each send proposals. Whichever proposal had the largest proposal number will eventually get accepted, and its proposer becomes the new leader.

It’s a pretty simple thing – the core concept is simply that no consensus proposal is considered “committed” until it’s been accepted by a majority of the participants. And if it’s been accepted by a majority of the participants, that means that no conflicting proposal can ever reach consensus – because that would require at least one participant to accept 2 conflicting proposals.

But there’s still a bit of formality that’s working looking at. Exactly what guarantees does paxos give? What properties does paxos-style consensus have?
Even the formal properties of paxos are easy to understand. Paxos provides two key properties: validity, and agreement.
Validity
No value ever reaches consensus without first being proposed, and having its proposal accepted.
Agreement
No two distinct values ever reach consensus at the same time.
You can easily prove those two properties. In fact, the proof is completely obvious once you recognize that the paxos protocol has two invariants (and those invariants are themselves clear from the definition of the protocol!):
  1. An acceptor can only accept a proposal P if and only if it has not yet made a promise
    for a proposal where n>=P is the consensus value of the
    highest numbered proposal that has been accepted before this proposal.
Getting back to the beginning: the point of all of this is to have a system in which we can be sure that things work correctly even in the presence of failures. In paxos, as long as at some point there was a quorum of machines that come to an agreement, then any failure that leaves a surviving quorum of machines must have overlapped with the previous quorum – which means that the previous consensus still remains in effect, and will be propagated to the remaining participants. If you’ve got 5 machines, then two can fail, and you won’t lose consistency among the remaining ones.

Python Libraries

Some simple python implementations that I would like to point here as references to anyone interested in the nuts and bolts of the underlying engineering are listed below.

Obviously it is even better to display some code when necessary. I strongly believe that the following interfaces of python are self-explanatory.

<br />
'''<br />
This module provides an implementation of the Paxos algorithm as<br />
a set of composable classes.<br />
The code is available:<br />
https://raw.githubusercontent.com/cocagne/python-composable-paxos/master/composable_paxos.py<br />
'''</p>
<p>import collections</p>
<p># ProposalID<br />
#<br />
# In order for the Paxos algorithm to function, all proposal ids must be<br />
# unique. A simple way to ensure this is to include the proposer's unique<br />
# id in the proposal id.<br />
#<br />
# Python tuples allow the proposal number and the UID to be combined in a<br />
# manner that supports comparison in the expected manner:<br />
#<br />
# (4,'C') &gt; (4,'B') &gt; (3,'Z')<br />
#<br />
# Named tuples from the collections module support all of the regular<br />
# tuple operations but additionally allow access to the contents by<br />
# name so the numeric component of the proposal ID may be referred to<br />
# via 'proposal_id.number' instead of 'proposal_id[0]'.<br />
#<br />
ProposalID = collections.namedtuple('ProposalID', ['number', 'uid'])</p>
<p>class PaxosMessage (object):<br />
'''<br />
Base class for all messages defined in this module<br />
'''<br />
from_uid = None # Set by subclass constructor</p>
<p>class Prepare (PaxosMessage):<br />
'''<br />
Prepare messages should be broadcast to all Acceptors.<br />
'''<br />
def __init__(self, from_uid, proposal_id):<br />
self.from_uid = from_uid<br />
self.proposal_id = proposal_id</p>
<p>class Nack (PaxosMessage):<br />
'''<br />
NACKs are technically optional though few practical applications will<br />
want to omit their use. They are used to signal a proposer that their<br />
current proposal number is out of date and that a new one should be<br />
chosen. NACKs may be sent in response to both Prepare and Accept<br />
messages<br />
'''<br />
def __init__(self, from_uid, proposer_uid, proposal_id, promised_proposal_id):<br />
self.from_uid = from_uid<br />
self.proposal_id = proposal_id<br />
self.proposer_uid = proposer_uid<br />
self.promised_proposal_id = promised_proposal_id</p>
<p>class Promise (PaxosMessage):<br />
'''<br />
Promise messages should be sent to at least the Proposer specified in<br />
the proposer_uid field<br />
'''<br />
def __init__(self, from_uid, proposer_uid, proposal_id, last_accepted_id, last_accepted_value):<br />
self.from_uid = from_uid<br />
self.proposer_uid = proposer_uid<br />
self.proposal_id = proposal_id<br />
self.last_accepted_id = last_accepted_id<br />
self.last_accepted_value = last_accepted_value</p>
<p>class Accept (PaxosMessage):<br />
'''<br />
Accept messages should be broadcast to all Acceptors<br />
'''<br />
def __init__(self, from_uid, proposal_id, proposal_value):<br />
self.from_uid = from_uid<br />
self.proposal_id = proposal_id<br />
self.proposal_value = proposal_value</p>
<p>class Accepted (PaxosMessage):<br />
'''<br />
Accepted messages should be sent to all Learners<br />
'''<br />
def __init__(self, from_uid, proposal_id, proposal_value):<br />
self.from_uid = from_uid<br />
self.proposal_id = proposal_id<br />
self.proposal_value = proposal_value</p>
<p>class Resolution (PaxosMessage):<br />
'''<br />
Optional message used to indicate that the final value has been selected<br />
'''<br />
def __init__(self, from_uid, value):<br />
self.from_uid = from_uid<br />
self.value = value</p>
<p>class InvalidMessageError (Exception):<br />
'''<br />
Thrown if a PaxosMessage subclass is passed to a class that does not<br />
support it<br />
'''</p>
<p>class MessageHandler (object):</p>
<p>def receive(self, msg):<br />
'''<br />
Message dispatching function. This function accepts any PaxosMessage subclass and calls<br />
the appropriate handler function<br />
'''<br />
handler = getattr(self, 'receive_' + msg.__class__.__name__.lower(), None)<br />
if handler is None:<br />
raise InvalidMessageError('Receiving class does not support messages of type: ' + msg.__class__.__name__)<br />
return handler( msg )</p>
<p>class Proposer (MessageHandler):<br />
'''<br />
The 'leader' attribute is a boolean value indicating the Proposer's<br />
belief in whether or not it is the current leader. This is not a reliable<br />
value as multiple nodes may simultaneously believe themselves to be the<br />
leader.<br />
'''</p>
<p>leader = False<br />
proposed_value = None<br />
proposal_id = None<br />
highest_accepted_id = None<br />
promises_received = None<br />
nacks_received = None<br />
current_prepare_msg = None<br />
current_accept_msg = None</p>
<p>def __init__(self, network_uid, quorum_size):<br />
self.network_uid = network_uid<br />
self.quorum_size = quorum_size<br />
self.proposal_id = ProposalID(0, network_uid)<br />
self.highest_proposal_id = ProposalID(0, network_uid)</p>
<p>def propose_value(self, value):<br />
'''<br />
Sets the proposal value for this node iff this node is not already aware of<br />
a previous proposal value. If the node additionally believes itself to be<br />
the current leader, an Accept message will be returned<br />
'''<br />
if self.proposed_value is None:<br />
self.proposed_value = value</p>
<p>if self.leader:<br />
self.current_accept_msg = Accept(self.network_uid, self.proposal_id, value)<br />
return self.current_accept_msg</p>
<p>def prepare(self):<br />
'''<br />
Returns a new Prepare message with a proposal id higher than<br />
that of any observed proposals. A side effect of this method is<br />
to clear the leader flag if it is currently set.<br />
'''</p>
<p>self.leader = False<br />
self.promises_received = set()<br />
self.nacks_received = set()<br />
self.proposal_id = ProposalID(self.highest_proposal_id.number + 1, self.network_uid)<br />
self.highest_proposal_id = self.proposal_id<br />
self.current_prepare_msg = Prepare(self.network_uid, self.proposal_id)</p>
<p>return self.current_prepare_msg</p>
<p>def observe_proposal(self, proposal_id):<br />
'''<br />
Optional method used to update the proposal counter as proposals are<br />
seen on the network. When co-located with Acceptors and/or Learners,<br />
this method may be used to avoid a message delay when attempting to<br />
assume leadership (guaranteed NACK if the proposal number is too low).<br />
This method is automatically called for all received Promise and Nack<br />
messages.<br />
'''<br />
if proposal_id &gt; self.highest_proposal_id:<br />
self.highest_proposal_id = proposal_id</p>
<p>def receive_nack(self, msg):<br />
'''<br />
Returns a new Prepare message if the number of Nacks received reaches<br />
a quorum.<br />
'''<br />
self.observe_proposal( msg.promised_proposal_id )</p>
<p>if msg.proposal_id == self.proposal_id and self.nacks_received is not None:<br />
self.nacks_received.add( msg.from_uid )</p>
<p>if len(self.nacks_received) == self.quorum_size:<br />
return self.prepare() # Lost leadership or failed to acquire it</p>
<p>def receive_promise(self, msg):<br />
'''<br />
Returns an Accept messages if a quorum of Promise messages is achieved<br />
'''<br />
self.observe_proposal( msg.proposal_id )</p>
<p>if not self.leader and msg.proposal_id == self.proposal_id and msg.from_uid not in self.promises_received:</p>
<p>self.promises_received.add( msg.from_uid )</p>
<p>if msg.last_accepted_id &gt; self.highest_accepted_id:<br />
self.highest_accepted_id = msg.last_accepted_id<br />
if msg.last_accepted_value is not None:<br />
self.proposed_value = msg.last_accepted_value</p>
<p>if len(self.promises_received) == self.quorum_size:<br />
self.leader = True</p>
<p>if self.proposed_value is not None:<br />
self.current_accept_msg = Accept(self.network_uid, self.proposal_id, self.proposed_value)<br />
return self.current_accept_msg</p>
<p>class Acceptor (MessageHandler):<br />
'''<br />
Acceptors act as the fault-tolerant memory for Paxos. To ensure correctness<br />
in the presense of failure, Acceptors must be able to remember the promises<br />
they've made even in the event of power outages. Consequently, any changes<br />
to the promised_id, accepted_id, and/or accepted_value must be persisted to<br />
stable media prior to sending promise and accepted messages.</p>
<p>When an Acceptor instance is composed alongside a Proposer instance, it<br />
is generally advantageous to call the proposer's observe_proposal()<br />
method when methods of this class are called.<br />
'''</p>
<p>def __init__(self, network_uid, promised_id=None, accepted_id=None, accepted_value=None):<br />
'''<br />
promised_id, accepted_id, and accepted_value should be provided if and only if this<br />
instance is recovering from persistent state.<br />
'''<br />
self.network_uid = network_uid<br />
self.promised_id = promised_id<br />
self.accepted_id = accepted_id<br />
self.accepted_value = accepted_value</p>
<p>def receive_prepare(self, msg):<br />
'''<br />
Returns either a Promise or a Nack in response. The Acceptor's state must be persisted to disk<br />
prior to transmitting the Promise message.<br />
'''<br />
if msg.proposal_id &gt;= self.promised_id:<br />
self.promised_id = msg.proposal_id<br />
return Promise(self.network_uid, msg.from_uid, self.promised_id, self.accepted_id, self.accepted_value)<br />
else:<br />
return Nack(self.network_uid, msg.from_uid, msg.proposal_id, self.promised_id)</p>
<p>def receive_accept(self, msg):<br />
'''<br />
Returns either an Accepted or Nack message in response. The Acceptor's state must be persisted<br />
to disk prior to transmitting the Accepted message.<br />
'''<br />
if msg.proposal_id &gt;= self.promised_id:<br />
self.promised_id = msg.proposal_id<br />
self.accepted_id = msg.proposal_id<br />
self.accepted_value = msg.proposal_value<br />
return Accepted(self.network_uid, msg.proposal_id, msg.proposal_value)<br />
else:<br />
return Nack(self.network_uid, msg.from_uid, msg.proposal_id, self.promised_id)</p>
<p>class Learner (MessageHandler):<br />
'''<br />
This class listens to Accepted messages, determines when the final value is<br />
selected, and tracks which peers have accepted the final value.<br />
'''<br />
class ProposalStatus (object):<br />
__slots__ = ['accept_count', 'retain_count', 'acceptors', 'value']<br />
def __init__(self, value):<br />
self.accept_count = 0<br />
self.retain_count = 0<br />
self.acceptors = set()<br />
self.value = value</p>
<p>def __init__(self, network_uid, quorum_size):<br />
self.network_uid = network_uid<br />
self.quorum_size = quorum_size<br />
self.proposals = dict() # maps proposal_id =&gt; ProposalStatus<br />
self.acceptors = dict() # maps from_uid =&gt; last_accepted_proposal_id<br />
self.final_value = None<br />
self.final_acceptors = None # Will be a set of acceptor UIDs once the final value is chosen<br />
self.final_proposal_id = None</p>
<p>def receive_accepted(self, msg):<br />
'''<br />
Called when an Accepted message is received from an acceptor. Once the final value<br />
is determined, the return value of this method will be a Resolution message containing<br />
the consentual value. Subsequent calls after the resolution is chosen will continue to add<br />
new Acceptors to the final_acceptors set and return Resolution messages.<br />
'''<br />
if self.final_value is not None:<br />
if msg.proposal_id &gt;= self.final_proposal_id and msg.proposal_value == self.final_value:<br />
self.final_acceptors.add( msg.from_uid )<br />
return Resolution(self.network_uid, self.final_value)</p>
<p>last_pn = self.acceptors.get(msg.from_uid)</p>
<p>if msg.proposal_id &lt;= last_pn:<br />
return # Old message</p>
<p>self.acceptors[ msg.from_uid ] = msg.proposal_id</p>
<p>if last_pn is not None:<br />
ps = self.proposals[ last_pn ]<br />
ps.retain_count -= 1<br />
ps.acceptors.remove(msg.from_uid)<br />
if ps.retain_count == 0:<br />
del self.proposals[ last_pn ]</p>
<p>if not msg.proposal_id in self.proposals:<br />
self.proposals[ msg.proposal_id ] = Learner.ProposalStatus(msg.proposal_value)</p>
<p>ps = self.proposals[ msg.proposal_id ]</p>
<p>assert msg.proposal_value == ps.value, 'Value mismatch for single proposal!'</p>
<p>ps.accept_count += 1<br />
ps.retain_count += 1<br />
ps.acceptors.add(msg.from_uid)</p>
<p>if ps.accept_count == self.quorum_size:<br />
self.final_proposal_id = msg.proposal_id<br />
self.final_value = msg.proposal_value<br />
self.final_acceptors = ps.acceptors<br />
self.proposals = None<br />
self.acceptors = None</p>
<p>return Resolution( self.network_uid, self.final_value )</p>
<p>class PaxosInstance (Proposer, Acceptor, Learner):<br />
'''<br />
Aggregate Proposer, Accepter, &amp; Learner class.<br />
'''</p>
<p>def __init__(self, network_uid, quorum_size, promised_id=None, accepted_id=None, accepted_value=None):<br />
Proposer.__init__(self, network_uid, quorum_size)<br />
Acceptor.__init__(self, network_uid, promised_id, accepted_id, accepted_value)<br />
Learner.__init__(self, network_uid, quorum_size)</p>
<p>def receive_prepare(self, msg):<br />
self.observe_proposal( msg.proposal_id )<br />
return super(PaxosInstance,self).receive_prepare(msg)</p>
<p>def receive_accept(self, msg):<br />
self.observe_proposal( msg.proposal_id )<br />
return super(PaxosInstance,self).receive_accept(msg)<br />

 

Advertisements

1 Comment »

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: