diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,5 @@
+# Revision history for raft-consensus
+
+## 0.1.0.0 -- 2026-11-26
+
+* First version. Released on an unsuspecting world.
diff --git a/LICENSE b/LICENSE
new file mode 100644
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,29 @@
+Copyright (c) 2026, Laurent P. René de Cotret
+
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+
+    * Redistributions in binary form must reproduce the above
+      copyright notice, this list of conditions and the following
+      disclaimer in the documentation and/or other materials provided
+      with the distribution.
+
+    * Neither the name of the copyright holder nor the names of its
+      contributors may be used to endorse or promote products derived
+      from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/README.md b/README.md
new file mode 100644
--- /dev/null
+++ b/README.md
@@ -0,0 +1,72 @@
+# raft-consensus
+
+Haskell implementation of the Raft consensus protocol, with built-in support for deterministic simulation testing.
+
+This library lets you bring your own pure state machine, persistence layer, and communication layer to implement a fault-tolerant, strongly-consistent, distributed state machine.
+
+Features of the Raft algorithm include:
+
+* Leader election;
+* Log replication;
+* Log compaction (i.e. snapshotting);
+* Membership changes;
+* Client request pipelining;
+* Read-only query optimizations;
+
+The goal is to have feature-parity with industry standard implementations such as [etcd's Raft implementation](https://github.com/etcd-io/raft).
+
+## Development
+
+This library can be built using `cabal`:
+
+```sh
+$ cabal build
+```
+
+and tests can be run with:
+
+```sh
+$ cabal test
+```
+
+### Deterministic simulation testing
+
+Cluster properties and client request linearizability are tested under two modes: with, and without, schedule exploration.
+
+In both cases, the cluster's and clients' initial conditions are generated at random by QuickCheck: timeouts, cluster configuration, fault schedules, etc.
+
+Without schedule exploration, a simulated trace is run from these initial conditions. This is relatively fast, and allows to explore the behavior of the system under many initial conditions. You can tweak the number of tests run in this mode using the `quichcheck-tests` option. For example:
+
+```sh
+cabal test --test-options='--quickcheck-tests=1000'
+```
+
+With schedule exploration, the system is started in randomly-generated conditions. However, whenever the simulation reaches a branching-point, timing-wise, both branches are explored separately as tests. This is much slower, but allows to detect races in the execution of a cluster. You can tweak the number of tests in this mode using the `num-racy-tests` option. For example:
+
+```sh
+cabal test --test-options='--num-racy-tests=5'
+```
+
+### Replaying a failure
+
+
+During the course of development, you may see a test failure for the deterministic simulation test suite:
+
+```sh
+$ cabal test
+Running 1 test suites...
+Test suite raft-consensus-test: RUNNING...
+raft-consensus
+  Raft
+    Property tests
+      Cluster properties: FAIL
+        <snip>
+        Use --quickcheck-replay="(SMGen 6009993106432336185 7272677387067049729,0)" to reproduce.
+        <snip>
+```
+
+This is great news! You can replay the specific failing scenario using `--quickcheck-replay` in combination with `test-options`:
+
+```sh
+$ cabal test --test-options='--quickcheck-replay="(SMGen 6009993106432336185 7272677387067049729,0)"'
+```
diff --git a/bench/Main.hs b/bench/Main.hs
new file mode 100644
--- /dev/null
+++ b/bench/Main.hs
@@ -0,0 +1,301 @@
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE NumericUnderscores #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE RankNTypes #-}
+{-# LANGUAGE TupleSections #-}
+
+module Main (main) where
+
+import Control.Concurrent (threadDelay)
+import Control.Concurrent.Async (async, cancel, forConcurrently_)
+import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)
+import Control.Concurrent.STM (TQueue, atomically, flushTQueue, newTQueueIO, readTQueue, retry, writeTQueue)
+import Control.DeepSeq (NFData)
+import Control.Monad (forever, replicateM, (>=>))
+import Data.Functor ((<&>))
+import Data.IntMap.Strict (IntMap)
+import qualified Data.IntMap.Strict as IntMap
+import Data.List.NonEmpty (NonEmpty, nonEmpty)
+import Data.Map.Strict (Map)
+import qualified Data.Map.Strict as Map
+import Data.Set (Set)
+import qualified Data.Set as Set
+import Data.Word (Word64)
+import Distributed.Consensus.Raft (Config (..), Implementation (..), Microseconds, Networking (..), RPC, RPCResult, StateMachineStep (..), ephemeralPersistence, runRaftServer)
+import qualified Distributed.Consensus.Raft as Raft
+import Distributed.Consensus.Raft.Admin (AdminRequest, AdminResponse)
+import Distributed.Consensus.Raft.Client
+  ( ClientError,
+    ClientImplementation (..),
+    ClientRequest,
+    ClientResponse,
+    newRequest,
+    sendClientRequest,
+    sessionId,
+    withClientSession,
+  )
+import GHC.Generics (Generic)
+import Test.Tasty (withResource)
+import Test.Tasty.Bench (bench, bgroup, defaultMain, nfIO)
+
+main :: IO ()
+main = do
+  defaultMain
+    [ withResource startCluster stopCluster $ \getClusterHandle ->
+        bgroup
+          "Benchmark"
+          [ unloadedLatency getClusterHandle,
+            bgroup
+              "Unloaded throughput"
+              [ unloadedThroughput getClusterHandle 1,
+                unloadedThroughput getClusterHandle 10,
+                unloadedThroughput getClusterHandle 100
+              ]
+          ]
+    ]
+  where
+    unloadedLatency getClusterHandle =
+      bench "Unloaded latency " $ nfIO $ do
+        cluster <- getClusterHandle
+        cluster.runRequest (Get 'a')
+
+    unloadedThroughput getClusterHandle batchSize =
+      bench (show batchSize <> " commands") $
+        nfIO $
+          do
+            cluster <- getClusterHandle
+            replicateM batchSize (cluster.runRequest (Get 'a'))
+
+data Cluster = Cluster
+  { runRequest :: Command -> IO Result,
+    runShutDown :: IO ()
+  }
+
+startCluster :: IO Cluster
+startCluster = do
+  harness <- benchHarness clusterScenario
+  serversTid <- async (runServers harness)
+
+  runnerVar <- newEmptyMVar
+  sessionTid <-
+    async $
+      withClient harness $ \runClientRequest -> do
+        putMVar runnerVar runClientRequest
+        forever (threadDelay 1_000_000)
+  runClientRequest <- takeMVar runnerVar
+
+  leader <- waitUntilLeaderElected runClientRequest
+  pure $
+    Cluster
+      { runRequest = runClientRequest leader >=> either (fail . show) (pure . snd),
+        runShutDown = cancel sessionTid >> cancel serversTid
+      }
+  where
+    waitUntilLeaderElected runClientRequest =
+      runClientRequest 0 (Get 'a') >>= \case
+        Left _ -> threadDelay 10_000 >> waitUntilLeaderElected runClientRequest
+        Right (leader, _) -> pure leader
+
+    runServers :: Harness -> IO ()
+    runServers harness =
+      forConcurrently_ (IntMap.elems harness.clusterServers) $ \server ->
+        runRaftServer
+          server.sConfig
+          (Raft.InCluster $ Set.fromList (map fromIntegral $ IntMap.keys harness.clusterServers))
+          mempty
+          server.sSpec
+
+stopCluster :: Cluster -> IO ()
+stopCluster = runShutDown
+
+clusterScenario :: ScenarioInputs
+clusterScenario =
+  let numNodes = 9
+   in ScenarioInputs
+        { heartbeatTimeout = 10_000,
+          electionTimeoutLowerBound = 100_000,
+          electionTimeoutUpperBound = 300_000,
+          seeds = [1 .. numNodes],
+          numInitialClusterNodes = fromIntegral numNodes
+        }
+
+data ScenarioInputs
+  = ScenarioInputs
+  { heartbeatTimeout :: Microseconds,
+    electionTimeoutLowerBound :: Microseconds,
+    electionTimeoutUpperBound :: Microseconds,
+    seeds :: [Word64],
+    numInitialClusterNodes :: Int
+  }
+  deriving (Eq, Show)
+
+data Server
+  = MkServer
+  { sConfig :: Config Node,
+    sSpec :: Implementation Command Node Result State IO
+  }
+
+type Mailbox a = IntMap (TQueue a)
+
+data NetworkFabric
+  = MkNetworkFabric
+  { rpcMailbox :: Mailbox (RPC Command Node State),
+    rpcResultsMailbox :: Mailbox (RPCResult Node Result),
+    requestsMailbox :: Mailbox (ClientRequest Command Node),
+    responsesMailbox :: Mailbox (ClientResponse Node Result),
+    adminMailbox :: Mailbox (AdminRequest Node),
+    adminResponsesMailbox :: Mailbox (AdminResponse Node)
+  }
+
+newNetworkFabric :: Set Node -> IO NetworkFabric
+newNetworkFabric nodes =
+  MkNetworkFabric
+    <$> newMailbox
+    <*> newMailbox
+    <*> newMailbox
+    <*> newMailbox
+    <*> newMailbox
+    <*> newMailbox
+  where
+    newMailbox =
+      IntMap.fromList
+        <$> traverse
+          (\n -> (fromIntegral n,) <$> newTQueueIO)
+          (Set.toList nodes)
+
+mkServer :: NetworkFabric -> Microseconds -> Microseconds -> Microseconds -> Word64 -> Node -> Server
+mkServer network hbto etolb etoub seed node =
+  MkServer
+    { sConfig =
+        MkConfig
+          { nodeId = node,
+            electionTimeoutRange = (etolb, etoub),
+            heartBeatTimeout = hbto,
+            randomSeed = seed,
+            maxLogLength = Nothing
+          },
+      sSpec =
+        Implementation
+          { persistence = ephemeralPersistence,
+            stateMachine = step,
+            networking =
+              Networking
+                { sendRPC = send network.rpcMailbox,
+                  sendRPCResult = send network.rpcResultsMailbox,
+                  sendClientResponse = send network.responsesMailbox,
+                  sendAdminResponse = send network.adminResponsesMailbox,
+                  receiveRPC = receive network.rpcMailbox node,
+                  receiveRPCResult = receive network.rpcResultsMailbox node,
+                  receiveClientRequests = receiveAll network.requestsMailbox node,
+                  receiveAdminRequest = receive network.adminMailbox node
+                },
+            tracer = \_ -> pure ()
+          }
+    }
+
+data Harness
+  = MkHarness
+  { clusterServers :: IntMap Server,
+    -- | Open a client session and run an action with it. One session serves
+    -- the whole benchmark: see 'withClientSession'.
+    withClient ::
+      forall b.
+      ((Node -> Command -> IO (Either (ClientError Command Node) (Node, Result))) -> IO b) ->
+      IO b
+  }
+
+benchHarness ::
+  ScenarioInputs ->
+  IO Harness
+benchHarness
+  (ScenarioInputs hb etlb etup s numClusterNodes) = do
+    networkFabric <-
+      newNetworkFabric $
+        mconcat
+          [ Set.fromList (fromIntegral <$> serverNodes),
+            Set.singleton clientNode,
+            Set.singleton adminNode
+          ]
+
+    let mkServer' :: Word64 -> Node -> Server
+        mkServer' = mkServer networkFabric hb etlb etup
+
+    pure $
+      MkHarness
+        { clusterServers =
+            IntMap.fromList $
+              map (\(serverSeed, n) -> (n, mkServer' serverSeed (fromIntegral n))) serverNodesWithSeeds,
+          withClient = \useClient ->
+            withClientSession clientNode (clientSpec networkFabric) $ \runSession ->
+              useClient (\leader comm -> runSession (newRequest comm >>= sendClientRequest maxBound leader))
+        }
+    where
+      adminNode = -1
+      clientNode = Node $ numClusterNodes + 1
+
+      serverNodes = [0 .. numClusterNodes - 1]
+      serverNodesWithSeeds = zip (take numClusterNodes s) serverNodes
+
+      clientSpec network =
+        ClientImplementation
+          { sendRequest = send network.requestsMailbox,
+            receiveResponse =
+              receive network.responsesMailbox clientNode,
+            -- We should generate a random session ID in normal circumstances,
+            -- but for a benchmark this doesn't matter
+            generateSessionId = pure . sessionId 0 . fromIntegral
+          }
+
+simulatedNetworkLatency :: IO ()
+simulatedNetworkLatency = threadDelay 1_000
+
+send :: IntMap (TQueue a) -> Node -> a -> IO ()
+send mailbox node message =
+  case IntMap.lookup (fromIntegral node) mailbox of
+    Nothing -> error $ "Mailbox badly configures: missing node " <> show node
+    Just queue -> simulatedNetworkLatency >> atomically (writeTQueue queue message)
+
+receive :: IntMap (TQueue a) -> Node -> IO a
+receive mailbox node =
+  case IntMap.lookup (fromIntegral node) mailbox of
+    Nothing -> error $ "Mailbox badly configures: missing node " <> show node
+    Just queue -> atomically $ readTQueue queue
+
+receiveAll :: IntMap (TQueue a) -> Node -> IO (NonEmpty a)
+receiveAll mailbox node =
+  case IntMap.lookup (fromIntegral node) mailbox of
+    Nothing -> error $ "Mailbox badly configures: missing node " <> show node
+    Just queue ->
+      atomically $
+        flushTQueue queue <&> nonEmpty >>= \case
+          Nothing -> retry
+          Just xs -> pure xs
+
+-- Simple key-value store
+
+newtype Node = Node Int
+  deriving (Eq, Show, Bounded, Enum, Num, Ord, Real, Integral)
+
+type State = Map Char Int
+
+data Command
+  = Insert Char Int
+  | Delete Char
+  | Get Char
+  deriving (Eq, Ord, Show)
+
+data Result
+  = Value Int
+  | Ok
+  | Err
+  deriving (Eq, Show, Generic)
+
+instance NFData Result
+
+step :: Command -> StateMachineStep Result State
+step (Insert k v) = Transition $ \state -> (Map.insert k v state, Ok)
+step (Delete k) = Transition $ \state -> (Map.delete k state, Ok)
+step (Get k) = Read $ \state -> maybe Err Value (Map.lookup k state)
diff --git a/raft-consensus.cabal b/raft-consensus.cabal
new file mode 100644
--- /dev/null
+++ b/raft-consensus.cabal
@@ -0,0 +1,107 @@
+cabal-version:      3.4
+name:               raft-consensus
+version:            0.1.0.0
+synopsis:           Haskell implementation of the Raft consensus protocol
+-- description:
+homepage:           https://github.com/LaurentRDC/distributed-consensus
+license:            BSD-3-Clause
+license-file:       LICENSE
+author:             Laurent P. René de Cotret
+maintainer:         laurent.decotret@outlook.com
+copyright:          Laurent P. René de Cotret
+category:           Distributed Systems, Consensus
+build-type:         Simple
+extra-doc-files:    README.md
+                    CHANGELOG.md
+
+source-repository head
+    type: git
+    location: https://github.com/LaurentRDC/distributed-consensus
+    subdir: raft-consensus
+
+common warnings
+    ghc-options: -Wall
+                 -Wcompat
+                 -Widentities
+                 -Wincomplete-uni-patterns
+                 -Wincomplete-record-updates
+                 -Wredundant-constraints
+                 -fhide-source-paths
+                 -Wpartial-fields
+                 -Wunused-packages
+
+library
+    import:           warnings
+    exposed-modules:  Distributed.Consensus.Raft
+                      -- TODO: split out client and admin modules
+                      --       into separate libraries so that a client
+                      --       executable doesn't need to compile the
+                      --       Raft algorithm?
+                      Distributed.Consensus.Raft.Admin
+                      Distributed.Consensus.Raft.Client
+    other-modules:    Distributed.Consensus.Raft.Algorithm
+                      Distributed.Consensus.Raft.Domain
+                      Distributed.Consensus.Raft.Domain.Admin
+                      Distributed.Consensus.Raft.Domain.Client
+                      Distributed.Consensus.Raft.Implementation
+                      Distributed.Consensus.Raft.Log
+                      Distributed.Consensus.Raft.Messaging
+                      Distributed.Consensus.Raft.Transformer
+                      Distributed.Consensus.Raft.Transformer.Definition
+                      Distributed.Consensus.Raft.Timer
+    -- GHC 9.6+ (base 4.18+) is required to infer types properly when
+    -- using io-classes
+    build-depends:    base >= 4.18 && <4.23
+                    , binary ^>=0.8
+                    , containers >=0.7 && <0.9
+                    , io-classes ^>=1.11
+                    , microlens-platform ^>=0.4
+                    , random ^>=1.3
+                    , transformers ^>=0.6
+    hs-source-dirs:   src
+    default-language: Haskell2010
+
+test-suite raft-consensus-test
+    import:           warnings
+    default-language: Haskell2010
+    type:             exitcode-stdio-1.0
+    hs-source-dirs:   tests
+    main-is:          Main.hs
+    other-modules:    Control.Monitor
+                      Control.Monitor.Predicate
+                      Control.Monitor.Reason
+                      Test.Distributed.Consensus.Raft
+                      Test.Distributed.Consensus.Raft.Client
+                      Test.Distributed.Consensus.Raft.Options
+                      Test.Distributed.Consensus.Raft.Properties
+                      Test.Distributed.Consensus.Raft.Scenario
+                      Test.StateMachine
+    ghc-options:      -rtsopts -threaded -with-rtsopts=-N
+    build-depends:    base >= 4.18 && <4.23
+                    , containers
+                    , raft-consensus
+                    , io-classes
+                    , io-sim ^>=1.11
+                    , linearizable ^>=0.1
+                    , pretty-simple ^>=4.1
+                    , random
+                    , tagged ^>=0.8
+                    , tasty ^>=1.5
+                    , tasty-quickcheck ^>=0.11
+                    , text
+
+benchmark raft-cluster
+  import:           warnings
+  default-language: Haskell2010
+  type:             exitcode-stdio-1.0
+  hs-source-dirs:   bench
+  main-is:          Main.hs
+  ghc-options:      -rtsopts -threaded -with-rtsopts=-N
+  build-depends:    async
+                  , base
+                  , containers
+                  , deepseq
+                  , raft-consensus
+                  , stm
+                  , tasty
+                  , tasty-bench
diff --git a/src/Distributed/Consensus/Raft.hs b/src/Distributed/Consensus/Raft.hs
new file mode 100644
--- /dev/null
+++ b/src/Distributed/Consensus/Raft.hs
@@ -0,0 +1,229 @@
+-- |
+-- Module:      $module
+-- Copyright:   (c) Laurent P. René de Cotret
+-- License:     BSD 3-Clause
+--
+-- Implementation of the <https://raft.github.io/raft.pdf Raft distributed consensus algorithm>,
+-- generic over networking and persistence.
+--
+-- === Why make use of distributed consensus
+--
+-- Distributed consensus allows to replicate a state machine across separate nodes. The major advantage
+-- is that a failure in one of the nodes does not lead to data loss, as the state machine's state is
+-- replicated on all nodes.
+--
+-- In the jargon, distributed consensus gives you a state machine which is strongly-consistent and fault-tolerant.
+--
+-- Applications of distributed consensus include boring but important things like distributed key-value store,
+-- or exciting things like distributed software transactional memory.
+--
+-- In practice, you should avoid having to use distributed consensus as much as possible. Strong consistency
+-- is desirable, but it comes at the cost of performance. It is also phenomenally difficult to implement correctly
+-- (more on this below).
+-- Nonetheless, if you persist in your desire to use distributed consensus, this library aims to be both
+-- correct and performant.
+--
+-- === Why use the @raft-consensus@ library
+--
+-- This library implements the core of the Raft algorithm while being agnostic to the way you implement
+-- networking and persistence. It is designed to be versatile and adapt to your needs.
+-- The genericity also serves to improve the testing story.
+--
+-- === How is @raft-consensus@ tested?
+--
+-- @raft-consensus@ makes use of a testing technique known as deterministic simulation testing,
+-- which finds bugs in the actual implementation by simulating operating conditions without actually doing any IO.
+-- The test suite uses deterministic simulation testing to execute the cluster logic over a wide range of
+-- inputs, and injects deterministic faults such as crashes and network partitions.
+--
+-- Cluster properties (such as the expectation that a cluster leader has the
+-- correct state) are continuously monitored to ensure that the implementation of @raft-consensus@ behaves
+-- in practice like the algorithm is designed.
+--
+-- In parallel, client requests are monitored during simulations, and their linearizability is checked
+-- using the linearizability checker from the @linearizable@ package.
+--
+-- === How does one use @raft-consensus@?
+--
+-- @raft-consensus@ requires a few things from you:
+--
+-- 1. You need to define your state machine of type 'StateMachineStep'.
+-- 2. You need to implement networking by creating a record of functions of type 'Networking'.
+--    A separate package @raft-consensus-distributed-process@ is provided in case you wish
+--    to use Cloud Haskell (@distributed-process@) for networking.
+-- 3. You need to implement persistence by creating a record of functions of type 'Persistence'.
+--    A separate package @raft-consensus-wal@ is provided in case you wish to use
+--    a write-ahead log from the @wal@ package.
+--
+-- Once this is done, you are ready to start individual nodes of your cluster using 'runRaftServer'
+-- or 'withRaftServer'.
+--
+-- === How does one interact with a @raft-consensus@-based cluster?
+--
+-- There are two ways to interact with a cluster:
+--
+-- * The typical way is as a client. A client is a process that sends requests to either read
+--   from the state machine, or mutate the state machine. This functionality is provided in
+--   the "Distributed.Consensus.Raft.Client" module.
+-- * The other way is as a cluster administrator. An administrator is a process that sends
+--   administrative requests, including requesting that a node join or leave a cluster.
+--   This functionality is provided in the "Distributed.Consensus.Raft.Admin" module.
+--
+-- === Examples
+--
+-- The <https://github.com/LaurentRDC/distributed-consensus source repository> contains examples
+-- of applications that make use of @raft-consensus@ and associated libraries.
+module Distributed.Consensus.Raft
+  ( -- * Server
+    runRaftServer,
+    withRaftServer,
+
+    -- ** Configuration
+    simpleConfig,
+    Config (..),
+
+    -- ** Configuration types
+    Microseconds,
+    ClusterState (..),
+
+    -- * Protocol implementation
+    Implementation (..),
+    Networking (..),
+    Persistence (..),
+    StateMachineStep (..),
+    runStateMachineStep,
+
+    -- ** Helpers
+    nullTracer,
+    ephemeralPersistence,
+
+    -- ** Domain types
+    LogEntry (..),
+    Term,
+    Role,
+    ClientRequestId,
+    ClusterConfiguration (..),
+    LogIndex,
+    Snapshot (..),
+    SnapshotMetadata (..),
+    SessionId,
+
+    -- ** Remote procedure calls
+    RPC (..),
+    RPCResult (..),
+    Command (..),
+    CommandResponse (..),
+    AppendEntries (..),
+    AppendEntriesResult (..),
+    InstallSnapshot (..),
+    InstallSnapshotResult (..),
+    ClusterMembershipRequest (..),
+    ClusterMembershipResult (..),
+    ClusterMembershipError (..),
+
+    -- ** Messaging
+    Request (..),
+    Response (..),
+
+    -- ** Event tracing
+    Event (..),
+    EventContext (..),
+    RaftTrace (..),
+    Log,
+  )
+where
+
+import Control.Concurrent.Class.MonadMVar (MonadMVar)
+import Control.Monad.Class.MonadAsync (MonadAsync, link, withAsync)
+import Control.Monad.Class.MonadFork (MonadFork)
+import Control.Monad.Class.MonadThrow (MonadMask)
+import Control.Monad.Class.MonadTimer (MonadDelay)
+import Distributed.Consensus.Raft.Algorithm (server)
+import Distributed.Consensus.Raft.Client (ClientRequestId)
+import Distributed.Consensus.Raft.Domain
+  ( ClusterConfiguration (..),
+    LogIndex,
+    Role,
+    SessionId,
+    Snapshot (..),
+    SnapshotMetadata (..),
+    StateMachineStep (..),
+    Term,
+    runStateMachineStep,
+  )
+import Distributed.Consensus.Raft.Implementation
+  ( AppendEntries (..),
+    AppendEntriesResult (..),
+    ClusterMembershipError (..),
+    ClusterMembershipRequest (..),
+    ClusterMembershipResult (..),
+    Command (..),
+    CommandResponse (..),
+    Event (..),
+    EventContext (..),
+    Implementation (..),
+    InstallSnapshot (..),
+    InstallSnapshotResult (..),
+    LogEntry (..),
+    Networking (..),
+    Persistence (..),
+    RPC (..),
+    RPCResult (..),
+    RaftTrace (..),
+    ephemeralPersistence,
+    nullTracer,
+  )
+import Distributed.Consensus.Raft.Log (Log)
+import Distributed.Consensus.Raft.Messaging
+  ( Request (..),
+    Response (..),
+  )
+import Distributed.Consensus.Raft.Timer (Microseconds (..))
+import Distributed.Consensus.Raft.Transformer
+  ( ClusterState (..),
+    Config (..),
+    runRaftT,
+    simpleConfig,
+  )
+
+-- | Run a Raft server. This function returns in case of an administrative
+-- request to shut down.
+--
+-- See also 'withRaftServer'.
+runRaftServer ::
+  ( Ord node,
+    MonadMVar m,
+    MonadMask m,
+    MonadDelay m,
+    MonadAsync m,
+    MonadFork m
+  ) =>
+  Config node ->
+  ClusterState node ->
+  state ->
+  Implementation entry node result state m ->
+  m ()
+runRaftServer config startingState initState impl =
+  runRaftT config startingState initState impl server
+
+-- | Run a Raft server in a separate thread, while running a separate action.
+--
+-- Once the action returns, the server is shut down.
+withRaftServer ::
+  ( Ord node,
+    MonadMVar m,
+    MonadMask m,
+    MonadDelay m,
+    MonadAsync m,
+    MonadFork m
+  ) =>
+  Config node ->
+  ClusterState node ->
+  state ->
+  Implementation entry node result state m ->
+  m a ->
+  m a
+withRaftServer config startingState initState impl f =
+  withAsync (runRaftServer config startingState initState impl) $ \serverThread -> do
+    link serverThread
+    f
diff --git a/src/Distributed/Consensus/Raft/Admin.hs b/src/Distributed/Consensus/Raft/Admin.hs
new file mode 100644
--- /dev/null
+++ b/src/Distributed/Consensus/Raft/Admin.hs
@@ -0,0 +1,290 @@
+{-# LANGUAGE BangPatterns #-}
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE DerivingStrategies #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE RankNTypes #-}
+{-# LANGUAGE TemplateHaskell #-}
+
+-- |
+-- Module:      $module
+-- Copyright:   (c) Laurent P. René de Cotret
+-- License:     BSD 3-Clause
+--
+-- Manage a Raft cluster as an administrator.
+--
+-- === How to use this module
+--
+-- The key piece of information to use this module effectively is that
+-- interactions are done in /sessions/. An admin starts a session
+-- by calling 'withAdminSession', and all requests will have to originate
+-- from within.
+--
+-- Try to keep sessions open as long as possible -- ideally for the length
+-- of an admin's lifetime.
+--
+-- Administrators create requests using 'leaveCluster', 'joinCluster', or other builders.
+-- Requests are then sent using 'sendAdminCommand'. Interacting with a cluster may
+-- require retrying or redirecting requests; reuse requests as much as possible.
+-- To keep the implementation flexible, retrying and redirecting is something
+-- you need to do yourself.
+module Distributed.Consensus.Raft.Admin
+  ( -- * Interface
+    withAdminSession,
+    RaftAdminT,
+
+    -- ** Creating commands
+    leaveCluster,
+    joinCluster,
+    getClusterConfiguration,
+    shutDown,
+
+    -- ** Sending commands
+    sendAdminCommand,
+    AdminError (..),
+
+    -- ** Configuration
+    AdminImplementation (..),
+
+    -- * Other exports
+    SessionId,
+    sessionId,
+    SequenceNum,
+    Microseconds,
+    AdminRequest,
+    Request (..),
+    AdminResponse,
+    Response (..),
+    AdminCommand (..),
+    AdminCommandResult (..),
+  )
+where
+
+import Control.Concurrent.Class.MonadSTM
+  ( MonadSTM,
+    TMVar,
+    TVar,
+    atomically,
+    check,
+    newEmptyTMVar,
+    newTVarIO,
+    orElse,
+    readTMVar,
+    readTVar,
+    tryPutTMVar,
+    writeTVar,
+  )
+import Control.Monad (void)
+import Control.Monad.Class.MonadAsync (MonadAsync, link, withAsync)
+import Control.Monad.Class.MonadFork (MonadFork)
+import Control.Monad.Class.MonadThrow (MonadMask)
+import Control.Monad.Class.MonadTimer (MonadTimer, registerDelay)
+import Control.Monad.Trans.Class (MonadTrans (lift))
+import Control.Monad.Trans.Reader (ReaderT (runReaderT))
+import qualified Control.Monad.Trans.Reader as Reader
+import Data.Map (Map)
+import qualified Data.Map.Strict as Map
+import Distributed.Consensus.Raft.Domain (SequenceNum, SessionId, sessionId)
+import Distributed.Consensus.Raft.Domain.Admin
+  ( AdminCommand (..),
+    AdminCommandResult (..),
+    AdminRequest,
+    AdminRequestId (MkAdminRequestId),
+    AdminResponse,
+  )
+import Distributed.Consensus.Raft.Messaging (Request (..), Response (..))
+import Distributed.Consensus.Raft.Timer (Microseconds)
+import Lens.Micro.Platform (makeLenses)
+
+-- | Admin monad transformer to issue administrative commands to a Raft cluster.
+--
+-- The only way to execute an action of type 'RaftAdminT' is with
+-- 'withAdminSession'.
+newtype RaftAdminT node m a
+  = MkRaftAdminT (ReaderT (RaftAdminEnv node m) m a)
+  deriving (Functor, Applicative, Monad)
+
+instance MonadTrans (RaftAdminT node) where
+  lift = MkRaftAdminT . lift
+
+asks :: (Monad m) => (RaftAdminEnv node m -> a) -> RaftAdminT node m a
+asks = MkRaftAdminT . Reader.asks
+
+-- | Implementation of communication between an administrator and a cluster.
+--
+-- See the @raft-consensus-distributed-process@ package for an example
+-- implementation for the Cloud Haskell ecosystem.
+data AdminImplementation node m = AdminImplementation
+  { -- | Send an admin request to a node.
+    sendAdminRequest :: node -> AdminRequest node -> m (),
+    -- | Receive the next admin response.
+    receiveAdminResponse :: m (AdminResponse node),
+    -- | Generate a globally-unique session ID.
+    generateSessionId :: node -> m SessionId
+  }
+
+-- | Open an admin session, and run an action with a runner for that session.
+--
+-- It is safe to use the runner from several threads concurrently.
+--
+-- The typical way you would use 'withAdminSession' is like so:
+--
+-- @
+-- 'withAdminSession' nodeId $ \\run -> do
+--     req <- run 'shutDown'
+--
+--     let go serverNode =
+--             run ('sendAdminCommand' 1000000 serverNode req) >>= \case
+--                Left _ -> go serverNode -- infinite retries
+--                Right resp -> pure resp
+--
+--     go lastKnownLeader
+-- @
+--
+-- In practice, 'withAdminSession' is usually run in its own thread,
+-- and requests are sent over to that thread using e.g. a 'TQueue'.
+withAdminSession ::
+  ( MonadAsync m,
+    MonadFork m,
+    MonadMask m
+  ) =>
+  -- | self identification
+  node ->
+  AdminImplementation node m ->
+  ((forall a. RaftAdminT node m a -> m a) -> m b) ->
+  m b
+withAdminSession self impl withSession = do
+  nRId <- newTVarIO 0
+  mbox <- newTVarIO mempty
+  sessId <- generateSessionId impl self
+  let recvLoop = do
+        receiveAdminResponse impl >>= \resp -> do
+          let adminReqId = responseRequestId resp
+          atomically $ do
+            box <- readTVar mbox
+            case Map.lookup adminReqId box of
+              Nothing -> pure ()
+              -- Using 'tryPutTMVar' here in case of duplicate responses
+              Just var -> void $ tryPutTMVar var (responsePayload resp)
+          recvLoop
+
+  withAsync recvLoop $ \thread -> do
+    link thread
+    withSession
+      ( \(MkRaftAdminT f) ->
+          runReaderT
+            f
+            (MkRaftAdminEnv self sessId impl nRId mbox)
+      )
+
+data RaftAdminEnv node m
+  = MkRaftAdminEnv
+  { node :: !node,
+    currentSessionId :: !SessionId,
+    implementation :: AdminImplementation node m,
+    nextRequestId :: TVar m SequenceNum,
+    mailbox :: TVar m (Map AdminRequestId (TMVar m (AdminCommandResult node)))
+  }
+
+makeLenses ''AdminImplementation
+
+data AdminError node
+  = AdminNotLeader !(Maybe node)
+  | Timeout
+  | UnexpectedAdminResponse
+  deriving (Eq, Show)
+
+newCommand ::
+  (MonadSTM m) =>
+  AdminCommand node ->
+  RaftAdminT node m (AdminRequest node)
+newCommand entry = do
+  (seqNumVar, sessId, self) <- asks ((,,) <$> nextRequestId <*> currentSessionId <*> node)
+  reqId <- lift $ atomically $ do
+    nextSeqNum <- readTVar seqNumVar
+    writeTVar seqNumVar (succ nextSeqNum)
+    pure $ MkAdminRequestId sessId nextSeqNum
+
+  pure $ MkRequest reqId self entry
+
+-- | Command that a node join a Raft cluster.
+--
+-- This has no effect if the node is already a member of the
+-- cluster.
+joinCluster ::
+  (MonadSTM m) =>
+  -- | Leader of the cluster to join
+  node ->
+  RaftAdminT node m (AdminRequest node)
+joinCluster = newCommand . JoinCluster
+
+-- | Command that a node leave the Raft cluster.
+--
+-- Note that this node will not shut down unless the 'shutDown'
+-- command is also sent to it.
+leaveCluster :: (MonadSTM m) => RaftAdminT node m (AdminRequest node)
+leaveCluster = newCommand LeaveCluster
+
+-- | Ask a node for the cluster configuration it has committed.
+--
+-- This is the only way for an admin to tell whether a 'joinCluster' or
+-- 'leaveCluster' has actually taken effect.
+getClusterConfiguration :: (MonadSTM m) => RaftAdminT node m (AdminRequest node)
+getClusterConfiguration = newCommand GetClusterConfiguration
+
+-- | Request that a node shuts down.
+shutDown :: (MonadSTM m) => RaftAdminT node m (AdminRequest node)
+shutDown = newCommand ShutDown
+
+sendAdminCommand ::
+  (MonadTimer m) =>
+  Microseconds ->
+  node ->
+  AdminRequest node ->
+  RaftAdminT
+    node
+    m
+    ( Either
+        (AdminError node)
+        (AdminCommandResult node)
+    )
+sendAdminCommand timeout contact req@(MkRequest reqId _ command) = do
+  send <- asks (sendAdminRequest . implementation)
+  mbox <- asks mailbox
+  lift $ do
+    resultVar <- atomically $ do
+      mbox' <- readTVar mbox
+      resultVar <- newEmptyTMVar
+      writeTVar mbox (Map.insert reqId resultVar mbox')
+
+      pure resultVar
+
+    expired <- registerDelay (fromIntegral timeout)
+    send contact req
+
+    -- TODO: clean up mailbox entry for req ID
+    --       regardless of success (possibly using 'bracket')
+    atomically
+      ( ( do
+            resp <- readTMVar resultVar
+            mbox' <- readTVar mbox
+            writeTVar mbox (Map.delete reqId mbox')
+            pure (expectedResponse command (Just resp))
+        )
+          `orElse` ( do
+                       readTVar expired >>= check
+                       readTVar mbox >>= writeTVar mbox . Map.delete reqId
+                       pure (expectedResponse command Nothing)
+                   )
+      )
+
+-- TODO: is there a better way to associate valid responses based on the request?
+expectedResponse :: AdminCommand node -> Maybe (AdminCommandResult node) -> Either (AdminError node) (AdminCommandResult node)
+expectedResponse _ Nothing = Left Timeout
+expectedResponse _ (Just (NotLeader leader)) = Left (AdminNotLeader leader)
+expectedResponse (JoinCluster {}) (Just JoinInitiated) = Right JoinInitiated
+expectedResponse (LeaveCluster {}) (Just LeaveInitiated) = Right LeaveInitiated
+expectedResponse GetClusterConfiguration (Just resp@(ClusterConfigurationIs {})) = Right resp
+expectedResponse ShutDown (Just ShutdownInitiated) = Right ShutdownInitiated
+expectedResponse _ _ = Left UnexpectedAdminResponse
diff --git a/src/Distributed/Consensus/Raft/Algorithm.hs b/src/Distributed/Consensus/Raft/Algorithm.hs
new file mode 100644
--- /dev/null
+++ b/src/Distributed/Consensus/Raft/Algorithm.hs
@@ -0,0 +1,669 @@
+{-# LANGUAGE BangPatterns #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+module Distributed.Consensus.Raft.Algorithm
+  ( server,
+  )
+where
+
+import Control.Concurrent.Class.MonadMVar (MonadMVar, putMVar)
+import Control.Concurrent.Class.MonadSTM (atomically, readTQueue, tryPeekTQueue, writeTQueue)
+import Control.Monad (forever, unless, when)
+import Control.Monad.Class.MonadAsync (MonadAsync, async, cancel, link)
+import Control.Monad.Class.MonadFork (MonadFork, labelThisThread)
+import Control.Monad.Class.MonadThrow (MonadMask)
+import Control.Monad.Class.MonadTimer (MonadDelay)
+import Control.Monad.Trans.Class (lift)
+import Data.Foldable (for_, toList, traverse_)
+import Data.Functor ((<&>))
+import Data.List.NonEmpty (NonEmpty)
+import qualified Data.List.NonEmpty as NonEmpty
+import qualified Data.Map.Strict as Map
+import Data.Maybe (fromMaybe)
+import qualified Data.Set as Set
+import qualified Distributed.Consensus.Raft.Admin as Admin
+import Distributed.Consensus.Raft.Domain
+  ( ClusterConfiguration (..),
+    LogIndex,
+    Role (..),
+    Snapshot (..),
+    SnapshotMetadata (..),
+    StateMachineStep (..),
+    Term,
+  )
+import Distributed.Consensus.Raft.Domain.Admin (AdminCommand (..), AdminRequest)
+import Distributed.Consensus.Raft.Domain.Client (ClientRequest, ClientResult (..))
+import Distributed.Consensus.Raft.Implementation
+  ( AppendEntries (..),
+    AppendEntriesResult (..),
+    ClusterMembershipError (..),
+    ClusterMembershipRequest (..),
+    ClusterMembershipResult (..),
+    Command (..),
+    Event (..),
+    Implementation (..),
+    InstallSnapshot (..),
+    InstallSnapshotResult (..),
+    LogEntry (..),
+    Networking (..),
+    RPC (..),
+    RPCResult (..),
+    RaftTrace (..),
+  )
+import qualified Distributed.Consensus.Raft.Implementation as Impl
+import Distributed.Consensus.Raft.Log (Lookup (..), lastLogIndex, (!?))
+import qualified Distributed.Consensus.Raft.Log as Log
+import Distributed.Consensus.Raft.Messaging (Request (..), Response (..))
+import Distributed.Consensus.Raft.Transformer
+  ( Config (..),
+    RaftT,
+    acceptClientRequests,
+    appendLogEntries,
+    applyCommittedEntries,
+    applyLogEntries,
+    applySnapshot,
+    becomeCandidate,
+    becomeFollower,
+    checkElection,
+    clusterConfiguration,
+    commandLog,
+    commitIndex,
+    configuration,
+    currentLeader,
+    currentSnapshot,
+    dequeueEvent,
+    enqueueEvent,
+    eventQueue,
+    exitLock,
+    implementation,
+    isClusterMember,
+    leaderStepDown,
+    nextIndex,
+    peers,
+    pendingClusterMembershipChanges,
+    pendingReadLeaderAcknowledgedBy,
+    pendingReadRequests,
+    pendingReadSequenceNum,
+    persistSnapshot,
+    proposeClusterMembership,
+    resetElectionTimer,
+    resetHeartBeatTimer,
+    restoreState,
+    role,
+    runSend,
+    self,
+    sendAppendEntriesTo,
+    serveReadOnlyQueries,
+    setCommitIndex,
+    term,
+    trace,
+    updateMatchIndex,
+    updateTerm,
+    voteFor,
+    votedFor,
+    yesVotes,
+  )
+import qualified Distributed.Consensus.Raft.Transformer as Transformer
+import Lens.Micro.Platform (at, filtered, traversed, use, view, (%=), (.=))
+
+server ::
+  ( Ord node,
+    MonadMask m,
+    MonadFork m,
+    MonadMVar m,
+    MonadAsync m,
+    MonadDelay m
+  ) =>
+  RaftT entry node result state m ()
+server = do
+  impl <- view implementation
+  queue <- view eventQueue
+
+  t1 <- lift $ async $ receiveRPCsThread impl queue
+  t2 <- lift $ async $ receiveRPCResultsThread impl queue
+  t3 <- lift $ async $ receiveClientRequestsThread impl queue
+  t4 <- lift $ async $ receiveAdminRequestsThread impl queue
+  let receiveLoops = [t1, t2, t3, t4]
+  for_ receiveLoops (lift . link)
+
+  -- There are some initialization steps which require the configuration.
+  -- Instead of coupling 'initialRaftState' with the configuration,
+  -- we perform some initialization here.
+  ps <- peers
+  nextIndex .= Map.fromSet (const 0) ps
+
+  restoreState
+
+  -- NonMembers don't participate in elections, but also don't hold elections
+  -- for themselves. This prevents a NonMember from electing itself as the leader
+  -- of its own trivial cluster
+  r <- use role
+  unless (r == NonMember) $ do
+    resetHeartBeatTimer
+    resetElectionTimer
+
+  let loop = do
+        dequeueEvent >>= \case
+          Nothing -> pure () -- shutdown
+          Just ev -> do
+            trace (`EventReceived` ev)
+            handleEvent ev
+            loop
+
+  loop
+
+  for_ receiveLoops (lift . cancel)
+  trace GracefulShutdown
+  where
+    receiveRPCsThread impl queue = do
+      labelThisThread "receiceRPCs"
+      let recv = impl.networking.receiveRPC
+      forever $
+        recv
+          >>= atomically . writeTQueue queue . EventRPC
+    receiveRPCResultsThread impl queue = do
+      labelThisThread "receiceRPCResults"
+      let recv = impl.networking.receiveRPCResult
+      forever $
+        recv >>= atomically . writeTQueue queue . EventRPCResult
+    receiveClientRequestsThread impl queue = do
+      labelThisThread "receiceClientRequests"
+      let recv = impl.networking.receiveClientRequests
+      forever $ recv >>= atomically . writeTQueue queue . EventIncomingClientRequest
+    receiveAdminRequestsThread impl queue = do
+      labelThisThread "receiveAdminRequests"
+      let recv = impl.networking.receiveAdminRequest
+      forever $
+        recv >>= atomically . writeTQueue queue . EventAdminRequest
+
+handleEvent ::
+  ( Ord node,
+    MonadDelay m,
+    MonadMask m,
+    MonadFork m,
+    MonadAsync m,
+    MonadMVar m
+  ) =>
+  Event entry node result state -> RaftT entry node result state m ()
+handleEvent EventElectionTimeout = do
+  r <- use role
+  member <- isClusterMember
+  when (member && r /= Leader) $ do
+    when (r == Candidate) $ do
+      trace SplitElection
+    unless (r == Candidate) $ do
+      trace ElectionTriggered
+    becomeCandidate
+handleEvent EventHeartBeatTimeout = Transformer.sendHeartbeat
+handleEvent (EventIncomingClientRequest requests) = do
+  -- There may be other client requests queued up. We can increase throughput by flushing them all
+  queue <- view eventQueue
+  let go =
+        tryPeekTQueue queue >>= \case
+          Just (EventIncomingClientRequest !otherRequests) -> readTQueue queue *> ((otherRequests :) <$> go)
+          _ -> pure []
+
+  queued <- lift (atomically go)
+  handleClientRequest (NonEmpty.appendList requests (concatMap NonEmpty.toList queued))
+handleEvent (EventRPC (RequestVote candidateTerm candidateNode candidateLastLogEntry candidateLastLogEntryTerm)) =
+  handleRequestVote candidateTerm candidateNode candidateLastLogEntry candidateLastLogEntryTerm
+handleEvent (EventRPC (AE appendEntries)) = handleAppendEntries appendEntries
+handleEvent (EventRPC (IS installSnapshot)) = handleInstallSnapshot installSnapshot
+handleEvent (EventRPC (CM clusterMembershipRequest)) = handleClusterMembershipRequest clusterMembershipRequest
+handleEvent (EventRPCResult (RequestVoteResult voter voterTerm votedForUs)) =
+  handleRequestVoteResult voter voterTerm votedForUs
+handleEvent (EventRPCResult (AER appendEntriesResult)) = handleAppendEntriesResult appendEntriesResult
+handleEvent (EventRPCResult (ISR installSnapshotResult)) = handleInstallSnapshotResult installSnapshotResult
+handleEvent (EventRPCResult (CMR clusterMembershipResult)) = handleClusterMembershipResult clusterMembershipResult
+handleEvent (EventAdminRequest adminCommand) = handleAdminRequest adminCommand
+handleEvent (EventSnapshotPersisted snapshot) = applySnapshot snapshot
+
+handleClientRequest ::
+  ( Ord node,
+    MonadMVar m,
+    MonadAsync m,
+    MonadMask m,
+    MonadFork m,
+    MonadDelay m
+  ) =>
+  NonEmpty (ClientRequest entry node) -> RaftT entry node result state m ()
+handleClientRequest requests = do
+  mLeaderId <- use currentLeader
+  use role >>= \case
+    NonMember ->
+      runSend $ do
+        for_ requests $ \(MkRequest reqId clientId _) ->
+          Transformer.sendClientResponse clientId (MkResponse reqId mLeaderId NotLeader)
+    Candidate ->
+      runSend $
+        for_ requests $ \(MkRequest reqId clientId _) ->
+          Transformer.sendClientResponse clientId (MkResponse reqId mLeaderId NotLeader)
+    Follower ->
+      runSend $
+        for_ requests $ \(MkRequest reqId clientId _) ->
+          Transformer.sendClientResponse clientId (MkResponse reqId mLeaderId NotLeader)
+    Leader -> do
+      reqIds <- acceptClientRequests requests
+      let commands = NonEmpty.zipWith Command reqIds (requestPayload <$> requests)
+      -- TODO: trace in separate thread?
+      for_ commands $ \(Command rid entry) ->
+        trace (\ctx -> CommandReceived ctx rid entry)
+
+      -- Special case: if this leader is the only node in the cluster,
+      -- we can service read-only request immediately
+      serveReadOnlyQueries
+
+      -- Not all commands need to be appended to the log
+      sm <- view implementation <&> stateMachine
+      let isNotReadOnly (Command _ entry) = case sm entry of
+            Read _ -> False
+            Transition _ -> True
+
+      ourTerm <- use term
+      traverse_
+        (appendLogEntries . fmap (\c -> (ourTerm, LogEntryCommand c)))
+        (NonEmpty.nonEmpty $ NonEmpty.filter isNotReadOnly commands)
+
+handleAppendEntries ::
+  ( Ord node,
+    MonadMVar m,
+    MonadAsync m,
+    MonadMask m,
+    MonadFork m,
+    MonadDelay m
+  ) =>
+  AppendEntries entry node ->
+  RaftT entry node result state m ()
+handleAppendEntries (AppendEntries leaderTerm leaderNode prevLogIndex previousLogTerm newEntries leaderCommitIndex leaderReadOnlySeqNum) = do
+  termComparison <- handleTermNumber leaderTerm
+  when (termComparison /= LT) (becomeFollower (Just leaderNode))
+
+  ourRole <- use role
+  -- It's quite important for non-followers to append entries
+  -- since any node can be thrust into the leader role
+  -- due to a leader crash
+  unless (ourRole == Leader) $ do
+    when (termComparison == EQ || termComparison == GT) resetElectionTimer
+
+    -- Consistency check
+    entries <- use commandLog
+    let (SnapshotMetadata lastIncludedIndex lastIncludedTerm) = Log.lSnapshotMetadata entries
+        logIsConsistent =
+          (prevLogIndex >= lastIncludedIndex)
+            && case entries !? prevLogIndex of
+              NotFound -> prevLogIndex == 0 && previousLogTerm == lastIncludedTerm
+              LogIndexInSnapshot _ ->
+                -- By snapshot construction, indices
+                prevLogIndex == lastIncludedIndex && previousLogTerm == lastIncludedTerm
+              Found (!entryTerm, _, _) -> entryTerm == previousLogTerm
+
+    ourTerm <- use term
+    s <- self
+    if leaderTerm < ourTerm || not logIsConsistent
+      then do
+        let ourLastIndex = Log.lastLogIndex entries
+        runSend $
+          Transformer.sendRPCResult
+            leaderNode
+            ( AER
+                ( AppendEntriesResult
+                    { aerCurrentTerm = ourTerm,
+                      aerNode = s,
+                      aerMatch = False,
+                      aerNewEntryLogIndex = ourLastIndex,
+                      aerReadOnlySeqNum = leaderReadOnlySeqNum
+                    }
+                )
+            )
+      else do
+        -- TODO: unify the logic below with
+        --       appendLogEntries
+        impl <- view implementation
+        (firstNewIndex, entriesToAppend) <- case Log.reconcile entries prevLogIndex newEntries of
+          Log.Coherent appendFrom toAppend -> pure (appendFrom, toAppend)
+          Log.Incoherent truncateFrom toAppend -> do
+            commandLog %= (`Log.keepEntriesUpTo` pred truncateFrom)
+            lift $ impl.persistence.truncateLogEntriesFrom s truncateFrom
+            pure (truncateFrom, toAppend)
+
+        -- It's a little awkward to have to determine the log indices
+        -- of new entries before they're assigned.
+        -- Not clear if there's a better way to do this,
+        -- given that persistence must happen first
+        let batchToWrite = zipWith (\ix (t, e) -> (t, ix, e)) [firstNewIndex ..] (toList entriesToAppend)
+        unless (null batchToWrite) $
+          lift $
+            -- Note that the content of 'batchToWrite' may override
+            -- previously-persisted records. 'writeLogEntry' should
+            -- support that
+            impl.persistence.writeLogEntry s batchToWrite
+        for_ batchToWrite $ \(t, ix, entry) ->
+          trace (\ctx -> LogEntryAppended ctx t ix entry)
+
+        commandLog %= (`Log.extend` entriesToAppend)
+
+        newLastEntry <- use commandLog <&> Log.lastLogIndex
+        trace (`LastLogIndexChangedTo` newLastEntry)
+
+        let lastVerifiedIndex = prevLogIndex + fromIntegral (length newEntries)
+
+        runSend $
+          Transformer.sendRPCResult
+            leaderNode
+            ( AER
+                ( AppendEntriesResult
+                    { aerCurrentTerm = ourTerm,
+                      aerNode = s,
+                      aerMatch = True,
+                      aerNewEntryLogIndex = lastVerifiedIndex,
+                      aerReadOnlySeqNum = leaderReadOnlySeqNum
+                    }
+                )
+            )
+        ourCommitIndex <- use commitIndex
+        let newCommitIndex = min leaderCommitIndex lastVerifiedIndex
+        when (newCommitIndex > ourCommitIndex) $ do
+          setCommitIndex newCommitIndex
+          trace (`CommitIndexIncreasedTo` newCommitIndex)
+          -- A follower takes the commit index from the leader; it must not
+          -- try to re-derive it from match indices, which it doesn't track.
+          applyCommittedEntries
+
+handleAppendEntriesResult ::
+  ( Ord node,
+    MonadMVar m,
+    MonadAsync m,
+    MonadMask m,
+    MonadFork m,
+    MonadDelay m
+  ) =>
+  AppendEntriesResult node result ->
+  RaftT entry node result state m ()
+handleAppendEntriesResult (AppendEntriesResult responderTerm responderNode responderSuccess responderLogIndex responderReadOnlySeqNum) = do
+  termComp <- handleTermNumber responderTerm
+  ourRole <- use role
+  when (ourRole == Leader && termComp == EQ) $
+    if responderSuccess
+      then do
+        updateMatchIndex responderNode responderLogIndex
+
+        pendingReadRequests
+          . traversed
+          -- Only if the responder is responding to a recent-enough 'ReadOnlySequenceNum'
+          -- should the responder count in the quorum for a read-only request.
+          --
+          -- This prevents, for example, a heartbeat that was already in-flight when a read-only
+          -- query was received from counting
+          . filtered ((<= responderReadOnlySeqNum) . view pendingReadSequenceNum)
+          . pendingReadLeaderAcknowledgedBy
+          %= Set.insert responderNode
+
+        serveReadOnlyQueries
+
+        applyLogEntries
+      else do
+        lastIx <- use commandLog <&> lastLogIndex
+        -- Note that it's possible for a responder to not be known (we don't have its key
+        -- in `nextIndex`) due to in-flight cluster configuration changes. This is why
+        -- we have a fallback value (`fromMaybe`)
+        currentResponderIndex <- use (nextIndex . at responderNode) <&> fromMaybe (succ lastIx)
+
+        let backedOff =
+              max
+                -- minimum valid log index is 0, so the minimum next index
+                -- must be `succ 0`
+                (succ 0)
+                ( min
+                    (pred currentResponderIndex)
+                    (succ responderLogIndex)
+                )
+        nextIndex . at responderNode .= Just backedOff
+        when (backedOff < currentResponderIndex) $
+          sendAppendEntriesTo responderNode
+
+-- | How to handle a term provided by another node. If this term
+-- is larger than ours, this means that we must clear some state from
+-- the previous term, and possibly transition to a new role.
+--
+-- Returns the comparison between the incoming term and our term before this function ran.
+-- Therefore, a return value of 'GT' means that the term provided as input was larger than
+-- our term.
+handleTermNumber ::
+  ( MonadMVar m,
+    MonadDelay m,
+    MonadFork m,
+    MonadMask m,
+    MonadAsync m
+  ) =>
+  Term -> RaftT entry node result state m Ordering
+handleTermNumber newTerm = do
+  (currTerm, _newTerm) <- updateTerm (const newTerm)
+
+  when (newTerm > currTerm) $ do
+    voteFor Nothing
+    use role >>= \case
+      Leader -> becomeFollower Nothing
+      Candidate -> becomeFollower Nothing
+      Follower -> pure ()
+      NonMember -> pure ()
+
+  pure $ compare newTerm currTerm
+
+handleRequestVote ::
+  ( Ord node,
+    MonadMVar m,
+    MonadAsync m,
+    MonadMask m,
+    MonadFork m,
+    MonadDelay m
+  ) =>
+  Term ->
+  node ->
+  LogIndex ->
+  Term ->
+  RaftT entry node result state m ()
+handleRequestVote candidateTerm candidateNode candidateLastLogIndex candidateLastLogIndexTerm = do
+  termOrdering <- handleTermNumber candidateTerm
+  ourTerm <- use term
+  s <- self
+  trace (\ctx -> VoteRequestedBy ctx candidateTerm candidateNode)
+  case termOrdering of
+    LT -> runSend $ Transformer.sendRPCResult candidateNode (RequestVoteResult s ourTerm False)
+    _ -> do
+      when (termOrdering == GT) $ leaderStepDown Nothing
+      mAlreadyVoted <- use votedFor
+      entries <- use commandLog
+      case mAlreadyVoted of
+        -- We haven't voted yet
+        Nothing ->
+          if candidateTerm >= ourTerm
+            && (candidateLastLogIndexTerm, candidateLastLogIndex) >= Log.lastLogInfo entries
+            then do
+              voteFor (Just candidateNode)
+              grantVote ourTerm
+              trace (\ctx -> VotedFor ctx candidateTerm candidateNode)
+            else do
+              runSend $ Transformer.sendRPCResult candidateNode (RequestVoteResult s ourTerm False)
+        -- We already voted for this candidate
+        Just someCandidate
+          | someCandidate == candidateNode ->
+              runSend $ Transformer.sendRPCResult candidateNode (RequestVoteResult s ourTerm True)
+        -- We already voted, for another candidate
+        Just _ ->
+          runSend $ Transformer.sendRPCResult candidateNode (RequestVoteResult s ourTerm False)
+  where
+    grantVote ourTerm = do
+      s <- self
+      runSend $ Transformer.sendRPCResult candidateNode (RequestVoteResult s ourTerm True)
+      r <- use role
+      when (r == Follower) resetElectionTimer
+
+handleRequestVoteResult ::
+  ( Ord node,
+    MonadAsync m,
+    MonadMask m,
+    MonadFork m,
+    MonadMVar m,
+    MonadDelay m
+  ) =>
+  node -> Term -> Bool -> RaftT entry node result state m ()
+handleRequestVoteResult voter voterTerm votedForUs = do
+  handleTermNumber voterTerm >>= \case
+    LT -> pure () -- Vote request for an old term
+    _ -> do
+      ourRole <- use role
+      when (ourRole == Candidate) $
+        if votedForUs
+          then do
+            trace (`VoteGrantedFrom` voter)
+            yesVotes %= Set.insert voter
+            checkElection
+          else
+            trace (`VoteDeniedFrom` voter)
+
+handleInstallSnapshot ::
+  (MonadMVar m, MonadAsync m, MonadMask m, MonadFork m, MonadDelay m) =>
+  InstallSnapshot node state -> RaftT entry node result state m ()
+handleInstallSnapshot (InstallSnapshot leaderTerm leaderNode snapshot) =
+  handleTermNumber leaderTerm >>= \case
+    LT ->
+      -- old term
+      -- We reply so that the other node hopefully learns of our newer term
+      -- and transitions to follower
+      InstallSnapshotResult
+        <$> use term
+        <*> (view configuration <&> nodeId)
+        <*> pure (sMetadata snapshot)
+        >>= runSend . Transformer.sendRPCResult leaderNode . ISR
+    _ -> do
+      becomeFollower (Just leaderNode)
+      persistSnapshot snapshot
+      InstallSnapshotResult
+        <$> use term
+        <*> (view configuration <&> nodeId)
+        <*> pure (sMetadata snapshot)
+        >>= runSend . Transformer.sendRPCResult leaderNode . ISR
+
+handleInstallSnapshotResult ::
+  ( Ord node,
+    MonadMVar m,
+    MonadAsync m,
+    MonadMask m,
+    MonadFork m,
+    MonadDelay m
+  ) =>
+  InstallSnapshotResult node -> RaftT entry node result state m ()
+handleInstallSnapshotResult (InstallSnapshotResult responderTerm responderNode (SnapshotMetadata lastIncludedIndex _)) = do
+  termComp <- handleTermNumber responderTerm
+  ourRole <- use role
+  when (ourRole == Leader && termComp == EQ) $ do
+    updateMatchIndex responderNode lastIncludedIndex
+    -- The only reason to send an 'InstallSnapshot' RPC
+    -- (and thus get a result) is because a node has gotten behind
+    -- in its entries. With the snapshot installed, we're free to
+    -- send the rest of the logs
+    sendAppendEntriesTo responderNode
+
+handleClusterMembershipRequest ::
+  ( Ord node,
+    MonadMVar m,
+    MonadAsync m,
+    MonadMask m,
+    MonadFork m,
+    MonadDelay m
+  ) =>
+  ClusterMembershipRequest node -> RaftT entry node result state m ()
+handleClusterMembershipRequest request = do
+  let (requester, resultCtor) = case request of
+        ClusterMembershipJoinRequest r -> (r, ClusterMembershipJoinResult)
+        ClusterMembershipLeaveRequest r -> (r, ClusterMembershipLeaveResult)
+  use role >>= \case
+    NonMember -> self >>= \s -> runSend $ Transformer.sendRPCResult requester (CMR (resultCtor (Left (NoKnownLeader s))))
+    Candidate -> self >>= \s -> runSend $ Transformer.sendRPCResult requester (CMR (resultCtor (Left (NoKnownLeader s))))
+    Follower ->
+      use currentLeader >>= \case
+        Nothing -> do
+          s <- self
+          runSend $ Transformer.sendRPCResult requester (CMR (resultCtor (Left (NoKnownLeader s))))
+        Just leader -> runSend $ Transformer.sendRPC leader (CM request) -- forward to leader
+    Leader -> do
+      s <- self
+      pending <- pendingClusterMembershipChanges
+      let -- Whether the committed configuration already says what the requester
+          -- is asking for.
+          alreadySettled cluster = case request of
+            ClusterMembershipJoinRequest r -> r `Set.member` cluster
+            ClusterMembershipLeaveRequest r -> r `Set.notMember` cluster
+
+          ongoing = runSend $ Transformer.sendRPCResult requester (CMR (resultCtor (Left (OngoingClusterMembershipChange s))))
+      use clusterConfiguration >>= \case
+        -- By design, we cannot handle more than one membership request
+        -- at a time. The requester must retry later.
+        --
+        -- Note the early return: previously this answered with an error and
+        -- then went on to initiate a second, concurrent change anyway.
+        Joint {} -> ongoing
+        Simple cluster
+          | pending -> ongoing
+          -- We distinguish between a request that succeeds the first
+          -- and subsequent times to better track executions
+          | alreadySettled cluster -> do
+              trace (`MembershipChangeAlreadySettled` requester)
+              runSend $ Transformer.sendRPCResult requester (CMR (resultCtor (Right s)))
+          | otherwise -> do
+              trace MembershipChangeInitiated
+              runSend $ Transformer.sendRPCResult requester (CMR (resultCtor (Right s)))
+
+              case request of
+                ClusterMembershipJoinRequest _ -> do
+                  -- By definition, a node that just joined
+                  -- needs to catch up with a snapshot.
+                  ( InstallSnapshot
+                      <$> use term
+                      <*> self
+                      <*> currentSnapshot
+                    )
+                    >>= runSend . Transformer.sendRPC requester . IS
+                  proposeClusterMembership (Joint cluster (Set.insert requester cluster))
+                ClusterMembershipLeaveRequest _ ->
+                  proposeClusterMembership (Joint cluster (Set.delete requester cluster))
+
+handleClusterMembershipResult ::
+  ( MonadDelay m,
+    MonadMVar m,
+    MonadFork m,
+    MonadMask m,
+    MonadAsync m
+  ) =>
+  ClusterMembershipResult node -> RaftT entry node result state m ()
+handleClusterMembershipResult = \case
+  ClusterMembershipJoinResult (Right leaderId) -> do
+    becomeFollower (Just leaderId)
+    trace JoinedCluster -- TODO: is this the right moment to trace this? Probably should wait until log is replicated
+  ClusterMembershipJoinResult (Left _) -> pure ()
+  ClusterMembershipLeaveResult (Right _) -> pure () -- Nothing to do until log entry is applied
+  ClusterMembershipLeaveResult (Left _) -> pure ()
+
+handleAdminRequest :: (MonadMVar m, MonadAsync m) => AdminRequest node -> RaftT entry node result state m ()
+handleAdminRequest req@(MkRequest reqId adminId command) = do
+  trace (`AdminRequestReceived` req)
+  mLeaderId <- use currentLeader
+  case command of
+    ShutDown -> do
+      view exitLock >>= lift . (`putMVar` ())
+      runSend $ Transformer.sendAdminResponse adminId (MkResponse reqId mLeaderId Admin.ShutdownInitiated)
+    GetClusterConfiguration ->
+      use role >>= \case
+        Leader -> use clusterConfiguration >>= \conf -> runSend $ Transformer.sendAdminResponse adminId (MkResponse reqId mLeaderId (Admin.ClusterConfigurationIs conf))
+        _ -> runSend $ Transformer.sendAdminResponse adminId (MkResponse reqId mLeaderId (Admin.NotLeader mLeaderId))
+    (JoinCluster target) -> do
+      self >>= runSend . Transformer.sendRPC target . CM . ClusterMembershipJoinRequest
+      runSend $ Transformer.sendAdminResponse adminId (MkResponse reqId mLeaderId Admin.JoinInitiated)
+    LeaveCluster -> do
+      s <- self
+      enqueueEvent (EventRPC (CM (ClusterMembershipLeaveRequest s)))
+      runSend $ Transformer.sendAdminResponse adminId (MkResponse reqId mLeaderId Admin.LeaveInitiated)
diff --git a/src/Distributed/Consensus/Raft/Client.hs b/src/Distributed/Consensus/Raft/Client.hs
new file mode 100644
--- /dev/null
+++ b/src/Distributed/Consensus/Raft/Client.hs
@@ -0,0 +1,301 @@
+{-# LANGUAGE DerivingStrategies #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE RankNTypes #-}
+{-# LANGUAGE TemplateHaskell #-}
+
+-- |
+-- Module:      $module
+-- Copyright:   (c) Laurent P. René de Cotret
+-- License:     BSD 3-Clause
+--
+-- Interface to interact with a Raft cluster as a client.
+--
+-- === How to use this module
+--
+-- The key piece of information to use this module effectively is that
+-- interactions are done in /sessions/. A client starts a session
+-- by calling 'withClientSession', and all requests will have to originate
+-- from within.
+--
+-- Try to keep sessions open as long as possible -- ideally for the length
+-- of a client's lifetime.
+--
+-- Clients create requests using 'newRequest', and send those requests
+-- to a cluster via 'sendClientRequest'. Interacting with a cluster may
+-- require retrying or redirecting requests; reuse requests as much as possible.
+-- To keep the implementation flexible, retrying and redirecting is something
+-- you need to do yourself.
+module Distributed.Consensus.Raft.Client
+  ( -- * Interface
+    withClientSession,
+    RaftClientT,
+
+    -- ** Creating requests
+    newRequest,
+
+    -- ** Sending requests
+    sendClientRequest,
+    ClientError (..),
+
+    -- ** Configuration
+    ClientImplementation (..),
+
+    -- ** Session information
+    clientSession,
+
+    -- * Other exports
+    SessionId,
+    sessionId,
+    SequenceNum,
+    Microseconds,
+    ClientRequestId (..),
+    ClientRequest,
+    Request (..),
+    ClientResponse,
+    Response (..),
+    ClientResult (..),
+  )
+where
+
+import Control.Concurrent.Class.MonadSTM
+  ( MonadSTM,
+    TMVar,
+    TVar,
+    atomically,
+    check,
+    newEmptyTMVar,
+    newTVarIO,
+    orElse,
+    readTMVar,
+    readTVar,
+    tryPutTMVar,
+    writeTVar,
+  )
+import Control.Monad (void)
+import Control.Monad.Class.MonadAsync (MonadAsync, link, withAsync)
+import Control.Monad.Class.MonadFork (MonadFork)
+import Control.Monad.Class.MonadThrow (MonadMask)
+import Control.Monad.Class.MonadTimer (MonadTimer, registerDelay)
+import Control.Monad.Trans.Class (MonadTrans, lift)
+import Control.Monad.Trans.Reader (ReaderT (runReaderT), asks)
+import Data.Map.Strict (Map)
+import qualified Data.Map.Strict as Map
+import Data.Semigroup (Max (..))
+import Distributed.Consensus.Raft.Domain.Client
+  ( ClientRequest,
+    ClientRequestId (..),
+    ClientResponse,
+    ClientResult (..),
+    SequenceNum,
+    SessionId,
+    sessionId,
+  )
+import Distributed.Consensus.Raft.Messaging (Request (..), Response (..))
+import Distributed.Consensus.Raft.Timer (Microseconds)
+import Lens.Micro.Platform (makeLenses)
+
+-- | Client monad transformer to make requests to a Raft cluster.
+--
+-- The only way to execute an action of type 'RaftClientT' is with
+-- 'withClientSession'.
+newtype RaftClientT entry node result m a
+  = MkRaftClientT (ReaderT (RaftClientEnv entry node result m) m a)
+  deriving (Functor, Applicative, Monad)
+
+instance MonadTrans (RaftClientT entry node result) where
+  lift = MkRaftClientT . lift
+
+-- | Implementation of communication between a client and a cluster.
+--
+-- See the @raft-consensus-distributed-process@ package for an example
+-- implementation for the Cloud Haskell ecosystem.
+data ClientImplementation entry node result m = ClientImplementation
+  { sendRequest :: node -> ClientRequest entry node -> m (),
+    receiveResponse :: m (ClientResponse node result),
+    -- | Generate a globally-unique session ID.
+    generateSessionId :: node -> m SessionId
+  }
+
+-- | Open a client session, and run an action with a runner for that session.
+--
+-- It is safe to use the runner from several threads concurrently.
+--
+-- The typical way you would use 'withClientSession' is like so:
+--
+-- @
+-- 'withClientSession' nodeId $ \\run -> do
+--     req <- run ('newRequest' someRequest)
+--
+--     let go serverNode =
+--             run ('sendClientRequest' 1000000 serverNode req) >>= \case
+--                Left ('Redirect' otherServerNode) -> go otherServerNode
+--                Left _ -> go serverNode -- infinite retries
+--                Right resp -> pure resp
+--
+--     go lastKnownLeader
+-- @
+--
+-- In practice, 'withClientSession' is usually run in its own thread,
+-- and requests are sent over to that client thread using e.g. a 'TQueue'.
+withClientSession ::
+  ( MonadAsync m,
+    MonadFork m,
+    MonadMask m
+  ) =>
+  -- | self identification
+  node ->
+  ClientImplementation entry node result m ->
+  ((forall a. RaftClientT entry node result m a -> m a) -> m b) ->
+  m b
+withClientSession self impl withSession = do
+  nRId <- newTVarIO 0
+  lAck <- newTVarIO Nothing
+  mbox <- newTVarIO mempty
+  sessId <- generateSessionId impl self
+  let env =
+        MkRaftClientEnv
+          { node = self,
+            currentSessionId = sessId,
+            nextRequestId = nRId,
+            latestAcknowledgement = lAck,
+            implementation = impl,
+            mailbox = mbox
+          }
+      recvLoop = do
+        receiveResponse impl >>= \resp -> do
+          let reqId = responseRequestId resp
+          atomically $ do
+            box <- readTVar mbox
+            case Map.lookup reqId box of
+              Nothing -> pure ()
+              -- Using 'tryPutTMVar' here in case a response is duplicated
+              Just var -> void $ tryPutTMVar var resp
+          recvLoop
+
+  withAsync recvLoop $ \thread -> do
+    link thread
+    withSession (\(MkRaftClientT f) -> runReaderT f env)
+
+data RaftClientEnv entry node result m
+  = MkRaftClientEnv
+  { node :: !node,
+    currentSessionId :: !SessionId,
+    nextRequestId :: !(TVar m SequenceNum),
+    latestAcknowledgement :: !(TVar m (Maybe (Max SequenceNum))),
+    implementation :: ClientImplementation entry node result m,
+    mailbox :: TVar m (Map ClientRequestId (TMVar m (ClientResponse node result)))
+  }
+
+makeLenses ''ClientImplementation
+
+-- | Possible client errors
+data ClientError entry node
+  = -- | The client should make the request to another node
+    Redirect node
+  | Timeout
+  | NoKnownLeader
+  deriving (Eq, Show, Ord)
+
+-- | Read the current session ID. This helper can be useful if you need
+-- to pin information to the current client
+clientSession :: (Monad m) => RaftClientT entry node result m SessionId
+clientSession = MkRaftClientT $ asks currentSessionId
+
+newRequest :: (MonadSTM m) => entry -> RaftClientT entry node result m (ClientRequest entry node)
+newRequest entry = do
+  (seqNumVar, sessId, self) <- MkRaftClientT $ asks ((,,) <$> nextRequestId <*> currentSessionId <*> node)
+  reqId <- lift $ atomically $ do
+    nextSeqNum <- readTVar seqNumVar
+    writeTVar seqNumVar (succ nextSeqNum)
+    pure $ MkClientRequestId sessId nextSeqNum
+
+  pure $ MkRequest reqId self entry
+
+-- | Send a request to a Raft cluster.
+--
+-- The user must take care to handle the possible 'ClientError's, and be
+-- ready to retry.
+--
+-- First, it is quite likely that the server will redirect requests
+-- via @'Redirect' otherServer@. 'request' does not follow that redirect,
+-- as you may want to control delays and retries.
+--
+-- Second, there is an unlikely, but real, possibility that the server
+-- replies with 'NoKnownLeader'. In this case, you should try two things:
+--
+-- * Retry the request, which may resolve itself
+-- * If retrying doesn't work, you should try to send the request to another server.
+--   It may be beneficial to keep a memory of all servers ever contacted for this
+--   particular purpose.
+--
+-- It is perfectly safe, and encouraged, to send separate requests in
+-- separate threads. However, you should call 'withClientSession' only once.
+sendClientRequest ::
+  (MonadTimer m) =>
+  -- | Maximum time to wait for a response.
+  Microseconds ->
+  node ->
+  ClientRequest entry node ->
+  RaftClientT
+    entry
+    node
+    result
+    m
+    ( Either
+        (ClientError entry node)
+        (node, result)
+    )
+sendClientRequest timeout lastKnownLeader req@(MkRequest reqId _ _) = do
+  send <- MkRaftClientT $ asks (sendRequest . implementation)
+  mbox <- MkRaftClientT $ asks mailbox
+  ackVar <- MkRaftClientT $ asks latestAcknowledgement
+  lift
+    ( do
+        resultVar <- atomically $ do
+          mbox' <- readTVar mbox
+          resultVar <- newEmptyTMVar
+          -- TODO: bracket to deregister in case of an exception
+          writeTVar mbox (Map.insert reqId resultVar mbox')
+
+          pure resultVar
+
+        expired <- registerDelay (fromIntegral timeout)
+        send lastKnownLeader req
+
+        -- TODO: clean up mailbox entry for req ID
+        --       regardless of success (possibly using 'bracket')
+        atomically
+          ( ( do
+                resp <- readTMVar resultVar
+                mbox' <- readTVar mbox
+                lAck <- readTVar ackVar
+                writeTVar mbox (Map.delete reqId mbox')
+
+                let MkClientRequestId _ respSeqNum = responseRequestId resp
+                    watermark = Max respSeqNum
+                writeTVar
+                  ackVar
+                  ( maybe
+                      (Just watermark)
+                      (Just . mappend watermark)
+                      lAck
+                  )
+
+                pure (Just resp)
+            )
+              `orElse` ( do
+                           readTVar expired >>= check
+                           readTVar mbox >>= writeTVar mbox . Map.delete reqId
+                           pure Nothing
+                       )
+          )
+    )
+    >>= \case
+      Nothing -> pure $ Left Timeout
+      Just (MkResponse _ (Just actualLeaderId) NotLeader) -> pure $ Left $ Redirect actualLeaderId
+      Just (MkResponse _ (Just leader) (Success result)) -> pure $ Right (leader, result)
+      -- TODO: what if leader is @Nothing@ but response is `Success`??
+      Just (MkResponse _ Nothing _) -> pure $ Left NoKnownLeader
diff --git a/src/Distributed/Consensus/Raft/Domain.hs b/src/Distributed/Consensus/Raft/Domain.hs
new file mode 100644
--- /dev/null
+++ b/src/Distributed/Consensus/Raft/Domain.hs
@@ -0,0 +1,158 @@
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE DerivingStrategies #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+
+module Distributed.Consensus.Raft.Domain
+  ( Term,
+    Role (..),
+    ClusterConfiguration (..),
+    allNodes,
+    hasQuorum,
+    LogIndex,
+
+    -- * Sessions and sequences
+    SessionId,
+    sessionId,
+    SequenceNum,
+
+    -- ** Read-only sequences
+    ReadOnlySequenceNum,
+
+    -- * Snapshots
+    Snapshot (..),
+    SnapshotMetadata (..),
+
+    -- * State machine
+    StateMachineStep (..),
+    runStateMachineStep,
+  )
+where
+
+import Data.Binary (Binary)
+import Data.Set (Set)
+import qualified Data.Set as Set
+import Data.Word (Word64)
+import GHC.Generics (Generic)
+import System.Random (Uniform)
+
+-- | Election term
+newtype Term = Term Word64
+  deriving stock (Generic, Eq, Ord, Show, Read)
+  deriving newtype (Real, Binary, Enum, Num, Integral)
+
+data Role
+  = Leader
+  | Follower
+  | Candidate
+  | -- | Special states for nodes that aren't members of a cluster. This
+    -- doesn't let them participate in elections and change their terms
+    NonMember
+  deriving (Eq, Show, Ord, Enum, Generic, Bounded)
+
+instance Binary Role
+
+-- | Represents the membership of a cluster.
+--
+-- In normal operations, a cluster is composed of a particular set of nodes.
+-- During membership changes, the cluster is in two overlapping states;
+-- one state with all of the previous members, and another state with a different, possibly
+-- overlapping, set of members.
+data ClusterConfiguration node
+  = Simple (Set node)
+  | Joint (Set node) (Set node)
+  deriving (Eq, Ord, Generic, Show)
+
+instance (Binary node) => Binary (ClusterConfiguration node)
+
+-- | Uniquely identifies a session between a cluster and a client or admin, globally. This
+-- value should be generated at random.
+data SessionId = MkSessionId Word64 Word64
+  deriving (Eq, Show, Ord, Generic)
+
+instance Binary SessionId
+
+instance Uniform SessionId
+
+sessionId :: Word64 -> Word64 -> SessionId
+sessionId = MkSessionId
+
+-- | Incrementing sequence number for every client or admin request
+-- in the same session.
+newtype SequenceNum = MkSequenceNum Word64
+  deriving stock (Eq, Ord)
+  deriving newtype (Show, Real, Num, Enum, Bounded, Integral, Binary)
+
+-- | Incrementing counter for each round of approval for a read-only query.
+newtype ReadOnlySequenceNum = MkReadOnlySequenceNum Word64
+  deriving stock (Eq, Ord)
+  deriving newtype (Show, Real, Num, Enum, Bounded, Integral, Binary)
+
+allNodes :: (Ord node) => ClusterConfiguration node -> Set node
+allNodes (Simple nodes) = nodes
+allNodes (Joint nodes1 nodes2) = nodes1 `Set.union` nodes2
+
+-- | Whether a set of nodes has a quorum based on current cluster configuration.
+--
+-- In the case of a joint cluster configuration, a quorum is achieved if
+-- a quorum is achieves within both configurations
+--
+-- >>> :set -XOverloadedLists
+-- >>> conf = Joint ['A', 'B', 'C'] ['A', 'C', 'D']
+-- >>> hasQuorum conf ['A']
+-- False
+-- >>> hasQuorum conf ['A', 'B']
+-- False
+-- >>> hasQuorum conf ['A', 'C']
+-- True
+-- >>> hasQuorum (Simple ['A']) ['A']
+-- True
+hasQuorum :: (Ord node) => ClusterConfiguration node -> Set node -> Bool
+hasQuorum (Simple members) votes = Set.size (Set.intersection members votes) > Set.size members `div` 2
+hasQuorum (Joint members1 members2) votes =
+  hasQuorum (Simple members1) votes
+    && hasQuorum (Simple members2) votes
+
+-- | 'LogIndex' is an absolute position within the 'Log'.
+--
+-- Note that the 'Log' may not have the elements associated with a given
+-- 'LogIndex' due to compaction.
+newtype LogIndex = LogIndex Word64
+  deriving stock (Generic, Eq, Ord, Show)
+  deriving newtype (Real, Enum, Num, Binary, Integral)
+
+data SnapshotMetadata = SnapshotMetadata
+  { smLastIncludedIndex :: !LogIndex,
+    smLastIncludedTerm :: !Term
+  }
+  deriving (Eq, Ord, Show, Generic)
+
+instance Binary SnapshotMetadata
+
+data Snapshot node state = Snapshot
+  { sMetadata :: !SnapshotMetadata,
+    sData :: !state,
+    sCluster :: !(ClusterConfiguration node)
+  }
+  deriving (Eq, Ord, Show, Generic)
+
+instance (Binary node, Binary state) => Binary (Snapshot node state)
+
+-- | A state machine entry results in a step which can either read the state ('Read')
+-- or mutate the state ('Write').
+--
+-- The distinction is important because reading from the state can be optimized
+-- differently than a mutation.
+--
+-- >>> data CounterOp = ReadCounter | Increment | Decrement
+-- >>> :{ let stateMachine = \case
+--    ReadCounter -> Read id
+--    Increment -> Transition $ \st -> (succ st, succ st)
+--    Decrement -> Transition $ \st -> (pred st, pred st)
+-- :}
+data StateMachineStep result state
+  = Read (state -> result)
+  | Transition (state -> (state, result))
+
+runStateMachineStep :: StateMachineStep result state -> state -> (state, result)
+runStateMachineStep (Read runRead) st = (st, runRead st)
+runStateMachineStep (Transition runTrans) st = runTrans st
diff --git a/src/Distributed/Consensus/Raft/Domain/Admin.hs b/src/Distributed/Consensus/Raft/Domain/Admin.hs
new file mode 100644
--- /dev/null
+++ b/src/Distributed/Consensus/Raft/Domain/Admin.hs
@@ -0,0 +1,52 @@
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE DerivingStrategies #-}
+
+module Distributed.Consensus.Raft.Domain.Admin
+  ( AdminRequestId (..),
+    AdminRequest,
+    AdminResponse,
+    AdminCommand (..),
+    AdminCommandResult (..),
+  )
+where
+
+import Data.Binary (Binary)
+import Distributed.Consensus.Raft.Domain (ClusterConfiguration, SequenceNum, SessionId)
+import Distributed.Consensus.Raft.Messaging (Request (..), Response (..))
+import GHC.Generics (Generic)
+
+data AdminCommand node
+  = JoinCluster
+      -- | Target node
+      node
+  | LeaveCluster
+  | -- | Ask a node for the cluster configuration it has committed.
+    GetClusterConfiguration
+  | ShutDown
+  deriving (Eq, Show, Ord, Generic)
+
+instance (Binary node) => Binary (AdminCommand node)
+
+data AdminRequestId
+  = MkAdminRequestId
+      SessionId
+      SequenceNum
+  deriving stock (Generic, Eq, Ord, Show)
+
+instance Binary AdminRequestId
+
+type AdminRequest node = Request AdminRequestId node (AdminCommand node)
+
+data AdminCommandResult node
+  = JoinInitiated
+  | LeaveInitiated
+  | ShutdownInitiated
+  | ClusterConfigurationIs !(ClusterConfiguration node)
+  | -- | The contacted node isn't the leader. The 'Maybe' contains the
+    -- | node believed to be the current leader, if known.
+    NotLeader !(Maybe node)
+  deriving (Eq, Show, Generic)
+
+instance (Binary node) => Binary (AdminCommandResult node)
+
+type AdminResponse node = Response AdminRequestId node (AdminCommandResult node)
diff --git a/src/Distributed/Consensus/Raft/Domain/Client.hs b/src/Distributed/Consensus/Raft/Domain/Client.hs
new file mode 100644
--- /dev/null
+++ b/src/Distributed/Consensus/Raft/Domain/Client.hs
@@ -0,0 +1,39 @@
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE DerivingStrategies #-}
+
+module Distributed.Consensus.Raft.Domain.Client
+  ( SessionId,
+    sessionId,
+    SequenceNum,
+    ClientRequestId (..),
+    ClientRequest,
+    ClientResponse,
+    ClientResult (..),
+  )
+where
+
+import Data.Binary (Binary)
+import Distributed.Consensus.Raft.Domain (SequenceNum, SessionId, sessionId)
+import Distributed.Consensus.Raft.Messaging (Request (..), Response (..))
+import GHC.Generics (Generic)
+
+-- | Client-sourced request ID. This allows to correlate multiple client
+-- side-responses.
+data ClientRequestId
+  = MkClientRequestId
+      SessionId
+      SequenceNum
+  deriving stock (Generic, Eq, Ord, Show)
+
+instance Binary ClientRequestId
+
+type ClientRequest entry node = Request ClientRequestId node entry
+
+data ClientResult result
+  = Success !result
+  | NotLeader
+  deriving (Eq, Show, Generic)
+
+instance (Binary result) => Binary (ClientResult result)
+
+type ClientResponse node result = Response ClientRequestId node (ClientResult result)
diff --git a/src/Distributed/Consensus/Raft/Implementation.hs b/src/Distributed/Consensus/Raft/Implementation.hs
new file mode 100644
--- /dev/null
+++ b/src/Distributed/Consensus/Raft/Implementation.hs
@@ -0,0 +1,367 @@
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE DerivingStrategies #-}
+{-# LANGUAGE ExistentialQuantification #-}
+
+module Distributed.Consensus.Raft.Implementation
+  ( -- * Protocol implementation
+    Implementation (..),
+    Networking (..),
+    Persistence (..),
+
+    -- ** Helpers
+    nullTracer,
+    ephemeralPersistence,
+
+    -- * Types
+    LogEntry (..),
+    Command (..),
+    CommandResponse (..),
+    AppendEntries (..),
+    AppendEntriesResult (..),
+    InstallSnapshot (..),
+    InstallSnapshotResult (..),
+    ClusterMembershipRequest (..),
+    ClusterMembershipResult (..),
+    ClusterMembershipError (..),
+    AdminRequest,
+    Event (..),
+    RPC (..),
+    RPCResult (..),
+    EventContext (..),
+    RaftTrace (..),
+  )
+where
+
+import Data.Binary (Binary)
+import Data.List.NonEmpty (NonEmpty)
+import Data.Sequence (Seq)
+import Distributed.Consensus.Raft.Domain (ClusterConfiguration (..), LogIndex, ReadOnlySequenceNum, Snapshot, SnapshotMetadata, StateMachineStep, Term)
+import Distributed.Consensus.Raft.Domain.Admin (AdminRequest, AdminResponse)
+import Distributed.Consensus.Raft.Domain.Client (ClientRequest, ClientRequestId, ClientResponse, ClientResult)
+import Distributed.Consensus.Raft.Log (Log)
+import GHC.Generics (Generic)
+
+-- | Implementation of the Raft protocol.
+--
+-- There are four categories of things that need an implementation:
+--
+-- * Persistence: how are values persisted durably?
+-- * State mechine: given an @entry@, how does the @state@ evolve?
+-- * Networking: how are nodes communicating?
+-- * Tracing: how is debugging information traced?
+data Implementation entry node result state m = Implementation
+  { persistence :: Persistence entry node state m,
+    stateMachine :: entry -> StateMachineStep result state,
+    networking :: Networking entry node result state m,
+    -- | Event tracer. This is mostly useful for testing and debugging.
+    --
+    -- You can turn tracing off using 'nullTracer'
+    tracer :: RaftTrace entry node result state -> m ()
+  }
+
+-- | Ignore 'RaftTrace' events
+nullTracer :: (Applicative m) => RaftTrace entry node result state -> m ()
+nullTracer _ = pure ()
+
+-- | Networking implementation.
+--
+-- See @raft-consensus-distributed-process@ for an implementation that fits
+-- in the Cloud Haskell ecosystem.
+data Networking entry node result state m = Networking
+  { -- | Send a remote procedure call to another Raft node.
+    sendRPC :: node -> RPC entry node state -> m (),
+    -- | Send the result of a remote procedure call to another Raft node.
+    sendRPCResult :: node -> RPCResult node result -> m (),
+    -- | Send a response to a client.
+    sendClientResponse :: node -> ClientResponse node result -> m (),
+    -- | Send a response to an administrator.
+    sendAdminResponse :: node -> AdminResponse node -> m (),
+    -- | Receive a remote procedure call.
+    --
+    -- At the type implies, this call should /block/ until a message is ready.
+    receiveRPC :: m (RPC entry node state),
+    -- | Receive the result of a remote procedure call.
+    --
+    -- At the type implies, this call should /block/ until a message is ready.
+    receiveRPCResult :: m (RPCResult node result),
+    -- | Receive client requests.
+    --
+    -- This call should block until at least one request is available. If
+    -- your software stack allows for it, queueing requests allows
+    -- for pipelined processing which is much more efficient.
+    receiveClientRequests :: m (NonEmpty (ClientRequest entry node)),
+    -- | Receive a request from an administrator.
+    --
+    -- At the type implies, this call should /block/ until a message is ready.
+    receiveAdminRequest :: m (AdminRequest node)
+  }
+
+-- | Persistence implementation.
+--
+-- This is broken out into its own type so that it can be provided cleanly by
+-- third-party packages. For example, see the @raft-consensus-wal@ package.
+data Persistence entry node state m = Persistence
+  { -- | Read log entries, starting from and including, a given 'LogIndex'
+    --
+    -- Implementations should
+    readLogEntriesFrom :: node -> LogIndex -> m [(Term, LogIndex, LogEntry entry node)],
+    -- | Write log entries durably.
+    --
+    -- Note that the writes need to support overwriting. In the normal course
+    -- of running a Raft node, the log may need to be updated. This means that
+    -- a previously seen '(Term, LogIndex)' may be written again. Only the most recently
+    -- written entry should be surfaced by 'readLogEntriesFrom'.
+    --
+    -- This function also receives the node identification (of type @node@), which
+    -- allows to persist data in a shared location for multiple nodes
+    -- (e.g. in a remote database)
+    writeLogEntry :: node -> [(Term, LogIndex, LogEntry entry node)] -> m (),
+    -- Truncate log entries starting, and including, the provided log index.
+    --
+    -- Note that not all storage technologies support truncation. For example,
+    -- write-ahead logs cannot implement truncation. However, the goal is that
+    -- any "truncation" results in entries with this 'LogIndex' and later ones
+    -- to not be returned by 'readLogEntriesFrom'.
+    truncateLogEntriesFrom :: node -> LogIndex -> m (),
+    -- | Read the last persisted term. In case this is not known (for example, on a
+    -- first boot), then the term should be @0@.
+    readTerm :: node -> m Term,
+    -- | Write the current term durably.
+    --
+    -- This function also receives the node identification (of type @node@), which
+    -- allows to persist data in a shared location for multiple nodes
+    -- (e.g. in a remote database)
+    writeTerm :: node -> Term -> m (),
+    -- | Read the node for which /this/ node has voted, for a given term, if known.
+    readVotedFor :: node -> Term -> m (Maybe node),
+    -- | Write this node's vote for the current term, durably.
+    --
+    -- This function also receives the node identification (of type @node@), which
+    -- allows to persist data in a shared location for multiple nodes
+    -- (e.g. in a remote database)
+    writeVotedFor :: node -> Term -> Maybe node -> m (),
+    -- | Read the most recent snapshot, if one exists.
+    readSnapshot :: node -> m (Maybe (Snapshot node state)),
+    -- | Write a snapshot durably.
+    --
+    -- This function also receives the node identification (of type @node@), which
+    -- allows to persist data in a shared location for multiple nodes
+    -- (e.g. in a remote database)
+    writeSnapshot :: node -> Snapshot node state -> m (),
+    -- | Read the last persisted commit index. A default value of @0@ should be
+    -- returned if the commit index was never persisted
+    readCommitIndex :: node -> m LogIndex,
+    -- | Write the node's commit index. Note that this does
+    -- not need to be durable; storing the commit index is a startup performance
+    -- optimization.
+    writeCommitIndex :: node -> LogIndex -> m ()
+  }
+
+-- | This 'Persistence' implementation does absolutely nothing.
+--
+-- Only use this for testing. If a node crashes and restarts without memory
+-- of its state, it may vote again leading to multiple leaders in a single
+-- cluster, which would be catastrophic.
+--
+-- An alternative would be for a node's identity (the 'node' type variable)
+-- to never be re-used. In this case, it would be perfectly fine to restart
+-- with an empty state.
+ephemeralPersistence :: (Applicative m) => Persistence entry node state m
+ephemeralPersistence =
+  Persistence
+    { readLogEntriesFrom = \_ _ -> pure [],
+      writeLogEntry = \_ _ -> pure (),
+      truncateLogEntriesFrom = \_ _ -> pure (),
+      readTerm = \_ -> pure 0,
+      writeTerm = \_ _ -> pure (),
+      readVotedFor = \_ _ -> pure Nothing,
+      writeVotedFor = \_ _ _ -> pure (),
+      readSnapshot = \_ -> pure Nothing,
+      writeSnapshot = \_ _ -> pure (),
+      readCommitIndex = \_ -> pure 0,
+      writeCommitIndex = \_ _ -> pure ()
+    }
+
+-- | A 'Command' comes from clients
+data Command entry
+  = Command
+      !ClientRequestId
+      !entry
+  deriving (Eq, Show, Ord, Generic)
+
+instance (Binary entry) => Binary (Command entry)
+
+-- | A 'LogEntry' is anything which gets persisted
+-- in the replicated log. This includes client commands,
+-- byt also leadership changes (which are no-op entries)
+-- and cluster membership changes.
+data LogEntry entry node
+  = LogEntryCommand (Command entry)
+  | LogEntryLeaderChange
+  | LogEntryMembershipChange (ClusterConfiguration node)
+  deriving (Eq, Show, Ord, Generic)
+
+instance (Binary node, Binary entry) => Binary (LogEntry entry node)
+
+data CommandResponse node result
+  = MkCommandResponse
+      !result
+      !ClientRequestId
+  deriving (Eq, Show, Ord, Generic)
+
+instance (Binary node, Binary result) => Binary (CommandResponse node result)
+
+data AppendEntries entry node = AppendEntries
+  { aeLeaderTerm :: !Term,
+    aeLeaderNode :: !node,
+    aePreviousLogIndex :: !LogIndex,
+    aePreviousLogTerm :: !Term,
+    aeEntries :: !(Seq (Term, LogEntry entry node)),
+    aeCommitIndex :: !LogIndex,
+    aeReadOnlySeqNum :: !ReadOnlySequenceNum
+  }
+  deriving (Eq, Show, Ord, Generic)
+
+instance (Binary node, Binary entry) => Binary (AppendEntries entry node)
+
+data AppendEntriesResult node result = AppendEntriesResult
+  { aerCurrentTerm :: !Term,
+    aerNode :: !node,
+    aerMatch :: !Bool,
+    aerNewEntryLogIndex :: !LogIndex,
+    aerReadOnlySeqNum :: !ReadOnlySequenceNum
+  }
+  deriving (Eq, Ord, Show, Generic)
+
+instance (Binary node, Binary result) => Binary (AppendEntriesResult node result)
+
+data InstallSnapshot node state = InstallSnapshot
+  { isLeaderTerm :: !Term,
+    isLeaderNode :: !node,
+    isSnapshot :: !(Snapshot node state)
+  }
+  deriving (Eq, Ord, Show, Generic)
+
+instance (Binary node, Binary state) => Binary (InstallSnapshot node state)
+
+data InstallSnapshotResult node = InstallSnapshotResult
+  { isrTerm :: !Term,
+    isrNode :: !node,
+    isrSnapshotMetadata :: !SnapshotMetadata
+  }
+  deriving (Eq, Ord, Show, Generic)
+
+instance (Binary node) => Binary (InstallSnapshotResult node)
+
+data ClusterMembershipRequest node
+  = ClusterMembershipJoinRequest node
+  | ClusterMembershipLeaveRequest node
+  deriving (Eq, Ord, Show, Generic)
+
+instance (Binary node) => Binary (ClusterMembershipRequest node)
+
+data ClusterMembershipError node
+  = -- | carries the node that replied, not the leader
+    NoKnownLeader node
+  | OngoingClusterMembershipChange node
+  deriving (Eq, Show, Ord, Generic)
+
+instance (Binary node) => Binary (ClusterMembershipError node)
+
+data ClusterMembershipResult node
+  = ClusterMembershipJoinResult (Either (ClusterMembershipError node) node)
+  | ClusterMembershipLeaveResult (Either (ClusterMembershipError node) node)
+  deriving (Eq, Ord, Show, Generic)
+
+instance (Binary node) => Binary (ClusterMembershipResult node)
+
+data RPC entry node state
+  = AE (AppendEntries entry node)
+  | IS (InstallSnapshot node state)
+  | CM (ClusterMembershipRequest node)
+  | RequestVote
+      -- | Candidate term
+      Term
+      -- | Identification of the candidate requesting vote
+      node
+      -- | Index of candidate's last log entry
+      LogIndex
+      -- | Term of candidate's last log entry
+      Term
+  deriving (Eq, Ord, Show, Generic) -- For easy derivation of de/serialization
+
+instance (Binary node, Binary entry, Binary state) => Binary (RPC entry node state)
+
+data RPCResult node result
+  = AER (AppendEntriesResult node result)
+  | ISR (InstallSnapshotResult node)
+  | CMR (ClusterMembershipResult node)
+  | RequestVoteResult
+      -- | Voter node
+      node
+      -- | Current term, for leader to update itself
+      Term
+      -- | Whether vote was granted
+      Bool
+  deriving (Eq, Ord, Show, Generic) -- For easy derivation of de/serialization
+
+instance (Binary node, Binary result) => Binary (RPCResult node result)
+
+data Event entry node result state
+  = EventElectionTimeout
+  | EventHeartBeatTimeout
+  | EventIncomingClientRequest (NonEmpty (ClientRequest entry node))
+  | EventRPC (RPC entry node state)
+  | EventRPCResult (RPCResult node result)
+  | EventAdminRequest (AdminRequest node)
+  | EventSnapshotPersisted (Snapshot node state)
+  deriving (Eq, Show)
+
+data EventContext node
+  = EventContext !Term !node
+  deriving (Eq)
+
+instance (Show node) => Show (EventContext node) where
+  show (EventContext term node) = "[Term=" <> show term <> " | node=" <> show node <> "]"
+
+data RaftTrace entry node result state
+  = StateRestored (EventContext node) (Maybe node) (Log (LogEntry entry node) node)
+  | LeaderElected (EventContext node)
+  | VotedFor (EventContext node) !Term node
+  | VoteRequestedBy (EventContext node) !Term node
+  | VoteGrantedFrom (EventContext node) node
+  | VoteDeniedFrom (EventContext node) node
+  | BecameCandidate (EventContext node)
+  | BecameFollower (EventContext node)
+  | BecameNonMember (EventContext node)
+  | EventReceived (EventContext node) (Event entry node result state)
+  | SplitElection (EventContext node)
+  | ElectionTriggered (EventContext node)
+  | -- | Command received by the leader node. If the command needs to be redirected
+    --    to another node, this event is not emitted
+    -- All Commands should have the same request ID
+    CommandReceived (EventContext node) !ClientRequestId entry
+  | CommandResultResponded (EventContext node) (CommandResponse node (ClientResult result))
+  | -- TODO: better traching of new joining/leaving cluster
+    MembershipChangeInitiated (EventContext node)
+  | MembershipChangeCompleted (EventContext node)
+  | AdminRequestReceived (EventContext node) (AdminRequest node)
+  | JoinedCluster (EventContext node)
+  | LeftCluster (EventContext node)
+  | CommitIndexIncreasedTo (EventContext node) !LogIndex
+  | LogEntryAppended (EventContext node) !Term !LogIndex (LogEntry entry node)
+  | ReadOnlyQueryQueued (EventContext node) !LogIndex entry
+  | LastLogIndexChangedTo (EventContext node) !LogIndex
+  | LogEntryApplied (EventContext node) !Term !LogIndex entry
+  | MembershipChangeApplied (EventContext node) (ClusterConfiguration node)
+  | -- | A leader was asked for a membership change that its committed
+    -- configuration already satisfies, so it did nothing.
+    MembershipChangeAlreadySettled (EventContext node) node
+  | LastAppliedIndexIncreasedTo (EventContext node) !LogIndex
+  | SnapshotApplied (EventContext node) !SnapshotMetadata
+  | GracefulShutdown (EventContext node)
+  | -- | The following event is emitted by the fault injector
+    -- in deterministic simulation tests. Users should not rely
+    -- on tracing this event in production.
+    Crashed node
+  deriving (Eq, Show)
diff --git a/src/Distributed/Consensus/Raft/Log.hs b/src/Distributed/Consensus/Raft/Log.hs
new file mode 100644
--- /dev/null
+++ b/src/Distributed/Consensus/Raft/Log.hs
@@ -0,0 +1,188 @@
+{-# LANGUAGE BangPatterns #-}
+{-# LANGUAGE DeriveFunctor #-}
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE DerivingStrategies #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+
+module Distributed.Consensus.Raft.Log
+  ( -- * Log
+    Log (lEntries, lSnapshotMetadata),
+    buildLog,
+    newLog,
+
+    -- ** Reading the log
+    logEntries,
+    lastLogIndex,
+    lastLogInfo,
+    (!?),
+    Lookup (..),
+    relativeIndex,
+    absoluteIndex,
+
+    -- ** Modifying the log
+    append,
+    extend,
+    keepEntriesUpTo,
+    applySnapshot,
+
+    -- ** Log reconciliation
+    Reconciliation (..),
+    reconcile,
+  )
+where
+
+import Data.Maybe (fromMaybe)
+import Data.Sequence (Seq)
+import qualified Data.Sequence as Seq
+import Distributed.Consensus.Raft.Domain (LogIndex, SnapshotMetadata (..), Term)
+import GHC.Generics (Generic)
+
+-- | 'RelativeIndex' is a relative position within the 'Log'. It is
+-- specified with respect to the snapshot.
+newtype RelativeLogIndex = RelativeLogIndex LogIndex
+  deriving stock (Generic, Eq, Ord, Show)
+  deriving newtype (Real, Enum, Num, Integral)
+
+data Log entry node = Log
+  { lEntries :: !(Seq (Term, LogIndex, entry)),
+    lSnapshotMetadata :: !SnapshotMetadata,
+    -- Metadata stored for performance reasons
+    lLastIndex :: !LogIndex,
+    lLastTerm :: !Term
+  }
+  deriving (Eq, Show)
+
+buildLog :: Seq (Term, LogIndex, entry) -> Maybe SnapshotMetadata -> Log entry node
+buildLog entries mMetadata =
+  let metadata = fromMaybe (SnapshotMetadata 0 0) mMetadata
+   in Log
+        { lEntries = entries,
+          lSnapshotMetadata = metadata,
+          lLastIndex = smLastIncludedIndex metadata + fromIntegral (length entries),
+          lLastTerm = case Seq.viewr entries of
+            Seq.EmptyR -> smLastIncludedTerm metadata
+            _ Seq.:> (lastTerm, _, _) -> lastTerm
+        }
+
+relativeIndex :: Log entry node -> LogIndex -> RelativeLogIndex
+relativeIndex (Log _ ((SnapshotMetadata !lastIx _)) _ _) !ix = RelativeLogIndex $ ix - lastIx
+{-# INLINEABLE relativeIndex #-}
+
+absoluteIndex :: Log entry node -> RelativeLogIndex -> LogIndex
+absoluteIndex (Log _ ((SnapshotMetadata !lastIx _)) _ _) (RelativeLogIndex !ix) = ix + lastIx
+{-# INLINEABLE absoluteIndex #-}
+
+append :: Log entry node -> (Term, entry) -> Log entry node
+Log es sn lst _ `append` (!term, !newEntry) = Log (es Seq.|> (term, succ lst, newEntry)) sn (succ lst) term
+{-# INLINEABLE append #-}
+
+extend :: Log entry node -> Seq (Term, entry) -> Log entry node
+Log es sn lst lt `extend` !newEntries =
+  Log
+    (es Seq.>< Seq.zipWith (\ix (t, e) -> (t, ix, e)) indices newEntries)
+    sn
+    (lst + fromIntegral (Seq.length newEntries))
+    newLastTerm
+  where
+    indices = Seq.fromList $ take (length newEntries) [succ lst ..]
+    newLastTerm = case Seq.viewr newEntries of
+      Seq.EmptyR -> lt
+      (_ Seq.:> (t, _)) -> t
+{-# INLINEABLE extend #-}
+
+-- | Truncate the log so that it retains only the entries up to, and including,
+-- the absolute index @ix@.
+keepEntriesUpTo :: Log entry node -> LogIndex -> Log entry node
+log'@(Log es sn@((SnapshotMetadata lastIx lastSnapshotTerm)) lst _) `keepEntriesUpTo` ix
+  -- Nothing to truncate
+  | ix >= lst = log'
+  | ix <= lastIx = Log Seq.empty sn lastIx lastSnapshotTerm
+  | otherwise =
+      let kept = Seq.take (fromIntegral $ relativeIndex log' ix) es
+          term = case Seq.viewr kept of
+            Seq.EmptyR -> lastSnapshotTerm
+            _ Seq.:> (keptLastTerm, _, _) -> keptLastTerm
+       in Log kept sn ix term
+
+data Reconciliation entry
+  = -- | There is no conflict, although there may be missing entries
+    Coherent
+      -- | Start appending from this index
+      !LogIndex
+      -- | Entries which aren't in the log yet
+      !(Seq (Term, entry))
+  | -- | There is a conflict that needs to be resolved
+    Incoherent
+      -- | Truncate from, and including, this index
+      !LogIndex
+      -- | Entries that aren't in the log yet
+      !(Seq (Term, entry))
+
+-- | Reconcile an existing 'Log' with new entries starting from a previous log index.
+reconcile :: Log entry node -> LogIndex -> Seq (Term, entry) -> Reconciliation entry
+reconcile log' prevIx = go (succ prevIx)
+  where
+    go !ix remaining = case Seq.viewl remaining of
+      Seq.EmptyL -> Coherent ix Seq.empty
+      (t, _) Seq.:< rest -> case log' !? ix of
+        LogIndexInSnapshot _ -> go (succ ix) rest
+        Found (existingTerm, _, _)
+          | existingTerm == t -> go (succ ix) rest
+          | otherwise -> Incoherent ix remaining
+        NotFound -> Coherent ix remaining
+
+data Lookup a
+  = LogIndexInSnapshot SnapshotMetadata
+  | Found !a
+  | NotFound
+  deriving (Functor)
+
+(!?) :: Log entry node -> LogIndex -> Lookup (Term, LogIndex, entry)
+(!?) log'@(Log es meta@(SnapshotMetadata lst _) _ _) ix
+  | ix <= lst = LogIndexInSnapshot meta
+  | otherwise =
+      maybe NotFound Found $
+        -- Seq.!? is zero-based indexing, but the Raft log
+        -- is traditionally one-based indexing, hence the -1 offset
+        es Seq.!? (fromIntegral (relativeIndex log' ix) - 1)
+
+logEntries :: Log entry node -> Seq (Term, LogIndex, entry)
+logEntries = lEntries
+
+newLog :: Log entry node
+newLog = buildLog mempty Nothing
+
+lastLogIndex :: Log entry node -> LogIndex
+lastLogIndex = lLastIndex
+{-# INLINE lastLogIndex #-}
+
+lastLogInfo :: Log entry node -> (Term, LogIndex)
+lastLogInfo (Log _ _ lix lt) = (lt, lix)
+{-# INLINE lastLogInfo #-}
+
+-- | Apply a snapshot to the log if it advances the log index only.
+-- Otherwise, this function does nothing.
+applySnapshot :: SnapshotMetadata -> Log entry node -> Log entry node
+applySnapshot newSnapshot@((SnapshotMetadata absoluteLastIndex lastSnapshotTerm)) log'
+  | absoluteLastIndex <= smLastIncludedIndex (lSnapshotMetadata log') = log'
+  | otherwise = case log' !? absoluteLastIndex of
+      Found (entryTerm, _, _)
+        -- An invariant is that if the log's entry at the same tip index
+        -- as the snapshot has the same term, then the rest of the log is also
+        -- contained in the snapshot. We can truncate the log
+        --
+        -- Otherwise, the log must be entirely replaced by the snapshot
+        | entryTerm == lastSnapshotTerm ->
+            let relativeLastIndex = relativeIndex log' absoluteLastIndex
+             in Log
+                  (Seq.drop (fromIntegral relativeLastIndex) (lEntries log'))
+                  newSnapshot
+                  (lLastIndex log')
+                  (lLastTerm log')
+      _ ->
+        Log
+          { lEntries = mempty,
+            lSnapshotMetadata = newSnapshot,
+            lLastIndex = absoluteLastIndex,
+            lLastTerm = lastSnapshotTerm
+          }
diff --git a/src/Distributed/Consensus/Raft/Messaging.hs b/src/Distributed/Consensus/Raft/Messaging.hs
new file mode 100644
--- /dev/null
+++ b/src/Distributed/Consensus/Raft/Messaging.hs
@@ -0,0 +1,34 @@
+{-# LANGUAGE DeriveGeneric #-}
+
+module Distributed.Consensus.Raft.Messaging
+  ( Request (..),
+    Response (..),
+  )
+where
+
+import Data.Binary (Binary)
+import GHC.Generics (Generic)
+
+-- | Request incoming to the Raft cluster.
+--
+-- This is an envelope that collects things that any request
+-- needs to be processed end-to-end.
+data Request id node payload
+  = MkRequest
+  { requestId :: !id,
+    requestOriginator :: !node,
+    requestPayload :: !payload
+  }
+  deriving (Eq, Show, Generic)
+
+instance (Binary id, Binary node, Binary payload) => Binary (Request id node payload)
+
+data Response id node payload
+  = MkResponse
+  { responseRequestId :: !id,
+    responseClusterLeader :: !(Maybe node),
+    responsePayload :: !payload
+  }
+  deriving (Eq, Show, Generic)
+
+instance (Binary id, Binary node, Binary payload) => Binary (Response id node payload)
diff --git a/src/Distributed/Consensus/Raft/Timer.hs b/src/Distributed/Consensus/Raft/Timer.hs
new file mode 100644
--- /dev/null
+++ b/src/Distributed/Consensus/Raft/Timer.hs
@@ -0,0 +1,70 @@
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE DerivingVia #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+
+module Distributed.Consensus.Raft.Timer
+  ( Microseconds (Microseconds),
+    Timer,
+    newTimer,
+    resetTimer,
+    cancelTimer,
+  )
+where
+
+import Control.Concurrent.Class.MonadMVar (MVar, MonadMVar, newEmptyMVar, putMVar, tryTakeMVar)
+import Control.Monad.Class.MonadAsync (Async, MonadAsync, async, cancel, link)
+import Control.Monad.Class.MonadFork (MonadFork)
+import Control.Monad.Class.MonadThrow (MonadMask)
+import Control.Monad.Class.MonadTimer (MonadDelay, threadDelay)
+import Data.Foldable (traverse_)
+import Data.Int (Int32)
+import GHC.Generics (Generic)
+import System.Random (UniformRange)
+
+-- | A 'Timer' is an action which is run after some amount of time.
+--
+-- When a 'Timer' is created with 'newTimer', the action is registered
+-- but the timer is inactive. Use 'resetTimer' to launch the coundown.
+-- Once the countdown finishes, the action is executed.
+--
+-- You can reset the timer by using 'resetTimer' again.
+--
+-- If the action throws an exception, the exception will be thrown
+-- in the thread that created the timer with 'newTimer'.
+data Timer m = MkTimer
+  { _action :: m (),
+    -- Normally we would use an IORef (Maybe _) here,
+    -- but 'io-classes' doesn't support IORef
+    _handle :: MVar m (Async m ())
+  }
+
+-- | Duration of time in microseconds.
+--
+-- The canonical way to build a 'Microsecond' value is to
+-- either use a literal integer, or via 'fromIntegral':
+--
+-- >>> 1000000 :: Microseconds
+-- Microseconds 1000000
+-- >>> fromIntegral (1000000 :: Int) :: Microseconds
+-- Microseconds 1000000
+newtype Microseconds = Microseconds Int32
+  deriving stock (Eq, Ord, Show, Generic)
+  deriving newtype (Real, Enum, Num, Integral, Bounded)
+
+instance UniformRange Microseconds -- via Generic
+
+newTimer :: (MonadMVar m) => m () -> m (Timer m)
+newTimer a = MkTimer a <$> newEmptyMVar
+
+resetTimer ::
+  (MonadAsync m, MonadMask m, MonadFork m, MonadMVar m, MonadDelay m) =>
+  Microseconds -> Timer m -> m ()
+resetTimer (Microseconds delay) timer@(MkTimer a h) = do
+  cancelTimer timer
+  thread <- async (threadDelay (fromIntegral delay) >> a)
+  link thread -- can't be too careful
+  putMVar h thread
+
+cancelTimer :: (MonadMVar m, MonadAsync m) => Timer m -> m ()
+cancelTimer (MkTimer _ h) =
+  tryTakeMVar h >>= traverse_ cancel
diff --git a/src/Distributed/Consensus/Raft/Transformer.hs b/src/Distributed/Consensus/Raft/Transformer.hs
new file mode 100644
--- /dev/null
+++ b/src/Distributed/Consensus/Raft/Transformer.hs
@@ -0,0 +1,916 @@
+{-# LANGUAGE BangPatterns #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE TupleSections #-}
+
+module Distributed.Consensus.Raft.Transformer
+  ( module Distributed.Consensus.Raft.Transformer.Definition,
+
+    -- * Cluster nodes
+    self,
+    peers,
+    clusterNodes,
+
+    -- * Capabilities
+    dequeueEvent,
+    enqueueEvent,
+    sendRPC,
+    sendRPCConcurrently,
+    sendRPCResult,
+    sendClientResponse,
+    sendAdminResponse,
+    whenRole,
+    sendHeartbeat,
+    sendAppendEntriesTo,
+    setCommitIndex,
+    voteFor,
+    applyLogEntries,
+    applyCommittedEntries,
+    nextElectionTimeout,
+    updateTerm,
+    updateMatchIndex,
+    trace,
+    acceptClientRequests,
+    persistSnapshot,
+    applySnapshot,
+    isClusterMember,
+    leaderStepDown,
+    serveReadOnlyQueries,
+    currentSnapshot,
+    appendLogEntries,
+    restoreState,
+    pendingClusterMembershipChanges,
+    proposeClusterMembership,
+
+    -- ** Roles
+    becomeFollower,
+    becomeNonMember,
+    becomeLeader,
+    becomeCandidate,
+
+    -- ** Elections
+    checkElection,
+
+    -- ** Timers
+    resetHeartBeatTimer,
+    resetElectionTimer,
+  )
+where
+
+import Control.Concurrent.Class.MonadMVar (MonadMVar, takeMVar)
+import Control.Concurrent.Class.MonadSTM (atomically, readTQueue, writeTQueue)
+import Control.Monad (unless, void, when)
+import Control.Monad.Class.MonadAsync (MonadAsync, async, mapConcurrently_, race)
+import Control.Monad.Class.MonadFork (MonadFork)
+import Control.Monad.Class.MonadSTM (MonadSTM)
+import Control.Monad.Class.MonadThrow (MonadMask)
+import Control.Monad.Class.MonadTimer (MonadDelay)
+import Control.Monad.Trans.Class (lift)
+import Data.Foldable (for_, traverse_)
+import qualified Data.Foldable as Foldable
+import Data.Function ((&))
+import Data.Functor (($>), (<&>))
+import Data.List.NonEmpty (NonEmpty)
+import qualified Data.List.NonEmpty as NonEmpty
+import qualified Data.Map.Strict as Map
+import Data.Maybe (fromJust, isJust)
+import Data.Sequence (ViewR (..))
+import qualified Data.Sequence as Seq
+import Data.Set (Set)
+import qualified Data.Set as Set
+import Data.Traversable (for)
+import Distributed.Consensus.Raft.Domain
+  ( ClusterConfiguration (..),
+    LogIndex,
+    Role (..),
+    Snapshot (..),
+    SnapshotMetadata (..),
+    StateMachineStep (..),
+    Term,
+    allNodes,
+    hasQuorum,
+  )
+import Distributed.Consensus.Raft.Domain.Admin (AdminResponse)
+import Distributed.Consensus.Raft.Domain.Client (ClientRequest, ClientRequestId, ClientResponse, ClientResult (..))
+import Distributed.Consensus.Raft.Implementation hiding (sendAdminResponse, sendClientResponse, sendRPC, sendRPCResult)
+import qualified Distributed.Consensus.Raft.Implementation as Impl
+import Distributed.Consensus.Raft.Log (Lookup (..), absoluteIndex, logEntries)
+import qualified Distributed.Consensus.Raft.Log as Log
+import Distributed.Consensus.Raft.Messaging (Request (..), Response (..))
+import Distributed.Consensus.Raft.Timer (Microseconds, resetTimer)
+import Distributed.Consensus.Raft.Transformer.Definition
+import Lens.Micro.Platform
+  ( assign,
+    at,
+    use,
+    view,
+    (%=),
+    (+=),
+    (.=),
+    (^.),
+    _1,
+    _3,
+  )
+import System.Random (uniformR)
+
+-- | Node identifier
+self :: (Monad m) => RaftT entry node result state m node
+self = view configuration <&> nodeId
+
+-- | All nodes in the cluster, except self
+peers :: (Monad m, Ord node) => RaftT entry node result state m (Set node)
+peers = do
+  s <- self
+  use clusterConfiguration <&> Set.delete s . allNodes
+
+-- | All nodes in the cluster; both 'self' and 'peers'.
+clusterNodes :: (Monad m, Ord node) => RaftT entry node result state m (Set node)
+clusterNodes = use clusterConfiguration <&> allNodes
+
+-- | Returns @Nothing@ if the exit lock has been unlocked, in which case
+-- the server should shut down
+dequeueEvent :: (MonadMVar m, MonadAsync m) => RaftT entry node result state m (Maybe (Event entry node result state))
+dequeueEvent = do
+  queue <- view eventQueue
+  lock <- view exitLock
+  lift (race (takeMVar lock) (atomically (readTQueue queue)))
+    >>= either (const (pure Nothing)) (pure . Just)
+
+enqueueEvent :: (MonadSTM m) => Event entry node result state -> RaftT entry node result state m ()
+enqueueEvent event = do
+  queue <- view eventQueue
+  lift $ atomically $ writeTQueue queue event
+
+-- | Send a 'RPC' to another node.
+--
+-- To send a 'RPC' to multiple other nodes, concurrently, see 'sendRPCConcurrently'
+sendRPC :: (Monad m) => node -> RPC entry node state -> RaftSendT entry node result state m ()
+sendRPC node rpc = do
+  impl <- view implementation
+  lift $ impl.networking.sendRPC node rpc
+
+-- | Send a 'RPC' concurrently to other nodes.
+--
+-- To send a 'RPC' to a single node, see 'sendRPC'
+sendRPCConcurrently :: (MonadAsync m) => Set node -> RPC entry node state -> RaftSendT entry node result state m ()
+sendRPCConcurrently nodes rpc = do
+  impl <- view implementation
+  lift $ mapConcurrently_ (flip impl.networking.sendRPC rpc) nodes
+
+sendRPCResult :: (Monad m) => node -> RPCResult node result -> RaftSendT entry node result state m ()
+sendRPCResult node rpc = do
+  impl <- view implementation
+  lift $ impl.networking.sendRPCResult node rpc
+
+sendClientResponse :: (Monad m) => node -> ClientResponse node result -> RaftSendT entry node result state m ()
+sendClientResponse node response = do
+  impl <- view implementation
+  lift $ impl.networking.sendClientResponse node response
+
+sendAdminResponse :: (Monad m) => node -> AdminResponse node -> RaftSendT entry node result state m ()
+sendAdminResponse admin response = do
+  impl <- view implementation
+  lift $ impl.networking.sendAdminResponse admin response
+
+whenRole ::
+  (Monad m) =>
+  Role ->
+  RaftT entry node result state m () ->
+  RaftT entry node result state m ()
+whenRole r action = do
+  ourRole <- use role
+  when (ourRole == r) action
+
+-- | Send a heartbeat RPC concurrently to all other nodes.
+--
+-- This function also resets the heartbeat timer.
+sendHeartbeat ::
+  ( Ord node,
+    MonadDelay m,
+    MonadMVar m,
+    MonadFork m,
+    MonadMask m,
+    MonadAsync m
+  ) =>
+  RaftT entry node result state m ()
+sendHeartbeat =
+  whenRole Leader $ do
+    config <- view configuration
+    peers >>= traverse_ sendAppendEntriesTo
+    view heartBeatTimer >>= lift . resetTimer config.heartBeatTimeout
+
+-- | For a given destination node, look up which of the entries
+-- in our log should be replicated, and send an appropriate 'AppendEntries' RPC.
+sendAppendEntriesTo :: (Ord node, MonadAsync m) => node -> RaftT entry node result state m ()
+sendAppendEntriesTo destination = do
+  entries <- use commandLog
+  use (nextIndex . at destination)
+    >>= ( \case
+            Nothing -> pure $ Just (0, initialTerm)
+            Just destNextIndex ->
+              let previousLogIndex = pred destNextIndex
+               in case entries Log.!? previousLogIndex of
+                    Found (!prevTerm, _, _) -> pure $ Just (previousLogIndex, prevTerm)
+                    NotFound -> pure $ Just (0, initialTerm)
+                    -- The follower's next index is "lost" in the snapshot;
+                    -- we can't specify entries to append. A snapshot will have
+                    -- to be installed
+                    LogIndexInSnapshot (SnapshotMetadata lastSnapshotIndex lastSnapshotTerm)
+                      | previousLogIndex == lastSnapshotIndex -> pure $ Just (lastSnapshotIndex, lastSnapshotTerm)
+                      | otherwise -> pure Nothing
+        )
+    >>= \case
+      Just (previousLogIndex, previousLogTerm) -> do
+        let toBeReplicated = Seq.drop (fromIntegral $ Log.relativeIndex entries previousLogIndex) (logEntries entries)
+        -- We send 'AppendEntries' event if 'toBeReplicated'
+        -- is empty, as this serves as a heartbeat mechanism
+        ( AppendEntries
+            <$> use term
+            <*> (view configuration <&> nodeId)
+            <*> pure previousLogIndex
+            <*> pure previousLogTerm
+            <*> pure (((,) <$> view _1 <*> view _3) <$> toBeReplicated)
+            <*> use commitIndex
+            <*> use readOnlySequenceNum
+          )
+          >>= runSend . sendRPC destination . AE
+      Nothing ->
+        ( InstallSnapshot
+            <$> use term
+            <*> (view configuration <&> nodeId)
+            <*> currentSnapshot
+        )
+          >>= runSend . sendRPC destination . IS
+
+applyEntry ::
+  ( Ord node,
+    MonadMVar m,
+    MonadAsync m
+  ) =>
+  Term -> LogIndex -> LogEntry entry node -> RaftT entry node result state m (Maybe (CommandResponse node result))
+applyEntry entryTerm entryIndex (LogEntryCommand (Command reqId entry)) = do
+  sm <- view implementation <&> stateMachine
+  currState <- use internalState
+  result <-
+    case sm entry of
+      Read runRead -> pure $ runRead currState
+      Transition runWrite -> do
+        let (newState, result) = runWrite currState
+        trace (\ctx -> LogEntryApplied ctx entryTerm entryIndex entry)
+        internalState .= newState
+
+        pure result
+
+  pure $ Just (MkCommandResponse result reqId)
+applyEntry _entryTerm _entryIndex LogEntryLeaderChange = pure Nothing
+applyEntry _entryTerm _entryIndex (LogEntryMembershipChange clusterConf) = do
+  setClusterMembership clusterConf
+  case clusterConf of
+    Simple {} -> trace MembershipChangeCompleted $> Nothing
+    Joint {} -> pure Nothing
+
+-- | Updates the commit index. Returns 'True' if some log entries can be applied,
+-- and 'False' otherwise.
+updateCommitIndex :: (Ord node, Monad m) => RaftT entry node result state m Bool
+updateCommitIndex = do
+  commitIndex' <- use commitIndex
+  entries <- use commandLog
+  ourTerm <- use term
+  matchIndices <- use matchIndex
+  s <- self
+  clusterConf <- use clusterConfiguration
+
+  -- Fetch the indices, starting from the log index after the commit index, such that:
+  -- 1. the entry is associated with the current term
+  -- 2. a quorum of nodes have committed this index
+  --
+  -- All of this is done relative to the snapshot, hence why all of the
+  -- indices are relativized
+  let relativeMatchIndices = fmap (Log.relativeIndex entries) matchIndices
+      relativeCommitIndex = Log.relativeIndex entries commitIndex'
+      liveEntries = logEntries entries
+      relativeQuorumIndices =
+        Seq.zip
+          ( Seq.fromFunction
+              (length liveEntries)
+              -- The initial commit index is 0, hence the first entry to be committed
+              -- should have index 1
+              succ
+          )
+          liveEntries
+          & Seq.drop (fromIntegral relativeCommitIndex)
+          & Seq.filter ((== ourTerm) . view _1 . snd)
+          & fmap fst
+          -- By definition of the Raft algorithm, only a contiguous subset of
+          -- indices can have been accepted with a quorum, hence the use of
+          -- takeWhileL
+          & Seq.takeWhileL
+            ( \i ->
+                hasQuorum
+                  clusterConf
+                  -- Note that 'matchIndices' do not include the leader,
+                  -- so we take the leader into account by inserting it
+                  -- with the other match indices
+                  ( Set.insert s $
+                      Map.keysSet
+                        (Map.filter (>= fromIntegral i) relativeMatchIndices)
+                  )
+            )
+          & fmap fromIntegral
+
+  case Seq.viewr relativeQuorumIndices of
+    Seq.EmptyR -> pure False
+    _ :> relativeLastIndex -> do
+      let lastIndex = absoluteIndex entries relativeLastIndex
+      setCommitIndex lastIndex
+      trace (`CommitIndexIncreasedTo` lastIndex)
+      pure True
+
+setCommitIndex :: (Monad m) => LogIndex -> RaftT entry node result state m ()
+setCommitIndex ix = do
+  impl <- view implementation
+  s <- self
+  commitIndex .= ix
+  lift $ impl.persistence.writeCommitIndex s ix
+
+-- | Set the current vote, both in the internal state
+-- but also in persisted state.
+--
+-- This function doesn't emit any RPCs
+voteFor :: (Monad m) => Maybe node -> RaftT entry node result state m ()
+voteFor mNode = do
+  impl <- view implementation
+  s <- self
+  t <- use term
+  lift $ impl.persistence.writeVotedFor s t mNode
+  votedFor .= mNode
+  traverse_ (\n -> trace (\ctx -> VotedFor ctx t n)) mNode
+
+-- | Update the commit index, and apply log entries if there are
+-- any log entries that /can/ be applied.
+applyLogEntries :: (Ord node, MonadMVar m, MonadAsync m, MonadMask m, MonadFork m, MonadDelay m) => RaftT entry node result state m ()
+applyLogEntries = do
+  isTimeToCommit <- updateCommitIndex
+  when isTimeToCommit applyCommittedEntries
+
+applyCommittedEntries :: (Ord node, MonadMVar m, MonadAsync m, MonadMask m, MonadFork m, MonadDelay m) => RaftT entry node result state m ()
+applyCommittedEntries = do
+  lastAppliedIndex <- use lastApplied
+  currentCommitIndex <- use commitIndex
+  when (lastAppliedIndex < currentCommitIndex) $ do
+    entries <- use commandLog
+    let unAppliedEntries =
+          entries
+            & (`Log.keepEntriesUpTo` currentCommitIndex)
+            & logEntries
+            & Seq.drop (fromIntegral (Log.relativeIndex entries lastAppliedIndex))
+
+    lastApplied .= currentCommitIndex
+    trace (`LastAppliedIndexIncreasedTo` currentCommitIndex)
+
+    confBefore <- use clusterConfiguration
+    results <-
+      mapM (\(t, ix, e) -> applyEntry t ix e) unAppliedEntries
+        -- Membership change commands don't return a result
+        <&> fmap fromJust . Seq.filter isJust
+
+    whenRole Leader $ do
+      leaderId <- self
+
+      let resultsByReqId =
+            results
+              & Foldable.toList
+              & map (\(MkCommandResponse result reqId) -> (reqId, NonEmpty.singleton result))
+              & Map.fromListWith (<>)
+              & Map.map NonEmpty.reverse -- Necessary because 'fromListWith' reverses order of applied commands
+      for_ (Map.toList resultsByReqId) $ \(reqId, responses) ->
+        use currentClientRequests
+          <&> Map.lookup reqId
+          >>= \case
+            Nothing -> pure () -- TODO: isn't this unexpected?
+            Just requester -> do
+              for_ responses $ \response -> do
+                runSend $ sendClientResponse requester (MkResponse reqId (Just leaderId) (Success response))
+                trace (`CommandResultResponded` MkCommandResponse (Success response) reqId)
+              currentClientRequests %= Map.delete reqId
+
+    view configuration <&> maxLogLength >>= \case
+      Nothing -> pure ()
+      Just maxLog -> do
+        entries' <- use commandLog
+        when
+          (Seq.length (logEntries entries') > maxLog)
+          (currentSnapshot >>= persistSnapshot)
+
+    -- If cluster configuration has changed, then the quorum
+    -- threshold may be different. Let's try to apply log entries
+    -- and unify the cluster membership
+    whenRole Leader $ do
+      reconfigured <- use clusterConfiguration <&> (/= confBefore)
+      when reconfigured applyLogEntries
+      unifyCluster
+
+  -- Since the last applied index could have been updated,
+  -- we might be able to serve some read-only requests
+  serveReadOnlyQueries
+
+nextElectionTimeout :: (Monad m) => RaftT entry node result state m Microseconds
+nextElectionTimeout = do
+  gen <- use randomGen
+  (lowerBound, upperBound) <- view configuration <&> electionTimeoutRange
+  let (timeout, nextGen) = uniformR (lowerBound, upperBound) gen
+  randomGen .= nextGen
+  pure timeout
+
+trace :: (Monad m) => (EventContext node -> RaftTrace entry node result state) -> RaftT entry node result state m ()
+trace makeTrace = do
+  eventCtx <- EventContext <$> use term <*> self
+  impl <- view implementation
+  lift $ tracer impl (makeTrace eventCtx)
+
+-- | Update the internal term state, returning the previous and new 'Term's.
+--
+-- If the update function returns the current term, this function does nothing.
+updateTerm :: (Monad m) => (Term -> Term) -> RaftT entry node result state m (Term, Term)
+updateTerm update = do
+  currTerm <- use term
+  s <- self
+  let newTerm = update currTerm
+
+  when (newTerm > currTerm) $ do
+    impl <- view implementation
+
+    lift $ impl.persistence.writeTerm s newTerm
+    term .= newTerm
+  pure (currTerm, newTerm)
+
+updateMatchIndex ::
+  (Ord node, Monad m) =>
+  node -> LogIndex -> RaftT entry node result state m ()
+updateMatchIndex responder ackedIndex = do
+  prev <- use (matchIndex . at responder)
+  let newMatch = maybe ackedIndex (max ackedIndex) prev
+  matchIndex . at responder .= Just newMatch
+  nextIndex . at responder .= Just (succ newMatch)
+
+-- | Set up a callback for a client request
+acceptClientRequests ::
+  (MonadMVar m) =>
+  -- | Client node
+  NonEmpty (ClientRequest entry node) ->
+  RaftT entry node result state m (NonEmpty ClientRequestId)
+acceptClientRequests requests = do
+  -- The term is part of the request ID. Our internal counter is volatile and
+  -- restarts from zero whenever we boot, so without the term an entry stamped
+  -- by an earlier leader could collide with one of ours, and we would answer
+  -- the client with the result of that older command. See 'RequestId'.
+  ourTerm <- use term
+  ci <- use commitIndex
+  sm <- view implementation <&> stateMachine
+  s <- self
+  for requests $ \(MkRequest clientReqId clientId entry) -> do
+    case sm entry of
+      -- Read-only requests don't go to the log, and so
+      -- we need to persist more information about them.
+      Read runRead -> do
+        readOnlySequenceNum += 1
+        rseq <- use readOnlySequenceNum
+        pendingReadRequests
+          %= Map.insert
+            clientReqId
+            ( MkPendingRead
+                { _pendingReadTerm = ourTerm,
+                  _pendingReadLogIndex = ci,
+                  _pendingReadClient = clientId,
+                  _pendingReadLeaderAcknowledgedBy = Set.singleton s,
+                  _pendingReadProjection = runRead,
+                  _pendingReadSequenceNum = rseq
+                }
+            )
+        trace (\ctx -> ReadOnlyQueryQueued ctx ci entry)
+      Transition _ -> currentClientRequests %= Map.insert clientReqId clientId
+    pure clientReqId
+
+currentSnapshot :: (Monad m) => RaftT entry node result state m (Snapshot node state)
+currentSnapshot = do
+  lastAppliedIndex <- use lastApplied
+  entries <- use commandLog
+  ourTerm <- use term
+
+  -- The snapshot stands in for the log up to and including 'lastAppliedIndex',
+  -- so its term has to be the term of the entry /at/ that index, not the term we
+  -- happen to be in now. Those differ whenever we snapshot in a later term than
+  -- the entries we are compacting, and getting it wrong wedges a follower for
+  -- good: it installs the snapshot, the leader then sends 'AppendEntries' with
+  -- the real term for that index, the consistency check against the snapshot
+  -- metadata fails, the leader backs up into the snapshot and installs it
+  -- again, forever.
+  let lastAppliedTerm = case entries Log.!? lastAppliedIndex of
+        Found (entryTerm, _, _) -> entryTerm
+        -- Already compacted into our own snapshot, whose metadata knows the term.
+        LogIndexInSnapshot (SnapshotMetadata _ snapshotTerm) -> snapshotTerm
+        -- Cannot happen: 'lastApplied' never runs past the log.
+        NotFound -> ourTerm
+
+  Snapshot (SnapshotMetadata lastAppliedIndex lastAppliedTerm)
+    <$> use internalState
+    <*> use clusterConfiguration
+
+-- | Serialize the snapshot in a separate thread.
+--
+-- An event will be emitted to run `applySnapshot`.
+--
+-- If a snapshot is currently being serialized, 'persistSnapshot' does nothing. This means
+-- that if the node is currently snapshotting because its log is too long, and then
+-- a leader sends 'InstallSnapshot', the leader's 'InstallSnapshot' may be ignored.
+-- This isn't wrong, but will result in the leader potentially re-sending an 'InstallSnapshot'
+-- RPC again soon.
+persistSnapshot :: (MonadAsync m) => Snapshot node state -> RaftT entry node result state m ()
+persistSnapshot snapshot = do
+  inprogress <- use snapshotInProgress
+
+  -- We guard persisting snapshot, since we could be appending to the log a lot,
+  -- in which case we might notice that the log is too long just as often,
+  -- resulting in a cascade of snapshotting.
+  if inprogress
+    then pure ()
+    else do
+      snapshotInProgress .= True
+
+      s <- self
+      impl <- view implementation
+      queue <- view eventQueue
+
+      void $ lift $ async $ do
+        impl.persistence.writeSnapshot s snapshot
+        atomically $
+          writeTQueue
+            queue
+            (EventSnapshotPersisted snapshot)
+
+-- | Whether we are in the configuration we are currently using.
+isClusterMember :: (Ord node, Monad m) => RaftT entry node result state m Bool
+isClusterMember = do
+  s <- self
+  use clusterConfiguration <&> Set.member s . allNodes
+
+-- | Check if any of the pending read only queries
+-- can be served. If they can, serve them!
+serveReadOnlyQueries :: (Ord node, MonadAsync m) => RaftT entry node result state m ()
+serveReadOnlyQueries = whenRole Leader $ do
+  clusterConf <- use clusterConfiguration
+  appIx <- use lastApplied
+  ourTerm <- use term
+  leaderId <- self
+  entries <- use commandLog
+
+  let appliedInOurTerm = case entries Log.!? appIx of
+        Found (t, _, _) -> t == ourTerm
+        LogIndexInSnapshot (SnapshotMetadata _ t) -> t == ourTerm
+        NotFound -> False
+
+      canBeServed pendingRead =
+        -- TODO: what if it's an old term? How could this even be possible?
+        (pendingRead ^. pendingReadTerm == ourTerm)
+          && appliedInOurTerm
+          && (pendingRead ^. pendingReadLogIndex <= appIx)
+          && hasQuorum clusterConf (pendingRead ^. pendingReadLeaderAcknowledgedBy)
+
+  (ready, notReady) <- use pendingReadRequests <&> Map.partition canBeServed
+
+  st <- use internalState
+  for_ (Map.toList ready) $ \(reqId, request) -> do
+    let result = request ^. pendingReadProjection $ st
+    runSend $
+      sendClientResponse
+        (request ^. pendingReadClient)
+        (MkResponse reqId (Just leaderId) (Success result))
+
+    trace (`CommandResultResponded` MkCommandResponse (Success result) reqId)
+
+  pendingReadRequests .= notReady
+
+-- | Apply a snapshot to the internal state.
+--
+-- This can be used by any node on itself, or
+-- as part of the 'InstallSnapshot' remote procedure call.
+applySnapshot ::
+  (Monad m) =>
+  Snapshot node state ->
+  RaftT entry node result state m ()
+applySnapshot snapshot = do
+  snapshotInProgress .= False
+  let snapshotIndex = snapshot.sMetadata.smLastIncludedIndex
+  alreadyApplied <- use lastApplied <&> (>= snapshotIndex)
+  -- Log.applySnapshot is a no-op if the incoming snapshot doesn't
+  -- advance the log
+  lastIndexBefore <- use commandLog <&> Log.lastLogIndex
+  commandLog %= Log.applySnapshot snapshot.sMetadata
+
+  -- A snapshot may change the last log index (either truncating
+  -- the log or fast-forwarding it), leading to the last log index
+  -- jumping around
+  lastIndexAfter <- use commandLog <&> Log.lastLogIndex
+  when (lastIndexAfter /= lastIndexBefore) $
+    trace (`LastLogIndexChangedTo` lastIndexAfter)
+
+  unless alreadyApplied $ do
+    internalState .= sData snapshot
+    clusterConfiguration .= sCluster snapshot
+
+    -- Commit index should never decrease
+    use commitIndex >>= \cix -> when (snapshotIndex > cix) (setCommitIndex snapshotIndex)
+    lastApplied %= max snapshot.sMetadata.smLastIncludedIndex
+
+  trace (`SnapshotApplied` sMetadata snapshot)
+
+-- | Apply one or more entries to the log, from the leader's point of view
+appendLogEntries ::
+  ( Ord node,
+    MonadMVar m,
+    MonadAsync m,
+    MonadMask m,
+    MonadFork m,
+    MonadDelay m
+  ) =>
+  NonEmpty (Term, LogEntry entry node) ->
+  RaftT entry node result state m ()
+appendLogEntries entries = do
+  s <- self
+  impl <- view implementation
+  startingLogIndex <- use commandLog <&> Log.lastLogIndex
+  commandLog %= (`Log.extend` Seq.fromList (NonEmpty.toList entries))
+
+  let batchToWrite =
+        zipWith
+          (curry (\(ix, (t, entry)) -> (t, ix, entry)))
+          [succ startingLogIndex ..]
+          (NonEmpty.toList entries)
+  lift $ impl.persistence.writeLogEntry s batchToWrite
+  for_ batchToWrite $ \(t, ix, entry) ->
+    trace (\ctx -> LogEntryAppended ctx t ix entry)
+
+  -- It's important to emit this event because a new leader may have its
+  -- log index jump. Without having visibility into this jump,
+  -- it's hard to check that the commit index is always <= the last log index
+  use commandLog <&> Log.lastLogIndex >>= trace . flip LastLogIndexChangedTo
+
+  whenRole Leader $
+    peers >>= traverse_ sendAppendEntriesTo
+
+  -- In a single-node cluster, we would already have
+  -- quorum to update our commit index
+  applyLogEntries
+
+restoreState ::
+  ( MonadMVar m,
+    MonadAsync m,
+    Ord node,
+    MonadMask m,
+    MonadFork m,
+    MonadDelay m
+  ) =>
+  RaftT entry node result state m ()
+restoreState = do
+  impl <- view implementation
+  s <- self
+
+  (persistedTerm, persistedVote, mPersistedSnapshot, persistedCommit) <-
+    lift $ do
+      t <- impl.persistence.readTerm s
+      (t,,,)
+        <$> impl.persistence.readVotedFor s t
+        <*> impl.persistence.readSnapshot s
+        <*> impl.persistence.readCommitIndex s
+
+  term .= persistedTerm
+  votedFor .= persistedVote
+
+  let snapshotIndex = maybe 0 (smLastIncludedIndex . sMetadata) mPersistedSnapshot
+
+  entries <- lift $ Seq.fromList <$> impl.persistence.readLogEntriesFrom s (succ snapshotIndex)
+
+  let restoredLog = Log.buildLog entries (sMetadata <$> mPersistedSnapshot)
+  commandLog .= restoredLog
+  -- Not persisting the commit index on purpose here,
+  -- since we're restoring from persisted state
+  commitIndex .= min persistedCommit (Log.lastLogIndex restoredLog)
+  traverse_ applySnapshot mPersistedSnapshot
+
+  trace
+    ( \ctx ->
+        StateRestored
+          ctx
+          persistedVote
+          restoredLog
+    )
+
+  restoredCommit <- use commitIndex
+  when (restoredCommit > 0) $ do
+    trace (`LastLogIndexChangedTo` Log.lastLogIndex restoredLog)
+    trace (`CommitIndexIncreasedTo` restoredCommit)
+
+  applyCommittedEntries
+
+-- | Is a cluster membership change ongoing?
+pendingClusterMembershipChanges :: (Monad m) => RaftT entry node result state m Bool
+pendingClusterMembershipChanges =
+  (>) <$> use pendingConfigurationIndex <*> use lastApplied
+
+-- | Set the cluster membership configuration, updating
+-- the rest of the state as well.
+setClusterMembership ::
+  ( Ord node,
+    MonadMVar m,
+    MonadAsync m
+  ) =>
+  ClusterConfiguration node -> RaftT entry node result state m ()
+setClusterMembership clusterConf = do
+  clusterConfiguration .= clusterConf
+  trace (`MembershipChangeApplied` clusterConf)
+  whenRole Leader $ do
+    s <- self
+    ps <- peers
+    lastIx <- use commandLog <&> Log.lastLogIndex
+    -- Pre-emptively prepare state for new membership
+    nextIndex %= \m -> Map.fromSet (\p -> Map.findWithDefault (succ lastIx) p m) ps
+    matchIndex %= (`Map.restrictKeys` ps)
+    unless (s `Set.member` allNodes clusterConf) becomeNonMember
+
+proposeClusterMembership ::
+  ( MonadMVar m,
+    MonadAsync m,
+    Ord node,
+    MonadMask m,
+    MonadFork m,
+    MonadDelay m
+  ) =>
+  ClusterConfiguration node -> RaftT entry node result state m ()
+proposeClusterMembership clusterConf = do
+  use commandLog <&> succ . Log.lastLogIndex >>= assign pendingConfigurationIndex
+  ourTerm <- use term
+  appendLogEntries (NonEmpty.singleton (ourTerm, LogEntryMembershipChange clusterConf))
+
+-- | If the cluster is currently in a joint configuration, unify the
+-- membership to be in a simple configuration. Otherwise, do nothing.
+unifyCluster :: (MonadMVar m, MonadAsync m, Ord node, MonadMask m, MonadFork m, MonadDelay m) => RaftT entry node result state m ()
+unifyCluster = do
+  pending <- pendingClusterMembershipChanges
+  use clusterConfiguration >>= \case
+    Joint _ after | not pending -> proposeClusterMembership (Simple after)
+    _ -> pure ()
+
+becomeLeader ::
+  ( Ord node,
+    MonadDelay m,
+    MonadMVar m,
+    MonadFork m,
+    MonadMask m,
+    MonadAsync m
+  ) =>
+  RaftT entry node result state m ()
+becomeLeader = do
+  role .= Leader
+  self <&> Just >>= assign currentLeader
+  yesVotes .= Set.empty
+
+  lastIx <- use commandLog <&> Log.lastLogIndex
+  peers <&> Map.fromSet (const (lastIx + 1)) >>= assign nextIndex
+
+  trace LeaderElected
+
+  -- In order to serve read-only queries, there needs to be at least
+  -- one entry committed in this term (see Raft paper, section 8)
+  ourTerm <- use term
+  appendLogEntries (NonEmpty.singleton (ourTerm, LogEntryLeaderChange))
+
+  -- cluster configuration could be ongoing, started under a different leader
+  use clusterConfiguration >>= \case
+    Simple _ -> pure ()
+    Joint _before after ->
+      appendLogEntries (NonEmpty.singleton (ourTerm, LogEntryMembershipChange (Simple after)))
+
+  sendHeartbeat -- Note that 'sendHeartbeat' will also reset the heartbeat timer
+
+-- | Reply to clients that the leader is stepping down. This function does nothing
+-- if the role isn't 'Leader'
+leaderStepDown :: (MonadAsync m) => Maybe node -> RaftT entry node result state m ()
+leaderStepDown mNewLeader = whenRole Leader $ do
+  clientReqs <- use currentClientRequests
+  for_ (Map.toList clientReqs) $ \(reqId, requester) -> do
+    runSend $ sendClientResponse requester (MkResponse reqId mNewLeader NotLeader)
+    trace (`CommandResultResponded` MkCommandResponse NotLeader reqId)
+
+  currentClientRequests .= mempty
+
+  readRequests <- use pendingReadRequests
+  for_ (Map.toList readRequests) $ \(reqId, request) -> do
+    runSend $
+      sendClientResponse
+        (request ^. pendingReadClient)
+        (MkResponse reqId mNewLeader NotLeader)
+    trace (`CommandResultResponded` MkCommandResponse NotLeader reqId)
+
+  pendingReadRequests .= mempty
+
+becomeFollower ::
+  (MonadMVar m, MonadDelay m, MonadFork m, MonadMask m, MonadAsync m) =>
+  -- | Leader if known
+  Maybe node ->
+  RaftT entry node result state m ()
+becomeFollower mLeaderNodeId = do
+  leaderStepDown mLeaderNodeId
+  resetHeartBeatTimer
+  resetElectionTimer
+  r <- use role
+  unless (r == Follower) $ do
+    trace BecameFollower
+    role .= Follower
+
+  currentLeader .= mLeaderNodeId
+
+becomeCandidate ::
+  ( Ord node,
+    MonadAsync m,
+    MonadMask m,
+    MonadFork m,
+    MonadMVar m,
+    MonadDelay m
+  ) =>
+  RaftT entry node result state m ()
+becomeCandidate = do
+  trace BecameCandidate
+  role .= Candidate
+
+  currentLeader .= Nothing
+
+  -- The following pieces of state are only useful to leaders
+  nextIndex .= mempty
+  matchIndex .= mempty
+
+  s <- self
+  term += 1
+  w <- view implementation <&> writeTerm . persistence
+  thisTerm <- use term
+  lift (w s thisTerm)
+
+  voteFor (Just s)
+  yesVotes .= Set.singleton s
+
+  resetElectionTimer
+
+  checkElection -- there might only be a single node in the cluster
+  r <- use role
+  when (r == Candidate) $ do
+    currentTerm <- use term
+    (lastLogTerm, lastLogIx) <- use commandLog <&> Log.lastLogInfo
+    let rpc = RequestVote currentTerm s lastLogIx lastLogTerm
+    peers >>= (runSend . (`sendRPCConcurrently` rpc))
+
+checkElection ::
+  ( Ord node,
+    MonadAsync m,
+    MonadMask m,
+    MonadFork m,
+    MonadMVar m,
+    MonadDelay m
+  ) =>
+  RaftT entry node result state m ()
+checkElection = do
+  q <- hasQuorum <$> use clusterConfiguration <*> use yesVotes
+  when q becomeLeader
+
+becomeNonMember ::
+  (MonadMVar m, MonadAsync m) =>
+  RaftT entry node result state m ()
+becomeNonMember = do
+  r <- use role
+  leaderStepDown Nothing
+  unless (r == NonMember) $ do
+    trace BecameNonMember
+    role .= NonMember
+  currentLeader .= Nothing
+
+resetHeartBeatTimer ::
+  ( MonadAsync m,
+    MonadMask m,
+    MonadFork m,
+    MonadMVar m,
+    MonadDelay m
+  ) =>
+  RaftT entry node result state m ()
+resetHeartBeatTimer = do
+  config <- view configuration
+  view heartBeatTimer >>= lift . resetTimer config.heartBeatTimeout
+
+resetElectionTimer ::
+  ( MonadAsync m,
+    MonadMask m,
+    MonadFork m,
+    MonadMVar m,
+    MonadDelay m
+  ) =>
+  RaftT entry node result state m ()
+resetElectionTimer = do
+  electionTimeout <- nextElectionTimeout
+  view electionTimer >>= lift . resetTimer electionTimeout
diff --git a/src/Distributed/Consensus/Raft/Transformer/Definition.hs b/src/Distributed/Consensus/Raft/Transformer/Definition.hs
new file mode 100644
--- /dev/null
+++ b/src/Distributed/Consensus/Raft/Transformer/Definition.hs
@@ -0,0 +1,296 @@
+{-# LANGUAGE NumericUnderscores #-}
+{-# LANGUAGE TemplateHaskell #-}
+
+module Distributed.Consensus.Raft.Transformer.Definition
+  ( runRaftT,
+    RaftT,
+    Config (..),
+    simpleConfig,
+    ClusterState (..),
+    RaftEnv,
+    implementation,
+    configuration,
+    eventQueue,
+    heartBeatTimer,
+    electionTimer,
+    exitLock,
+
+    -- ** Read-only operations
+    RaftSendT,
+    runSend,
+
+    -- * Internal Raft state
+    RaftState,
+    initialTerm,
+    initialRaftState,
+    role,
+    term,
+    clusterConfiguration,
+    internalState,
+    votedFor,
+    currentLeader,
+    commandLog,
+    commitIndex,
+    lastApplied,
+    nextIndex,
+    matchIndex,
+    pendingConfigurationIndex,
+    yesVotes,
+    currentClientRequests,
+    pendingReadRequests,
+    readOnlySequenceNum,
+    snapshotInProgress,
+    randomGen,
+
+    -- ** Read-only client requests
+    PendingRead (..),
+    pendingReadTerm,
+    pendingReadLogIndex,
+    pendingReadClient,
+    pendingReadLeaderAcknowledgedBy,
+    pendingReadSequenceNum,
+    pendingReadProjection,
+
+    -- * Generic helpers
+    ask,
+    asks,
+    local,
+    state,
+    get,
+    put,
+    modify,
+    gets,
+  )
+where
+
+import Control.Concurrent.Class.MonadMVar (MVar, MonadMVar, newEmptyMVar)
+import Control.Concurrent.Class.MonadSTM (TQueue, atomically, newTQueue, writeTQueue)
+import Control.Monad (void)
+import Control.Monad.Class.MonadAsync (MonadAsync, async)
+import Control.Monad.Class.MonadSTM (MonadSTM)
+import Control.Monad.IO.Class (MonadIO)
+import Control.Monad.Trans.Class (lift)
+import Control.Monad.Trans.RWS.CPS (RWST, ask, asks, evalRWST, get, gets, local, modify, put, state)
+import Control.Monad.Trans.Reader (ReaderT, runReaderT)
+import Data.Map.Strict (Map)
+import Data.Set (Set)
+import qualified Data.Set as Set
+import Data.Word (Word64)
+import Distributed.Consensus.Raft.Client (ClientRequestId)
+import Distributed.Consensus.Raft.Domain (ClusterConfiguration (..), LogIndex, ReadOnlySequenceNum, Role (..), Term)
+import Distributed.Consensus.Raft.Implementation (Event (..), Implementation, LogEntry)
+import Distributed.Consensus.Raft.Log (Log, newLog)
+import Distributed.Consensus.Raft.Timer (Microseconds, Timer, newTimer)
+import Lens.Micro.Platform (makeLenses)
+import System.Random (StdGen, mkStdGen64)
+import System.Random.Stateful (randomIO)
+
+type RaftT entry node result state m =
+  -- Note: using RWST prevents to use the `MonadAsync`, `MonadSTM`, ...
+  -- classes.
+  -- The alternative would be to keep the 'RaftState' in a mutable variable
+  -- (e.g. 'MVar'), but it's not clear how much of a performance or usability
+  -- downgrade this would be.
+  RWST
+    (RaftEnv entry node result state m)
+    ()
+    (RaftState entry node result state)
+    m
+
+-- | This type exists so that we can spin out asynchronous threads
+-- for sending messages
+type RaftSendT entry node result state m =
+  ReaderT
+    (RaftEnv entry node result state m)
+    m
+
+-- | Run an action of type 'RaftSendT' asynchronously
+runSend ::
+  (MonadAsync m) =>
+  RaftSendT entry node result state m () ->
+  RaftT entry node result state m ()
+runSend act = ask >>= lift . void . async . runReaderT act
+
+data ClusterState node
+  = -- | Lone node, not in a cluster. This 'ClusterState' is useful if you want
+    -- to start up a Raft server and have it join an existing cluster.
+    LoneNode
+  | -- | Node in cluster. The cluster configuration can be empty,
+    -- in which case this cluster has a single node
+    InCluster (Set node)
+
+data RaftState entry node result state = MkRaftState
+  { _role :: !Role,
+    _term :: !Term,
+    _clusterConfiguration :: !(ClusterConfiguration node),
+    _internalState :: !state,
+    _votedFor :: !(Maybe node),
+    _currentLeader :: !(Maybe node),
+    _commandLog :: !(Log (LogEntry entry node) node),
+    _commitIndex :: !LogIndex,
+    _lastApplied :: !LogIndex,
+    _nextIndex :: !(Map node LogIndex),
+    _matchIndex :: !(Map node LogIndex),
+    -- | Until this log index has been applied, a cluster configuration
+    -- change should not be started, possibly because another cluster
+    -- configuration change is ongoing.
+    _pendingConfigurationIndex :: !LogIndex,
+    -- | Set of votes received in the current term
+    _yesVotes :: !(Set node),
+    _currentClientRequests :: !(Map ClientRequestId node),
+    _pendingReadRequests :: !(Map ClientRequestId (PendingRead node result state)),
+    -- | Counter incremented on each incoming read-only query. This counter allows to know
+    -- when a heartbeat counts to acknowledge a read-only request (or was already
+    -- in-flight, for example)
+    _readOnlySequenceNum :: !ReadOnlySequenceNum,
+    -- | 'True' if a snapshot is currently being written to storage, which is done asynchronously.
+    _snapshotInProgress :: !Bool,
+    _randomGen :: !StdGen
+  }
+
+-- | A pending read-only request isn't part of the
+-- log, so we need a little bit of extra metadata
+data PendingRead node result state = MkPendingRead
+  { _pendingReadTerm :: !Term,
+    _pendingReadLogIndex :: !LogIndex,
+    _pendingReadClient :: !node,
+    _pendingReadSequenceNum :: !ReadOnlySequenceNum,
+    -- After the request is accepted by the leader,
+    -- we store nodes that have acknowledged us as the leader
+    -- here. Once `hasQuorum` is reached, we can reply
+    _pendingReadLeaderAcknowledgedBy :: !(Set node),
+    _pendingReadProjection :: state -> result
+  }
+
+initialTerm :: Term
+initialTerm = 1
+
+initialRaftState ::
+  (Ord node) =>
+  Role ->
+  -- | Random number generator seed
+  Word64 ->
+  -- | Initial cluster configuration
+  Set node ->
+  -- | Initial internal state
+  state ->
+  RaftState entry node result state
+initialRaftState initRole seed clusterConf initialState =
+  MkRaftState
+    { _role = initRole,
+      _term = initialTerm,
+      _clusterConfiguration = Simple clusterConf,
+      _internalState = initialState,
+      _votedFor = Nothing,
+      _currentLeader = Nothing,
+      _commandLog = newLog,
+      _commitIndex = 0,
+      _lastApplied = 0,
+      _nextIndex = mempty,
+      _matchIndex = mempty,
+      _pendingConfigurationIndex = 0,
+      _yesVotes = mempty,
+      _currentClientRequests = mempty,
+      _pendingReadRequests = mempty,
+      _readOnlySequenceNum = 0,
+      -- We use mkStdGen64 for reproducibility across 32-bit and 64-bit architectures
+      _snapshotInProgress = False,
+      _randomGen = mkStdGen64 seed
+    }
+
+runRaftT ::
+  ( Ord node,
+    MonadSTM m,
+    MonadMVar m
+  ) =>
+  Config node ->
+  ClusterState node ->
+  state ->
+  Implementation entry node result state m ->
+  RaftT entry node result state m a ->
+  m a
+runRaftT config startingState internalState impl f = do
+  queue <- atomically newTQueue
+  hbTimer <- newTimer (atomically $ writeTQueue queue EventHeartBeatTimeout)
+  elTimer <- newTimer (atomically $ writeTQueue queue EventElectionTimeout)
+  exitLock <- newEmptyMVar
+  let (members, initRole) = case startingState of
+        LoneNode -> (mempty, NonMember)
+        InCluster cluster -> (Set.insert (nodeId config) cluster, Follower)
+  fst
+    <$> evalRWST
+      f
+      ( MkRaftEnv
+          { _configuration = config,
+            _implementation = impl,
+            _eventQueue = queue,
+            _heartBeatTimer = hbTimer,
+            _electionTimer = elTimer,
+            _exitLock = exitLock
+          }
+      )
+      (initialRaftState initRole (randomSeed config) members internalState)
+
+data RaftEnv entry node result state m
+  = MkRaftEnv
+  { _configuration :: !(Config node),
+    _implementation :: !(Implementation entry node result state m),
+    _eventQueue :: TQueue m (Event entry node result state),
+    -- Handle to a thread which will send a heartbeat timeout
+    -- event after the appropriate amount of time.
+    _heartBeatTimer :: Timer m,
+    _electionTimer :: Timer m,
+    _exitLock :: MVar m ()
+  }
+
+-- | Simplest configuration with good defaults:
+--
+-- * Election range between 1s and 2s
+-- * Heartbeat timeout of 100ms
+-- * Random seed
+-- * Keep 100 000 log entries before compaction
+simpleConfig :: (MonadIO m) => node -> m (Config node)
+simpleConfig node = do
+  seed <- randomIO
+  pure $
+    MkConfig
+      { nodeId = node,
+        electionTimeoutRange = (1_000_000, 2_000_000),
+        heartBeatTimeout = 100_000,
+        randomSeed = seed,
+        maxLogLength = Just 100_000
+      }
+
+-- | Runtime configuration for a Raft server.
+--
+-- You should use 'simpleConfig' if you don't have strong opinions
+-- on the configuration values.
+data Config node
+  = MkConfig
+  { -- | Identification for the node
+    nodeId :: !node,
+    -- | Inclusive range of election timeouts. The actual election timeout will be
+    -- chosen at random, with a uniform probability distribution in the range.
+    electionTimeoutRange :: !(Microseconds, Microseconds),
+    -- | Heartbeat timeout.
+    heartBeatTimeout :: !Microseconds,
+    -- | Random seed for the generation of election timeouts.
+    --
+    -- Make sure to not re-use a seed across servers. Re-using the same seed
+    -- on multiple Raft servers will lead to permanently-split votes, rendering
+    -- the cluster unable to process any requests.
+    randomSeed :: !Word64,
+    -- | If provided, once the log on any node
+    -- reaches this length, a snapshot is produced
+    -- for log compaction. If @Nothing@, snapshotting
+    -- is disabled.
+    maxLogLength :: Maybe Int
+    -- TODO: configure the maximum amount of concurrency. For example, we currently
+    --       spawn a new thread to send an RPC to each other node.
+    --       We may want to batch this concurrency via something like
+    --       `Control.Concurrent.Stream.mapConcurrentlyBounded`
+  }
+
+makeLenses ''RaftEnv
+makeLenses ''RaftState
+makeLenses ''PendingRead
diff --git a/tests/Control/Monitor.hs b/tests/Control/Monitor.hs
new file mode 100644
--- /dev/null
+++ b/tests/Control/Monitor.hs
@@ -0,0 +1,366 @@
+{-# LANGUAGE BangPatterns #-}
+{-# LANGUAGE DeriveFunctor #-}
+{-# LANGUAGE OverloadedStrings #-}
+
+module Control.Monitor
+  ( -- * Types
+    Monitor,
+    Concurrently,
+    ppReasons,
+    ppReasonsWithTrace,
+
+    -- ** Running the 'Monitor'
+    runMonitor,
+
+    -- ** Defining 'Monitor's
+    label,
+    (<?>),
+    nonEmptyStep,
+    step,
+
+    -- * Predicates
+    module Control.Monitor.Predicate,
+
+    -- * Algebra
+
+    -- ** Unary operators
+    next,
+    eventually,
+    always,
+
+    -- ** Binary operators
+    until,
+    weakUntil,
+    release,
+
+    -- * Combinators
+    assert,
+    never,
+    collectUntil,
+    scanUntil,
+    whenever,
+
+    -- * Concurrent combinators
+    both,
+    race,
+    anyOf,
+    allOf,
+  )
+where
+
+import Control.Applicative (Alternative (..), asum, (<|>))
+import Control.Monad (unless, (>=>))
+import Control.Monitor.Predicate
+import Control.Monitor.Reason
+  ( Reason (..),
+    Reasons (..),
+    oneReason,
+    ppReasons,
+    ppReasonsWithTrace,
+    simpleReason,
+    unexpectedEnd,
+    unexpectedEvent,
+  )
+import Data.Bifunctor (first)
+import Data.Maybe (isJust)
+import Data.Text (Text)
+import qualified Data.Text as Text
+import Prelude hiding (until)
+
+data Monitor e a
+  = Done !a
+  | Fail !(Reasons e)
+  | Step
+      -- | What to do on end-of-input
+      !(Either (Reasons e) a)
+      -- | How to continue
+      !(e -> Monitor e a)
+  deriving (Functor)
+
+nonEmptyStep ::
+  (e -> Monitor e a) ->
+  Monitor e a
+nonEmptyStep = Step (Left (oneReason unexpectedEnd))
+
+step ::
+  a ->
+  (e -> Monitor e a) ->
+  Monitor e a
+step ifEmpty =
+  Step (Right ifEmpty)
+
+label :: Text -> Monitor e a -> Monitor e a
+label l = mapReason (\r -> r {reasonLabels = l : reasonLabels r})
+
+infix 0 <?>
+
+(<?>) :: Monitor e a -> Text -> Monitor e a
+(<?>) = flip label
+
+mapReason :: (Reason e -> Reason e) -> Monitor e a -> Monitor e a
+mapReason _ (Done a) = Done a
+mapReason f (Fail (Reasons rs)) = Fail (Reasons $ fmap f rs)
+mapReason f (Step end continue) = Step (first (Reasons . fmap f . unReasons) end) (mapReason f . continue)
+
+mapReasons :: (Reasons e -> Reasons e) -> Monitor e a -> Monitor e a
+mapReasons _ (Done a) = Done a
+mapReasons f (Fail rs) = Fail (f rs)
+mapReasons f (Step end k) = Step (first f end) (mapReasons f . k)
+
+runMonitor ::
+  Monitor e a ->
+  [e] ->
+  Either (Reasons e) a
+runMonitor = go 0
+  where
+    go !_ (Done a) _ = Right a
+    go !ix (Fail r) _ = Left (markPosition (Just ix) Nothing r)
+    go !_ (Step end _) [] = either (Left . markPosition Nothing Nothing) Right end
+    go !ix (Step _ continue) (ev : rest) = case continue ev of
+      Fail r -> Left (markPosition (Just ix) (Just ev) r)
+      m -> go (succ ix) m rest
+
+    markPosition mix mEvent = Reasons . fmap markOneReason . unReasons
+      where
+        markOneReason r =
+          r
+            { reasonIndex = reasonIndex r <|> mix,
+              reasonEvent = reasonEvent r <|> mEvent
+            }
+
+onEnd :: Monitor e a -> Either (Reasons e) a
+onEnd (Done r) = Right r
+onEnd (Fail f) = Left f
+onEnd (Step end _) = end
+
+-- | Applicative instance is sequential;
+--
+-- > liftA2 (,) p q
+--
+-- applies @p@, and THEN @q@.
+--
+-- To observe both in parallel, see 'Concurrently' or 'both'
+instance Applicative (Monitor e) where
+  pure = Done
+
+  Done f <*> ma = f <$> ma
+  Fail f <*> _ = Fail f
+  Step end continue <*> ma =
+    Step
+      (end <*> onEnd ma)
+      (\e -> continue e <*> ma)
+
+instance Monad (Monitor e) where
+  return = pure
+
+  Done a >>= f = f a
+  Fail f >>= _ = Fail f
+  Step end continue >>= f =
+    Step
+      (end >>= \a -> onEnd (f a))
+      (continue >=> f)
+
+instance MonadFail (Monitor e) where
+  fail = Fail . oneReason . simpleReason . Text.pack
+
+assert :: Text -> Bool -> Monitor e ()
+assert msg cond = unless cond (Fail (oneReason $ simpleReason msg))
+
+-- | Succeeds if the provided filter succeeds at any point
+eventually :: Predicate e a -> Monitor e a
+eventually f = go
+  where
+    go = nonEmptyStep (maybe go Done . runPredicate f)
+
+-- | Succeeds if the provided filter never matches for the
+-- rest of the sequence
+never :: Predicate e a -> Monitor e ()
+never f = go
+  where
+    go =
+      Step
+        (Right ())
+        ( \ev ->
+            maybe
+              go
+              (\_ -> Fail (oneReason $ unexpectedEvent ev))
+              (runPredicate f ev)
+        )
+
+always :: Predicate e a -> Monitor e ()
+always f = go
+  where
+    go =
+      Step
+        (Right ())
+        (\e -> if isJust (runPredicate f e) then go else Fail $ oneReason unexpectedEnd)
+
+-- | @'until' p q@ says that @q@ must eventually occur, and before it does,
+-- @p@ must hold for every e.
+--
+-- For a weaker expectation, see 'weakUntil'.
+until :: (e -> Maybe b) -> Predicate e a -> Monitor e a
+until pred' f = go
+  where
+    go = nonEmptyStep $ \ev ->
+      case runPredicate f ev of
+        Just result -> Done result
+        Nothing
+          | isJust (pred' ev) -> go
+          | otherwise -> Fail (oneReason $ unexpectedEvent ev)
+
+-- | @'weakUntil' p q@ says that @q@ might eventually occur, and before it does,
+-- @p@ must hold for every e.
+--
+-- For a stronger expectation, see 'until'.
+weakUntil ::
+  (e -> Maybe b) ->
+  Predicate e a ->
+  Monitor e (Maybe a)
+weakUntil pred' f = go
+  where
+    go = Step (Right Nothing) $ \ev ->
+      case runPredicate f ev of
+        Just result -> Done (Just result)
+        Nothing
+          | isJust (pred' ev) -> go
+          | otherwise -> Fail (oneReason $ unexpectedEvent ev)
+
+-- | 'collectUntil p q' collects the results of @p@,
+-- until @q@ is satisfied.
+collectUntil ::
+  Predicate e collect ->
+  Predicate e end ->
+  Monitor e ([collect], end)
+collectUntil collect isEnd =
+  first reverse <$> scanUntil [] (flip (:)) collect isEnd
+
+-- | @'scanUntil' start accumulate collect isEnd@ scans events that match @collect@
+-- and accumulates then with @accumulate@ until @isEnd@ matches.
+scanUntil ::
+  s ->
+  (s -> a -> s) ->
+  Predicate e a ->
+  Predicate e end ->
+  Monitor e (s, end)
+scanUntil start accumulate collect isEnd = go start
+  where
+    go !acc =
+      nonEmptyStep $ \ev -> case (runPredicate isEnd ev, runPredicate collect ev) of
+        (Nothing, Just toCollect) -> go (accumulate acc toCollect)
+        (Nothing, Nothing) -> go acc
+        (Just end, _) -> Done (acc, end)
+
+-- | @'next' f@ asserts that an e satisfying @f@ must immediately
+-- follow.
+next :: Predicate e a -> Monitor e a
+next f =
+  Step
+    (Left $ oneReason unexpectedEnd)
+    (\ev -> maybe (Fail (oneReason $ unexpectedEvent ev)) Done (runPredicate f ev))
+
+-- | @'release' p q@ asserts that @p@ must hold until @q@ does,
+-- and then @q@ holds forever.
+release ::
+  Predicate e a ->
+  Predicate e a ->
+  Monitor e ()
+release pred' f = go
+  where
+    go = nonEmptyStep $ \ev ->
+      case (runPredicate pred' ev, runPredicate f ev) of
+        (Just _, Just _) -> always f
+        (Just _, Nothing) -> go
+        (Nothing, _) -> Fail (oneReason $ unexpectedEvent ev)
+
+-- | @'whenever' p q@ says that once @p@ is satisfied,
+-- @q@ should hold.
+--
+-- This function returns the result of the inner monitor
+-- every time it was executed. This means that a return
+-- values of @[]@ means that the predicate @p@ never fired.
+whenever ::
+  Predicate e a ->
+  (a -> Monitor e b) ->
+  Monitor e [b]
+whenever trigger afterTrigger = go
+  where
+    go =
+      Step
+        (Right [])
+        ( \e -> case runPredicate trigger e of
+            Nothing -> go
+            Just x -> do
+              (y, ys) <- both (afterTrigger x) go
+              pure $ y : ys
+        )
+
+newtype Concurrently e a
+  = Concurrently {runConcurrently :: Monitor e a}
+  deriving (Functor)
+
+-- | Applicative instance is concurrent;
+--
+-- > liftA2 (,) p q
+--
+-- applies @p@ and @q@ at the same time.
+instance Applicative (Concurrently e) where
+  pure = Concurrently . pure
+
+  Concurrently p <*> Concurrently q = Concurrently (go p q)
+    where
+      go (Fail f) (Fail g) = Fail (f <> g)
+      go (Fail f) _ = Fail f
+      go _ (Fail g) = Fail g
+      go (Done f) x = fmap f x -- concurrence happens here
+      go f (Done a) = fmap ($ a) f
+      go (Step ef kf) (Step ea ka) =
+        Step (ef <*> ea) (\e -> go (kf e) (ka e))
+
+-- | Succeeds if both branches succeed
+both ::
+  Monitor e a ->
+  Monitor e b ->
+  Monitor e (a, b)
+both p q =
+  runConcurrently $
+    (,)
+      <$> Concurrently p
+      <*> Concurrently q
+
+race ::
+  Monitor e a ->
+  Monitor e b ->
+  Monitor e (Either a b)
+race = go
+  where
+    go (Done a) _ = Done (Left a)
+    go _ (Done b) = Done (Right b)
+    -- one arm died: the race degrades to the surviving arm, but we
+    -- remember why the loser died, in case the survivor also fails
+    go ma (Fail rb) = Left <$> mapReasons (rb <>) ma
+    go (Fail ra) mb = Right <$> mapReasons (<> ra) mb
+    -- both still running: synchronous product step
+    go (Step ea ka) (Step eb kb) =
+      Step (raceEnd ea eb) (\e -> go (ka e) (kb e))
+
+    -- eof verdict: leftmost acceptance wins; both rejecting accumulates
+    raceEnd (Right a) _ = Right (Left a)
+    raceEnd _ (Right b) = Right (Right b)
+    raceEnd (Left ra) (Left rb) = Left (ra <> rb)
+
+instance Alternative (Concurrently e) where
+  empty = Concurrently (Fail (oneReason (simpleReason "empty")))
+  Concurrently a <|> Concurrently b = Concurrently (either id id <$> race a b)
+
+-- | Run multiple monitors and succeed if any succeeds.
+-- The result is left-biased.
+anyOf ::
+  [Monitor e a] ->
+  Monitor e a
+anyOf = runConcurrently . asum . fmap Concurrently
+
+-- | Run multiple monitors and succeed only if
+-- all of the monitors succeed. Returns their results.
+allOf :: [Monitor e a] -> Monitor e [a]
+allOf = runConcurrently . traverse Concurrently
diff --git a/tests/Control/Monitor/Predicate.hs b/tests/Control/Monitor/Predicate.hs
new file mode 100644
--- /dev/null
+++ b/tests/Control/Monitor/Predicate.hs
@@ -0,0 +1,67 @@
+{-# LANGUAGE DeriveFunctor #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+
+module Control.Monitor.Predicate
+  ( Predicate (runPredicate),
+    predicate,
+    contramap,
+
+    -- ** Combining predicates
+    and,
+    or,
+  )
+where
+
+import Control.Applicative (Alternative (..))
+import Prelude hiding (and, or)
+
+-- | A 'Predicate' is a function which either fails,
+-- or succeeds by returning data.
+--
+-- This is a generalization of functions of type @a -> 'Bool'@.
+--
+-- Use 'fmap' to map the result of a 'Predicate', and 'contramap'
+-- to map over the input of 'Predicate'.
+--
+-- Use 'predicate' to turn a regular function into a 'Predicate'.
+-- Use 'and' or 'or' to compose 'Predicate's together.
+newtype Predicate e a = Predicate {runPredicate :: e -> Maybe a}
+  deriving (Functor)
+
+predicate :: (e -> Maybe a) -> Predicate e a
+predicate = Predicate
+
+contramap :: (e -> e') -> Predicate e' a -> Predicate e a
+contramap f (Predicate g) = Predicate (g . f)
+
+instance Applicative (Predicate e) where
+  pure a = predicate (const (Just a))
+
+  Predicate f <*> Predicate x =
+    Predicate $ \e -> case (f e, x e) of
+      (Just g, Just a) -> Just $ g a
+      _ -> Nothing
+
+instance Alternative (Predicate e) where
+  empty = predicate (const Nothing)
+
+  Predicate f <|> Predicate g = Predicate $
+    \e -> f e <|> g e
+
+instance Monad (Predicate e) where
+  return = pure
+
+  Predicate x >>= f = Predicate $ \e -> (\a -> runPredicate (f a) e) =<< x e
+
+instance MonadFail (Predicate e) where
+  fail _ = Predicate (const Nothing)
+
+and :: Predicate e a -> Predicate e b -> Predicate e (a, b)
+and = liftA2 (,)
+
+or :: Predicate e a -> Predicate e b -> Predicate e (Either a b)
+or (Predicate left) (Predicate right) =
+  Predicate $ \e -> case (left e, right e) of
+    (Just l, _) -> pure $ Left l
+    (_, Just r) -> pure $ Right r
+    _ -> Nothing
diff --git a/tests/Control/Monitor/Reason.hs b/tests/Control/Monitor/Reason.hs
new file mode 100644
--- /dev/null
+++ b/tests/Control/Monitor/Reason.hs
@@ -0,0 +1,195 @@
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE RecordWildCards #-}
+
+module Control.Monitor.Reason
+  ( -- * Reason
+    Reason (reasonMessage, reasonLabels, reasonIndex, reasonEvent),
+    simpleReason,
+    unexpectedEnd,
+    unexpectedEvent,
+
+    -- * 'Reasons'
+    Reasons (..),
+    oneReason,
+
+    -- * Pretty-printers
+    ppReasons,
+    ppReasonsWithTrace,
+  )
+where
+
+import Data.List (sortOn)
+import Data.List.NonEmpty (NonEmpty)
+import qualified Data.List.NonEmpty as NonEmpty
+import Data.Maybe (mapMaybe)
+import Data.Ord (Down (..))
+import Data.Text (Text)
+import qualified Data.Text as Text
+import Prelude hiding (until)
+
+data Reason event = Reason
+  { reasonMessage :: !Text,
+    reasonLabels :: ![Text],
+    reasonIndex :: !(Maybe Int), -- Nothing = end of trace
+    reasonEvent :: !(Maybe event)
+  }
+
+simpleReason :: Text -> Reason event
+simpleReason msg = Reason msg [] Nothing Nothing
+
+unexpectedEnd :: Reason event
+unexpectedEnd = simpleReason "Unexpected end"
+
+unexpectedEvent :: event -> Reason event
+unexpectedEvent ev = (simpleReason "Unexpected event") {reasonEvent = Just ev}
+
+newtype Reasons event = Reasons {unReasons :: NonEmpty (Reason event)}
+  deriving (Semigroup)
+
+oneReason :: Reason event -> Reasons event
+oneReason = Reasons . NonEmpty.singleton
+
+-- | Render a single failure.
+--
+-- > scenario failed at event 4182:
+-- >     BecameLeader n2 (Term 7)
+-- >   expected: no rival leader in term 7
+-- >   in: leadership phase
+-- >   in: scenario "uncontested election"
+ppReason :: (e -> Text) -> Reason e -> Text
+ppReason ppEvent Reason {..} =
+  Text.intercalate "\n" $
+    [header]
+      <> [indent 4 (ppEvent e) | Just e <- [reasonEvent]]
+      <> [indent 2 ("expected: " <> reasonMessage)]
+      <> [indent 2 ("in: " <> c) | c <- reasonLabels]
+  where
+    header = case reasonIndex of
+      Just i -> "scenario failed at event " <> Text.show i <> ":"
+      Nothing -> "scenario failed at end of trace:"
+
+-- | Render accumulated failures (e.g. from 'anyOf'), megaparsec-style:
+-- failures at the furthest position are shown in full first, on the
+-- heuristic that the branch that got furthest is the one the author meant;
+-- the rest are summarized one per line.
+ppReasons :: (e -> Text) -> Reasons e -> Text
+ppReasons ppEvent (Reasons rs) =
+  case ranked of
+    [r] -> ppReason ppEvent r
+    (r : rest) ->
+      Text.intercalate "\n" $
+        [ppReason ppEvent r]
+          <> ["", "other branches failed earlier:"]
+          <> [indent 2 (summary r') | r' <- rest]
+    [] -> error "ppReasons: impossible, NonEmpty"
+  where
+    -- eof failures rank furthest (the whole trace was consumed)
+    rank r = maybe (Down (Just maxBound)) (Down . Just) (reasonIndex r)
+    ranked = sortOn rank (NonEmpty.toList rs)
+    summary Reason {..} =
+      posStr <> "expected " <> reasonMessage <> ctxStr
+      where
+        posStr = case reasonIndex of
+          Just i -> "at event " <> Text.show i <> ": "
+          Nothing -> "at end of trace: "
+        ctxStr = case reasonLabels of
+          (c : _) -> "  (in: " <> Text.show c <> ")"
+          [] -> ""
+
+indent :: Int -> Text -> Text
+indent n = (Text.replicate n " " <>)
+
+-- | Render accumulated failures together with one shared trace window.
+--
+-- The furthest-position failure ("primary", per the 'ppReasons' heuristic)
+-- is rendered in full. A single excerpt is shown around the primary
+-- position; within it, the primary failure is gutter-marked with @>@ and
+-- any other branch's failure position falling inside the window with @*@.
+-- Remaining branches are then summarized, annotated with @*@ when their
+-- position is visible in the excerpt above.
+--
+-- > scenario failed at event 4182:
+-- >     BecameLeader "n2" 7
+-- >   expected: no rival leader in term 7
+-- >   in: leadership phase
+-- >
+-- > recent events:
+-- >   * 4180 | VoteGranted "n3" "n2" 7
+-- >     4181 | RequestVoteSent "n2" 7
+-- >   > 4182 | BecameLeader "n2" 7
+-- >     4183 | HeartbeatSent "n2" 7
+-- >
+-- > other branches failed earlier:
+-- >   * at event 4180: expected vote from a quorum  (in: election phase)
+-- >     at end of trace: expected heartbeat from n1  (in: leadership phase)
+ppReasonsWithTrace ::
+  (e -> Text) ->
+  -- | radius
+  Int ->
+  -- | indexed trace (or excerpt)
+  [(Int, e)] ->
+  Reasons e ->
+  Text
+ppReasonsWithTrace ppEvent radius trace (Reasons rs) =
+  Text.intercalate "\n" $
+    [ppReason ppEvent primary]
+      <> excerpt
+      <> others
+  where
+    ranked = sortOn (Down . rankPos . reasonIndex) (NonEmpty.toList rs)
+    (primary, rest) = case ranked of
+      (p : r) -> (p, r)
+      [] -> error "ppReasonsWithTrace: impossible, NonEmpty"
+
+    -- eof counts as furthest: the whole trace was consumed
+    rankPos = maybe (Just maxBound) Just
+
+    focus = case reasonIndex primary of
+      Just i -> i
+      Nothing -> case trace of [] -> 0; _ -> fst (last trace)
+
+    window =
+      [ (i, e)
+      | (i, e) <- trace,
+        i >= focus - radius,
+        i <= focus + radius
+      ]
+
+    restPositions = mapMaybe reasonIndex rest
+    visible i = any (\(j, _) -> j == i) window
+
+    excerpt = case window of
+      [] -> []
+      _ -> ["", "recent events:"] <> map row window
+      where
+        width = Text.length (Text.show (maximum (map fst window)))
+        row (i, e) = gutter <> pad width (Text.show i) <> " | " <> ppEvent e
+          where
+            gutter
+              | Just i == reasonIndex primary = "  > "
+              | i `elem` restPositions = "  * "
+              | otherwise = "    "
+
+    others = case rest of
+      [] -> []
+      _ -> ["", "other branches failed earlier:"] <> map line rest
+      where
+        line r = "  " <> mark <> summaryLine r
+          where
+            mark = case reasonIndex r of
+              Just i | visible i -> "* "
+              _ -> "  "
+
+    summaryLine Reason {..} =
+      posStr <> "expected " <> reasonMessage <> ctxStr
+      where
+        posStr = case reasonIndex of
+          Just i -> "at event " <> Text.show i <> ": "
+          Nothing -> "at end of trace: "
+        ctxStr = case reasonLabels of
+          (c : _) -> "  (in: " <> Text.show c <> ")"
+          [] -> ""
+
+pad :: Int -> Text -> Text
+pad w s = Text.replicate (w - Text.length s) " " <> s
diff --git a/tests/Main.hs b/tests/Main.hs
new file mode 100644
--- /dev/null
+++ b/tests/Main.hs
@@ -0,0 +1,22 @@
+{-# LANGUAGE TypeApplications #-}
+
+module Main (main) where
+
+import Data.Proxy (Proxy (..))
+import Test.Distributed.Consensus.Raft (tests)
+import Test.Distributed.Consensus.Raft.Options (BranchingFactor, NumRacyTests, PrintTrace, ScheduleBound)
+import Test.Tasty (defaultIngredients, defaultMainWithIngredients, includingOptions, testGroup)
+import Test.Tasty.Options (OptionDescription (..))
+
+main :: IO ()
+main =
+  defaultMainWithIngredients
+    ( includingOptions
+        [ Option (Proxy @NumRacyTests),
+          Option (Proxy @PrintTrace),
+          Option (Proxy @ScheduleBound),
+          Option (Proxy @BranchingFactor)
+        ]
+        : defaultIngredients
+    )
+    (testGroup "raft-consensus" [tests])
diff --git a/tests/Test/Distributed/Consensus/Raft.hs b/tests/Test/Distributed/Consensus/Raft.hs
new file mode 100644
--- /dev/null
+++ b/tests/Test/Distributed/Consensus/Raft.hs
@@ -0,0 +1,894 @@
+{-# LANGUAGE DerivingStrategies #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE NumericUnderscores #-}
+{-# LANGUAGE OverloadedRecordDot #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE RankNTypes #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE TupleSections #-}
+{-# LANGUAGE TypeApplications #-}
+
+module Test.Distributed.Consensus.Raft
+  ( tests,
+  )
+where
+
+import Control.Applicative ((<|>))
+import Control.Concurrent.Class.MonadMVar (MVar, newEmptyMVar, putMVar, takeMVar)
+import Control.Concurrent.Class.MonadSTM (MonadSTM, TQueue, TVar, atomically, flushTQueue, newTQueueIO, newTVarIO, readTQueue, readTVar, readTVarIO, retry, writeTQueue, writeTVar)
+import qualified Control.Concurrent.Linearizable as Linearizable
+import Control.Exception (Exception)
+import Control.Monad (replicateM, unless, void, when)
+import Control.Monad.Class.MonadAsync (async, asyncThreadId, concurrently_, forConcurrently_, race_, wait, waitCatch, withAsync)
+import Control.Monad.Class.MonadFork (ThreadId, throwTo)
+import Control.Monad.Class.MonadTest (exploreRaces)
+import Control.Monad.Class.MonadTime (getMonotonicTimeNSec)
+import Control.Monad.Class.MonadTimer (threadDelay, timeout)
+import Control.Monad.IOSim (ExplorationOptions, IOSim, exploreSimTrace, traceM)
+import Data.Functor ((<&>))
+import Data.IntMap (IntMap)
+import qualified Data.IntMap.Strict as IntMap
+import qualified Data.IntSet as IntSet
+import Data.List (genericLength, zip4)
+import Data.List.NonEmpty (NonEmpty, nonEmpty)
+import Data.Map.Strict (Map)
+import qualified Data.Map.Strict as Map
+import Data.Maybe (fromJust)
+import Data.Set (Set)
+import qualified Data.Set as Set
+import qualified Data.Text.Lazy as Text
+import Data.Word (Word64)
+import qualified Debug.Trace as Debug
+import Distributed.Consensus.Raft
+  ( ClusterConfiguration (..),
+    ClusterState,
+    Config (..),
+    Implementation (..),
+    LogEntry,
+    LogIndex,
+    Networking (..),
+    Persistence (..),
+    RPC,
+    RPCResult,
+    RaftTrace (..),
+    Snapshot,
+    Term,
+    runRaftServer,
+  )
+import qualified Distributed.Consensus.Raft as Raft
+import Distributed.Consensus.Raft.Admin
+  ( AdminCommandResult (ClusterConfigurationIs),
+    AdminError (AdminNotLeader),
+    AdminImplementation
+      ( AdminImplementation,
+        receiveAdminResponse,
+        sendAdminRequest
+      ),
+    AdminRequest,
+    AdminResponse,
+    Microseconds,
+    RaftAdminT,
+    sessionId,
+    withAdminSession,
+  )
+import qualified Distributed.Consensus.Raft.Admin as Admin
+import Distributed.Consensus.Raft.Client
+  ( ClientError (..),
+    ClientImplementation (..),
+    ClientRequest,
+    ClientResponse,
+    RaftClientT,
+    newRequest,
+    sendClientRequest,
+    withClientSession,
+  )
+import qualified Distributed.Consensus.Raft.Client as Client
+import System.Random (RandomGen, mkStdGen64, randomR, uniformR)
+import Test.Distributed.Consensus.Raft.Client (RaftClientTrace (..), checkLinearizability)
+import Test.Distributed.Consensus.Raft.Options (PrintTrace (..), setNumRacyTests, withExplorationOptions, withPrintTraceOption)
+import Test.Distributed.Consensus.Raft.Properties (FaultInjection (..), allProperties)
+import Test.Distributed.Consensus.Raft.Scenario (checkScenario)
+import Test.StateMachine (Command, Node (Node), Result, State, step)
+import Test.Tasty (TestTree, testGroup)
+import Test.Tasty.QuickCheck
+  ( Arbitrary (arbitrary),
+    Gen,
+    Property,
+    Testable (property),
+    chooseBoundedIntegral,
+    counterexample,
+    elements,
+    forAll,
+    testProperty,
+    vectorOf,
+    (.&&.),
+  )
+import Text.Pretty.Simple (pShow)
+import Prelude hiding (read)
+
+tests :: TestTree
+tests =
+  testGroup
+    "Raft"
+    [ testGroup
+        "Property tests"
+        [ testGroup
+            "No fault injection"
+            [ testClusterWithoutRaces NoFaultInjection,
+              testClusterWithRaces NoFaultInjection
+            ],
+          testGroup
+            "With fault injection"
+            [ testClusterWithoutRaces FaultInjection,
+              testClusterWithRaces FaultInjection
+            ]
+        ]
+    ]
+
+testClusterWithoutRaces :: FaultInjection -> TestTree
+testClusterWithoutRaces faultInjection =
+  withPrintTraceOption $ \printOrNot ->
+    testProperty "Cluster properties without schedule exploration" $
+      propClusterWith
+        printOrNot
+        id -- exploration options don't apply to non-racy simulations
+        faultInjection
+        (pure ())
+
+testClusterWithRaces :: FaultInjection -> TestTree
+testClusterWithRaces faultInjection =
+  withPrintTraceOption $ \printOrNote ->
+    setNumRacyTests $
+      withExplorationOptions $ \updateExplorationOptions ->
+        testProperty "Cluster properties with schedule exploration" $
+          propClusterWith printOrNote updateExplorationOptions faultInjection exploreRaces
+
+propClusterWith ::
+  PrintTrace ->
+  (ExplorationOptions -> ExplorationOptions) ->
+  FaultInjection ->
+  (forall s. IOSim s ()) ->
+  Property
+propClusterWith printTrace updateExplorationOptions faultInjection raceOrNot =
+  property $
+    forAll (genScenarioInputs faultInjection) $
+      \scenarioInputs ->
+        counterexample
+          (Text.unpack $ pShow scenarioInputs)
+          $ exploreSimTrace
+            updateExplorationOptions
+            (scenario scenarioInputs)
+            ( \_ trace ->
+                checkScenario
+                  (allProperties @Command @Node @Result @State faultInjection)
+                  trace
+                  .&&. checkLinearizability trace
+            )
+  where
+    debug :: forall a. (Show a) => a -> a
+    debug = case printTrace of
+      PrintTrace False -> id
+      PrintTrace True -> Debug.traceShowId
+    scenario scenarioInputs =
+      testHarness debug scenarioInputs $ \(harness :: Harness s) -> do
+        -- In order to detect infinite loops, especially in CI,
+        -- we use a *very generous* scenario timeout.
+        let timeStep = max clientRetryTick scenarioInputs.electionTimeoutUpperBound
+            scenarioTimeUpperBound =
+              10 * timeStep -- Baseline
+              -- To ensure all lone nodes have time to join, and then leave
+                + 3
+                  * maybe 0 maximum (nonEmpty $ sum <$> scenarioInputs.loneNodesWait)
+                -- To ensure all client requests have time to be served, we wait
+                -- for the client with the most commands as if ever command
+                -- was retried for the maximum number of times.
+                + maybe 0 maximum (nonEmpty $ genericLength <$> IntMap.elems scenarioInputs.commands)
+                  * ( clientRequestTimeout scenarioInputs
+                        + clientRetryBudget scenarioInputs
+                        + clientRetryTick
+                    )
+                -- To ensure membership changes have time to land
+                + 3
+                  * 6 -- 6 attempts
+                  * timeStep
+
+        race_
+          (threadDelay (fromIntegral scenarioTimeUpperBound) >> fail "Possible infinite loop detected")
+          ( do
+              withAdminSession harness.hAdminNode harness.hAdminSpec $ \runAdminAction ->
+                -- Run servers until the clients are done interacting
+                withAsync (runServers harness runAdminAction) $ \_ -> do
+                  withAsync (runClients harness scenarioInputs) $ \clients -> do
+                    wait clients
+                    -- We give an opportunity to all lone servers to leave the cluster
+                    -- properly before we shut everyone down.
+                    let shutDownNode node =
+                          let tryShutDown :: Int -> IOSim s ()
+                              tryShutDown 0 = pure ()
+                              tryShutDown attemptsLeft =
+                                runAdminAction (Admin.shutDown >>= Admin.sendAdminCommand scenarioInputs.electionTimeoutUpperBound node <&> void)
+                                  >>= either (const (tryShutDown (attemptsLeft - 1))) pure
+                           in tryShutDown 3
+
+                    forConcurrently_ harness.loneServers $ \(server, isDone, _, _) -> do
+                      takeMVar isDone
+                      shutDownNode server.sConfig.nodeId
+                    forConcurrently_ harness.clusterServers $ \server ->
+                      shutDownNode server.sConfig.nodeId
+          )
+
+    runServers ::
+      Harness s ->
+      (forall a. RaftAdminT Node (IOSim s) a -> IOSim s a) ->
+      IOSim s ()
+    runServers harness runAdminAction = do
+      -- This is the point where we can mark this thread "racy"
+      -- (by default, it is not).
+      --
+      -- The benefit of NOT marking this racy is to explore many more of the initial
+      -- parameter space (more 'ScenarioInputs's).
+      --
+      -- The benefit of marking this racy is to explore races within fewer initial
+      -- conditions
+      raceOrNot
+      concurrently_
+        -- Cluster nodes
+        ( forConcurrently_ (IntMap.elems harness.clusterServers) $ \server ->
+            runServerWithFaults
+              server
+              (Raft.InCluster $ Set.fromList (map fromIntegral $ IntMap.keys harness.clusterServers))
+        )
+        -- Lone nodes
+        ( forConcurrently_ (IntMap.elems harness.loneServers) $ \(server, isDone, waitToJoin, waitToLeave) ->
+            concurrently_
+              ( do
+                  let node = server.sConfig.nodeId
+                      -- A node that stayed in the cluster, so we have somebody
+                      -- to ask about the committed configuration. Asking the
+                      -- node that is leaving would never work: it never learns
+                      -- that it is out.
+                      contact =
+                        fromIntegral $
+                          fst $
+                            fromJust $
+                              IntSet.minView (IntMap.keysSet harness.clusterServers)
+                      betweenAttempts = snd server.sConfig.electionTimeoutRange
+                      requestTimeout = 3 * server.sConfig.heartBeatTimeout
+
+                  threadDelay (fromIntegral waitToJoin)
+                  untilJoined runAdminAction contact requestTimeout betweenAttempts node $
+                    Admin.joinCluster contact >>= Admin.sendAdminCommand maxBound node
+
+                  threadDelay (fromIntegral waitToLeave)
+                  untilLeft runAdminAction contact requestTimeout betweenAttempts node $
+                    Admin.leaveCluster >>= Admin.sendAdminCommand maxBound node
+
+                  putMVar isDone ()
+              )
+              (runServerWithFaults server Raft.LoneNode)
+        )
+
+    runClients ::
+      Harness s ->
+      ScenarioInputs ->
+      IOSim s ()
+    runClients harness scenarioInputs =
+      forConcurrently_ (IntMap.toList harness.hClients) $ \(clientNode, clientImplementation) ->
+        withClientSession (fromIntegral clientNode) clientImplementation $ \runClientAction ->
+          runClient
+            (fromIntegral clientNode)
+            runClientAction
+            -- In principle, there is no upper bound on how long a
+            -- client can wait to receive a message. I'm putting a generous
+            -- bound here because I have seen situations where the client never
+            -- receives a reply (due to a bug)
+            (clientRequestTimeout scenarioInputs)
+            (clientRetryBudget scenarioInputs)
+            (scenarioInputs.commands IntMap.! (clientNode - minClientNode))
+      where
+        minClientNode = IntSet.findMin $ IntMap.keysSet harness.hClients
+
+        runClient ::
+          Node ->
+          (forall a. RaftClientT Command Node Result (IOSim s) a -> IOSim s a) ->
+          -- \| Single request timeout
+          Microseconds ->
+          -- \| Timeout for retries
+          Microseconds ->
+          [Command] ->
+          IOSim s ()
+        runClient clientNode runRequest maxTime retryBudget = go (Set.singleton (0 :: Node))
+          where
+            -- \| Given a node, and a set of known nodes, deterministically pick another
+            -- node from the set.
+            nextCandidate :: Node -> Set Node -> Maybe Node
+            nextCandidate failed known = Set.lookupGT failed known <|> Set.lookupMin known
+
+            go _ [] = pure ()
+            go knownNodes (command : rest) = do
+              req <- runRequest (newRequest command)
+              start <- getMonotonicTimeNSec
+              attempt req knownNodes retryBudget 0 >>= \case
+                Just result -> do
+                  end <- getMonotonicTimeNSec
+                  traceM (MkRaftClientTrace clientNode (Linearizable.MkEvent start end (command, Just result)))
+                Nothing ->
+                  traceM (MkRaftClientTrace clientNode (Linearizable.MkEvent start maxBound (command, Nothing @Result)))
+              go knownNodes rest
+              where
+                attempt payload nodeSet remaining target = do
+                  threadDelay (fromIntegral clientRetryTick)
+                  runRequest (sendClientRequest maxTime target payload)
+                    >>= \case
+                      Left Timeout ->
+                        giveUp $
+                          "no response at all within "
+                            <> show (toInteger maxTime)
+                            <> " microseconds"
+                      -- Command needs to be retried but on another target
+                      (Left err@(Redirect otherNode))
+                        | remaining <= clientRetryTick ->
+                            giveUp $
+                              "retried for "
+                                <> show (toInteger retryBudget)
+                                <> " microseconds, last response was "
+                                <> show err
+                        | otherwise -> attempt payload (Set.insert otherNode nodeSet) (remaining - clientRetryTick) otherNode
+                      (Left err@NoKnownLeader)
+                        | remaining <= clientRetryTick ->
+                            giveUp $
+                              "retried for "
+                                <> show (toInteger retryBudget)
+                                <> " microseconds, last response was "
+                                <> show err
+                        | otherwise -> case nextCandidate target nodeSet of
+                            Nothing -> giveUp "No known nodes to query"
+                            Just candidate -> attempt payload nodeSet (remaining - clientRetryTick) candidate
+                      (Right (_, result)) -> pure (Just result)
+                  where
+                    giveUp why =
+                      case faultInjection of
+                        -- In a real Raft cluster (i.e. subject to faults), there's no guarantee of liveness.
+                        -- That's the price to pay for strong consistency.
+                        --
+                        -- This means we can be stuck in a situation where a cluster is so faulty, that it
+                        -- literally cannot serve any requests -- think of an election + crash loop. Thus,
+                        -- giving up in this context means letting go.
+                        --
+                        -- A Raft cluster that is NOT subject to faults has no excuse for not eventually
+                        -- service client requests, hence the use of 'fail'
+                        FaultInjection -> pure Nothing
+                        NoFaultInjection ->
+                          fail $
+                            "Client could not get "
+                              <> show command
+                              <> " served, and no node in this scenario can crash: "
+                              <> why
+
+data ScenarioInputs
+  = ScenarioInputs
+  { heartbeatTimeout :: Microseconds,
+    electionTimeoutLowerBound :: Microseconds,
+    electionTimeoutUpperBound :: Microseconds,
+    seeds :: [Word64],
+    faultProbabilities :: [Double],
+    partitionSeed :: Word64,
+    partitionProbability :: Double,
+    numInitialClusterNodes :: Int,
+    numInitialLoneNodes :: Int,
+    numClientNodes :: Int,
+    loneNodesWait :: [(Microseconds, Microseconds)],
+    -- | Zero-indexed commands per client node.
+    commands :: IntMap [Command]
+  }
+  deriving (Eq, Show)
+
+genScenarioInputs :: FaultInjection -> Gen ScenarioInputs
+genScenarioInputs faultInjection = do
+  clusterSize <- elements [1, 2, 3, 4, 5]
+  numLoneNodes <- elements [0, 1]
+  numClients <- elements [1, 2, 3]
+  ss <- vectorOf (clusterSize + numLoneNodes) (chooseBoundedIntegral (0, 1_000_000))
+  hb <- chooseBoundedIntegral (clientRetryTick, 200_000)
+  -- Making the lower election timeout possibly shorter than the heartbeat timeout
+  -- allows to have terms with no leaders elected
+  etolb <- chooseBoundedIntegral (round $ (0.9 :: Double) * fromIntegral hb, hb * 10)
+  etoub <- chooseBoundedIntegral (max etolb (round $ (1.1 :: Double) * fromIntegral hb), 2 * etolb)
+  faultProb <- case faultInjection of
+    FaultInjection -> vectorOf (clusterSize + numLoneNodes) (elements [0.0, 0.001, 0.01])
+    NoFaultInjection -> vectorOf (clusterSize + numLoneNodes) (pure 0)
+
+  pSeed <- chooseBoundedIntegral (0, 1_000_000)
+  pProb <- case faultInjection of
+    FaultInjection -> elements [0.0, 0.2]
+    NoFaultInjection -> pure 0
+  loneWaits <-
+    vectorOf
+      numLoneNodes
+      ( (,)
+          <$> chooseBoundedIntegral (etoub, 3 * etoub)
+          <*> chooseBoundedIntegral (etoub, 3 * etoub)
+      )
+
+  cmds <- replicateM numClients $ flip vectorOf (arbitrary @Command) =<< chooseBoundedIntegral (1, 15)
+  pure $
+    ScenarioInputs
+      { heartbeatTimeout = hb,
+        electionTimeoutLowerBound = etolb,
+        electionTimeoutUpperBound = etoub,
+        seeds = ss,
+        faultProbabilities = faultProb,
+        partitionSeed = pSeed,
+        partitionProbability = pProb,
+        numInitialClusterNodes = clusterSize,
+        numInitialLoneNodes = numLoneNodes,
+        numClientNodes = numClients,
+        loneNodesWait = loneWaits,
+        commands =
+          IntMap.fromList $
+            zip
+              [0 .. numClients - 1]
+              cmds
+      }
+
+data TestFault = TestFault deriving (Show)
+
+instance Exception TestFault
+
+data Server s
+  = MkServer
+  { sConfig :: Config Node,
+    sSpec :: Implementation Command Node Result State (IOSim s),
+    sFaultInjector :: TVar (IOSim s) (Maybe (ThreadId (IOSim s))) -> IOSim s ()
+  }
+
+runServerWithFaults :: Server s -> ClusterState Node -> IOSim s ()
+runServerWithFaults server clusterState = do
+  tidVar <- newTVarIO Nothing
+  concurrently_
+    (server.sFaultInjector tidVar)
+    ( supervisor tidVar $
+        runRaftServer
+          server.sConfig
+          clusterState
+          mempty
+          server.sSpec
+    )
+  where
+    -- Restart a workload on failure, except if it returned
+    -- normally.
+    supervisor tidVar workload = do
+      a <- async workload
+      atomically $ writeTVar tidVar (Just (asyncThreadId a))
+      r <- waitCatch a
+      atomically $ writeTVar tidVar Nothing
+      case r of
+        Left _ -> do
+          server.sSpec.tracer (Crashed server.sConfig.nodeId)
+          threadDelay $ fromIntegral clientRetryTick -- simulate a restart
+          supervisor tidVar workload
+        Right () -> pure ()
+
+-- | The pause before each client attempt, and the granularity in which the
+-- retry budget below is spent.
+clientRetryTick :: Microseconds
+clientRetryTick = 10_000
+
+-- | How long to wait for a resposne to a single request
+clientRequestTimeout :: ScenarioInputs -> Microseconds
+clientRequestTimeout inputs = 10 * inputs.electionTimeoutUpperBound
+
+-- | How long the client keeps retrying one command before the scenario fails.
+clientRetryBudget :: ScenarioInputs -> Microseconds
+clientRetryBudget inputs = max 1_000_000 (3 * inputs.electionTimeoutUpperBound)
+
+data MembershipDirection
+  = Joining
+  | Leaving
+  deriving (Eq)
+
+untilJoined,
+  untilLeft ::
+    -- | Run an admin action
+    (forall a. RaftAdminT Node (IOSim s) a -> IOSim s a) ->
+    -- | Leader if you know it, or initial contact
+    Node ->
+    -- | How long to wait for one admin request to be answered.
+    Microseconds ->
+    -- | How long to pause between attempts.
+    Microseconds ->
+    -- | The node whose membership should change
+    Node ->
+    -- | The command that requests the change
+    RaftAdminT Node (IOSim s) r ->
+    IOSim s ()
+untilJoined = untilMembership Joining
+untilLeft = untilMembership Leaving
+
+untilMembership ::
+  forall s r.
+  MembershipDirection ->
+  -- | Run an admin action
+  (forall a. RaftAdminT Node (IOSim s) a -> IOSim s a) ->
+  -- | Leader if you know it, or initial contact
+  Node ->
+  -- | How long to wait for one admin request to be answered.
+  Microseconds ->
+  -- | How long to pause between attempts.
+  Microseconds ->
+  -- | The node whose membership should change
+  Node ->
+  -- | The command that requests the change
+  RaftAdminT Node (IOSim s) r ->
+  IOSim s ()
+untilMembership direction runAdminAction initialContact requestTimeout betweenAttempts node command = do
+  go 4 initialContact
+  where
+    -- An admin action blocks until it gets a response, and the node being
+    -- asked may well be down, so every attempt needs a bound.
+    attempt :: forall a. RaftAdminT Node (IOSim s) a -> IOSim s (Maybe a)
+    attempt = timeout (fromIntegral requestTimeout) . runAdminAction
+
+    isDone = case direction of
+      Joining -> Set.member node
+      Leaving -> Set.notMember node
+
+    go :: Int -> Node -> IOSim s ()
+    go attemptsLeft contact
+      | attemptsLeft <= 0 = pure ()
+      | otherwise =
+          attempt (Admin.getClusterConfiguration >>= Admin.sendAdminCommand maxBound contact) >>= \case
+            -- Settled: the configuration says what we wanted it to say.
+            Just (Right (ClusterConfigurationIs (Simple cluster)))
+              | isDone cluster -> pure ()
+            -- A settled configuration that is not the one we want. This is the
+            -- only state in which asking for the change is the right move.
+            Just (Right (ClusterConfigurationIs (Simple _))) -> attempt command >> waitAndRetry contact
+            -- Only the leader answers a configuration read, so follow the
+            -- redirect. This still costs an attempt, so a pair of nodes that
+            -- disagree about who leads cannot keep us here forever.
+            Just (Left (AdminNotLeader (Just leader)))
+              | leader /= contact -> go (attemptsLeft - 1) leader
+            -- Either a change is already in flight (a 'Joint' configuration) or
+            -- nobody could tell us. Do not ask again on an unknown state: that
+            -- is how a request gets issued after the change has already landed,
+            -- and such a request has nothing left to happen for it. Wait and
+            -- re-read instead.
+            _ -> waitAndRetry contact
+      where
+        waitAndRetry c = do
+          threadDelay (fromIntegral betweenAttempts)
+          go (attemptsLeft - 1) c
+
+type Mailbox s m = IntMap (TQueue (IOSim s) m)
+
+type TopologyConstraints s = TVar (IOSim s) (Map Node (Set Node))
+
+data NetworkFabric s
+  = MkNetworkFabric
+  { rpcMailbox :: Mailbox s (RPC Command Node State),
+    rpcResultsMailbox :: Mailbox s (RPCResult Node Result),
+    requestsMailbox :: Mailbox s (ClientRequest Command Node),
+    responsesMailbox :: Mailbox s (ClientResponse Node Result),
+    adminMailbox :: Mailbox s (AdminRequest Node),
+    adminResponsesMailbox :: Mailbox s (AdminResponse Node),
+    -- Simulating a network partition by prevent messages sent
+    -- from given nodes to reach other nodes.
+    --
+    -- This design allows for asymmetric network partisions, since
+    -- Map.fromList [A, Set.fromList [B]] means A can't send messages
+    -- to B, but B  can send messages to A. Not clear if this is representative
+    -- of something that is possible, but it comes for free.
+    topologyConstraints :: TopologyConstraints s
+  }
+
+data Environment s
+  = MkResources
+  { networkFabric :: NetworkFabric s,
+    logPersistence :: IntMap (TVar (IOSim s) (Map LogIndex (Term, LogEntry Command Node))),
+    votePersistence :: IntMap (TVar (IOSim s) (Map Term Node)),
+    termPersistence :: IntMap (TVar (IOSim s) Term),
+    snapshotPersistence :: IntMap (TVar (IOSim s) (Maybe (Snapshot Node State))),
+    commitIndexPersistence :: IntMap (TVar (IOSim s) LogIndex)
+  }
+
+newEnvironment :: Set Node -> IOSim s (Environment s)
+newEnvironment nodes =
+  MkResources
+    <$> ( MkNetworkFabric
+            <$> newMailbox
+            <*> newMailbox
+            <*> newMailbox
+            <*> newMailbox
+            <*> newMailbox
+            <*> newMailbox
+            <*> newTVarIO mempty -- no contraints at first
+        )
+    <*> newPersistence mempty
+    <*> newPersistence mempty
+    <*> newPersistence 0
+    <*> newPersistence Nothing
+    <*> newPersistence 0
+  where
+    newMailbox =
+      IntMap.fromList
+        <$> traverse (\n -> (fromIntegral n,) <$> newTQueueIO) (Set.toList nodes)
+    newPersistence def =
+      IntMap.fromList
+        <$> traverse (\n -> (fromIntegral n,) <$> newTVarIO def) (Set.toList nodes)
+
+mkServer :: (forall a. (Show a) => a -> a) -> Environment s -> Microseconds -> Microseconds -> Microseconds -> Double -> Word64 -> Node -> Server s
+mkServer debug resources hbto etolb etoub faultProb seed node =
+  MkServer
+    { sConfig =
+        MkConfig
+          { nodeId = node,
+            electionTimeoutRange = (etolb, etoub),
+            heartBeatTimeout = hbto,
+            randomSeed = seed,
+            maxLogLength = Just 5 -- TODO: make configurable
+          },
+      sSpec =
+        Implementation
+          { persistence =
+              Persistence
+                { readLogEntriesFrom = readLogEntriesFromTest resources.logPersistence,
+                  writeLogEntry = writeLogEntryTest resources.logPersistence,
+                  truncateLogEntriesFrom = truncateLogEntriesTest resources.logPersistence,
+                  readTerm = readTest resources.termPersistence,
+                  writeTerm = writeTest resources.termPersistence,
+                  readVotedFor = readVotedForTest resources.votePersistence,
+                  writeVotedFor = writeVotedForTest resources.votePersistence,
+                  readSnapshot = readTest resources.snapshotPersistence,
+                  writeSnapshot = \self snapshot -> writeTest resources.snapshotPersistence self (Just snapshot),
+                  readCommitIndex = readTest resources.commitIndexPersistence,
+                  writeCommitIndex = writeTest resources.commitIndexPersistence
+                },
+            stateMachine = step,
+            networking =
+              Networking
+                { sendRPC = send resources.networkFabric.rpcMailbox resources.networkFabric.topologyConstraints node,
+                  sendRPCResult = send resources.networkFabric.rpcResultsMailbox resources.networkFabric.topologyConstraints node,
+                  sendClientResponse = send resources.networkFabric.responsesMailbox resources.networkFabric.topologyConstraints node,
+                  sendAdminResponse = send resources.networkFabric.adminResponsesMailbox resources.networkFabric.topologyConstraints node,
+                  receiveRPC = receive resources.networkFabric.rpcMailbox node,
+                  receiveRPCResult = receive resources.networkFabric.rpcResultsMailbox node,
+                  receiveClientRequests = receiveAll resources.networkFabric.requestsMailbox node,
+                  receiveAdminRequest = receive resources.networkFabric.adminMailbox node
+                },
+            -- We debug-print events here, rather than in `checkScenario`,
+            -- because `checkScenario` can fail and produce no trace.
+            tracer = traceM . debug
+          },
+      sFaultInjector = faultInjector faultProb seed
+    }
+
+faultInjector ::
+  -- | Fault probability
+  Double ->
+  -- | Random seed
+  Word64 ->
+  TVar (IOSim s) (Maybe (ThreadId (IOSim s))) ->
+  IOSim s ()
+faultInjector faultProb seed tidVar = go (mkStdGen64 seed)
+  where
+    go gen = do
+      threadDelay 10_000
+      let (failProb, nextGen) = uniformR @Double (0, 1) gen
+      tid <- atomically $ readTVar tidVar >>= maybe retry pure
+      when (failProb <= faultProb) (throwTo tid TestFault)
+      go nextGen
+
+data Harness s
+  = MkHarness
+  { clusterServers :: IntMap (Server s),
+    loneServers :: IntMap (Server s, MVar (IOSim s) (), Microseconds, Microseconds),
+    hClients :: IntMap (ClientImplementation Command Node Result (IOSim s)),
+    hAdminNode :: Node,
+    hAdminSpec :: AdminImplementation Node (IOSim s)
+  }
+
+testHarness ::
+  forall s.
+  (forall a. (Show a) => a -> a) ->
+  ScenarioInputs ->
+  (Harness s -> IOSim s ()) ->
+  IOSim s ()
+testHarness
+  debug
+  (ScenarioInputs hb etlb etup s faultProbs pSeed pProb numClusterNodes numLoneNodes numClients loneWaits _commands)
+  withHarness = do
+    resources <- newEnvironment allNodes
+
+    let mkServer' :: Double -> Word64 -> Node -> Server s
+        mkServer' = mkServer debug resources hb etlb etup
+    isDones <- replicateM numLoneNodes newEmptyMVar
+
+    withAsync (networkPartitioner (networkFabric resources)) $ \_ ->
+      withHarness
+        MkHarness
+          { clusterServers =
+              IntMap.fromList $
+                map (\(faultProb, serverSeed, n) -> (n, mkServer' faultProb serverSeed (fromIntegral n))) serverNodesWithMeta,
+            loneServers =
+              IntMap.fromList $
+                zipWith
+                  ( curry
+                      ( \((faultProb, serverSeed, (waitBeforeJoin, waitBeforeLeave), n), isDone) ->
+                          ( n,
+                            ( mkServer' faultProb serverSeed (fromIntegral n),
+                              isDone,
+                              waitBeforeJoin,
+                              waitBeforeLeave
+                            )
+                          )
+                      )
+                  )
+                  loneNodesWithMeta
+                  isDones,
+            hClients = IntMap.fromList [(clientNode, clientSpec (networkFabric resources) (Node clientNode)) | clientNode <- clientNodes],
+            hAdminNode = adminNode,
+            hAdminSpec = adminSpec (networkFabric resources)
+          }
+    where
+      allNodes =
+        mconcat
+          [ Set.fromList (fromIntegral <$> serverNodes),
+            Set.fromList (fromIntegral <$> loneNodes),
+            Set.fromList (fromIntegral <$> clientNodes),
+            Set.singleton adminNode
+          ]
+
+      adminNode = -1
+
+      serverNodes = [0 .. numClusterNodes - 1]
+      serverNodesWithMeta = zip3 (take numClusterNodes faultProbs) (take numClusterNodes s) serverNodes
+
+      loneNodes = [numClusterNodes .. numClusterNodes + numLoneNodes - 1]
+      loneNodesWithMeta = zip4 (drop numClusterNodes faultProbs) (drop numClusterNodes s) loneWaits loneNodes
+
+      -- Assuming there will never be 1M server nodes in these tests
+      clientNodes =
+        let start = numClusterNodes + numLoneNodes + 1
+         in [start .. start + numClients - 1]
+
+      clientSpec network clientNode =
+        ClientImplementation
+          { sendRequest = send network.requestsMailbox network.topologyConstraints clientNode,
+            receiveResponse =
+              receive network.responsesMailbox clientNode,
+            Client.generateSessionId = \node -> do
+              -- That's the simplest way I know how to introduce randomness in IOSim
+              now <- getMonotonicTimeNSec
+              pure $ sessionId now $ fromIntegral node
+          }
+
+      adminSpec network =
+        AdminImplementation
+          { sendAdminRequest = send network.adminMailbox network.topologyConstraints adminNode,
+            receiveAdminResponse = receive network.adminResponsesMailbox adminNode,
+            Admin.generateSessionId = pure . sessionId maxBound . fromIntegral
+          }
+
+      networkPartitioner network = go (mkStdGen64 pSeed)
+        where
+          go gen = do
+            let (w, newGen) = uniformR (0, fromIntegral $ 10 * hb) gen
+            threadDelay w
+            let (constraintGraph, newGen') = randomGraph pProb allNodes newGen
+            atomically $ writeTVar (topologyConstraints network) constraintGraph
+            go newGen'
+
+writeLogEntryTest ::
+  (MonadSTM m) =>
+  IntMap (TVar m (Map LogIndex (Term, LogEntry Command Node))) ->
+  Node ->
+  [(Term, LogIndex, LogEntry Command Node)] ->
+  m ()
+writeLogEntryTest storage self batch = case IntMap.lookup (fromIntegral self) storage of
+  Nothing -> error $ "Persistence badly configured: missing node " <> show self
+  Just var -> atomically $ do
+    log' <- readTVar var
+    -- Overwriting the log with new conflicting entries is important to ensure below
+    writeTVar var (Map.fromList [(ix, (term, entry)) | (term, ix, entry) <- batch] <> log')
+
+truncateLogEntriesTest ::
+  (MonadSTM m) =>
+  IntMap (TVar m (Map LogIndex (Term, LogEntry Command Node))) ->
+  Node ->
+  LogIndex ->
+  m ()
+truncateLogEntriesTest storage self truncateFrom = case IntMap.lookup (fromIntegral self) storage of
+  Nothing -> error $ "Persistence badly configured: missing node " <> show self
+  Just var -> atomically $ do
+    log' <- readTVar var
+    writeTVar var (log' `Map.restrictKeys` Set.fromAscList [0 .. pred truncateFrom])
+
+readLogEntriesFromTest :: (MonadSTM m) => IntMap (TVar m (Map LogIndex (Term, LogEntry Command Node))) -> Node -> LogIndex -> m [(Term, LogIndex, LogEntry Command Node)]
+readLogEntriesFromTest storage self logIndex = case IntMap.lookup (fromIntegral self) storage of
+  Nothing -> error $ "Persistence badly configured: missing node " <> show self
+  Just var -> readTVarIO var <&> fmap (\(ix, (term, entry)) -> (term, ix, entry)) . Map.toAscList . Map.filterWithKey (\ix _ -> ix >= logIndex)
+
+writeVotedForTest :: (MonadSTM m) => IntMap (TVar m (Map Term Node)) -> Node -> Term -> Maybe Node -> m ()
+writeVotedForTest storage self term value = case IntMap.lookup (fromIntegral self) storage of
+  Nothing -> error $ "Persistence badly configured: missing node " <> show self
+  Just var -> atomically $ do
+    m <- readTVar var
+    writeTVar var (Map.alter (const value) term m)
+
+readVotedForTest :: (MonadSTM m) => IntMap (TVar m (Map Term Node)) -> Node -> Term -> m (Maybe Node)
+readVotedForTest storage self term = case IntMap.lookup (fromIntegral self) storage of
+  Nothing -> error $ "Persistence badly configured: missing node " <> show self
+  Just var -> Map.lookup term <$> readTVarIO var
+
+writeTest :: (MonadSTM m) => IntMap (TVar m a) -> Node -> a -> m ()
+writeTest storage self value = case IntMap.lookup (fromIntegral self) storage of
+  Nothing -> error $ "Persistence badly configured: missing node " <> show self
+  Just var -> atomically $ writeTVar var value
+
+readTest :: (MonadSTM m) => IntMap (TVar m a) -> Node -> m a
+readTest storage self = case IntMap.lookup (fromIntegral self) storage of
+  Nothing -> error $ "Persistence badly configured: missing node " <> show self
+  Just var -> readTVarIO var
+
+send ::
+  (MonadSTM m) =>
+  IntMap (TQueue m a) ->
+  TVar m (Map Node (Set Node)) ->
+  Node ->
+  Node ->
+  a ->
+  m ()
+send mailbox networkConstraints sender receipient message =
+  case IntMap.lookup (fromIntegral receipient) mailbox of
+    Nothing -> error $ "Mailbox badly configured: missing node " <> show receipient
+    Just queue -> atomically $ do
+      constraints <- readTVar networkConstraints
+      unless (Set.member receipient $ Map.findWithDefault Set.empty sender constraints) $
+        writeTQueue queue message
+
+receive :: (MonadSTM m) => IntMap (TQueue m a) -> Node -> m a
+receive mailbox node =
+  case IntMap.lookup (fromIntegral node) mailbox of
+    Nothing -> error $ "Mailbox badly configured: missing node " <> show node
+    Just queue -> atomically $ readTQueue queue
+
+receiveAll :: (MonadSTM m) => IntMap (TQueue m a) -> Node -> m (NonEmpty a)
+receiveAll mailbox node =
+  case IntMap.lookup (fromIntegral node) mailbox of
+    Nothing -> error $ "Mailbox badly configures: missing node " <> show node
+    Just queue ->
+      atomically $
+        flushTQueue queue <&> nonEmpty >>= \case
+          Nothing -> retry
+          Just xs -> pure xs
+
+-- Random utilities
+
+randomGraph ::
+  (RandomGen g) =>
+  -- | Probability of a node being selected in this graph
+  Double ->
+  Set Node ->
+  g ->
+  (Map Node (Set Node), g)
+randomGraph p nodes gen =
+  go gen candidates Map.empty
+  where
+    candidates =
+      [ (src, dst)
+      | src <- Set.toList nodes,
+        dst <- Set.toList nodes,
+        src /= dst
+      ]
+
+    go g [] graph = (graph, g)
+    go g ((src, dst) : rest) graph =
+      let (r, g') = randomR (0.0, 1.0) g
+          graph'
+            | r < p =
+                Map.insertWith Set.union src (Set.singleton dst) graph
+            | otherwise =
+                graph
+       in go g' rest graph'
diff --git a/tests/Test/Distributed/Consensus/Raft/Client.hs b/tests/Test/Distributed/Consensus/Raft/Client.hs
new file mode 100644
--- /dev/null
+++ b/tests/Test/Distributed/Consensus/Raft/Client.hs
@@ -0,0 +1,106 @@
+{-# LANGUAGE ScopedTypeVariables #-}
+
+module Test.Distributed.Consensus.Raft.Client
+  ( checkLinearizability,
+
+    -- * Client tracing
+    RaftClientTrace (..),
+  )
+where
+
+import Control.Concurrent.Linearizable (Model (..), linearizable, operation, timestampReq)
+import qualified Control.Concurrent.Linearizable as Linearizable
+import Control.Monad.IOSim (SimEvent, SimEventType (EventLog), SimResult, Trace, selectTraceEvents)
+import Data.Dynamic (Typeable, fromDynamic)
+import Data.Function ((&))
+import Data.List (foldl', sortOn)
+import Data.Word (Word64)
+import Distributed.Consensus.Raft
+  ( runStateMachineStep,
+  )
+import Test.StateMachine (Command (..), Key, Node (..), Result, State, step)
+import Test.Tasty.QuickCheck (Property, counterexample, property, (.&&.))
+
+checkLinearizability :: Trace (SimResult a) SimEvent -> Property
+checkLinearizability trace' =
+  -- In order to reduce the state space of the linearizability checker,
+  -- we check the linearizability of events related to each
+  -- individual key independently.
+  Data.List.foldl'
+    (.&&.)
+    (property True)
+    -- The scenario inputs are such that there's always at least one
+    -- client with at least one command. Therefore, if 'clientEvents' is
+    -- null, we've got a problem, since an empty history is trivially linearizable.
+    ( counterexample "No client events generated" (not (null clientEvents))
+        : (checkLinearizabilityOnKey <$> enumFromTo minBound maxBound)
+    )
+  where
+    (clientEvents :: [RaftClientTrace Command Node Result]) = raftClientTrace trace'
+
+    checkLinearizabilityOnKey :: Key -> Property
+    checkLinearizabilityOnKey key =
+      let history =
+            [ (effectiveNode, event)
+            | (ix, MkRaftClientTrace (Node node) event) <- zip [0 :: Int ..] clientEvents,
+              commandKey (fst $ operation event) == key,
+              -- There's a problem with requests that never get a response.
+              -- I consider that they may apply at any time after the request
+              -- is sent. However, due to the way 'linearizable' works, the
+              -- 'Event' associated with a timed-out request blocks requests
+              -- sent after the timed-out one from being re-ordered.
+              --
+              -- The solution I have here is to let the timed-out request be re-orderable
+              -- by associating it with a unique node 'effectiveNode' with only this event.
+              -- The use of 'ix' makes this unique.
+              --
+              -- This concern should be included into 'linearizable' itself
+              let effectiveNode = case snd (operation event) of
+                    Just _ -> (node, Nothing)
+                    Nothing -> (node, Just ix)
+            ]
+              & sortOn (timestampReq . snd)
+       in counterexample
+            ("Client history for key " <> show key <> " not linearizable: " <> show history)
+            ( linearizable
+                model
+                history
+            )
+      where
+        commandKey (Insert k _) = k
+        commandKey (Delete k) = k
+        commandKey (Get k) = k
+    -- TODO: extend model to accept events where there was no 'Result' (e.g. timeout),
+    --       in which case the state of a particular key is considered 'unknown'.
+    --
+    --       To do this, 'RaftClientTrace' would have to be extended to represent 'Maybe result'
+    model :: Model State (Command, Maybe Result)
+    model =
+      MkModel
+        { initialState = mempty :: State,
+          apply = \(command, observedResult) state ->
+            let (newState, expectedResult) = runStateMachineStep (Test.StateMachine.step command) state
+             in case observedResult of
+                  -- Result never received; we assume that it has succeeded and continue
+                  Nothing -> Just newState
+                  Just result
+                    | result == expectedResult -> Just newState
+                    | otherwise -> Nothing
+        }
+
+raftClientTrace ::
+  (Typeable entry, Typeable result, Typeable node) =>
+  Trace (SimResult a) SimEvent -> [RaftClientTrace entry node result]
+raftClientTrace =
+  selectTraceEvents
+    ( \_ ev -> case ev of
+        EventLog dyn -> fromDynamic dyn
+        _ -> Nothing -- internal io-sim event
+    )
+
+data RaftClientTrace entry node result
+  = MkRaftClientTrace
+  { rctNode :: node,
+    rctEvent :: Linearizable.Event Word64 (entry, Maybe result)
+  }
+  deriving (Eq, Show)
diff --git a/tests/Test/Distributed/Consensus/Raft/Options.hs b/tests/Test/Distributed/Consensus/Raft/Options.hs
new file mode 100644
--- /dev/null
+++ b/tests/Test/Distributed/Consensus/Raft/Options.hs
@@ -0,0 +1,92 @@
+module Test.Distributed.Consensus.Raft.Options
+  ( setNumRacyTests,
+    withExplorationOptions,
+    withPrintTraceOption,
+    NumRacyTests,
+    ScheduleBound,
+    BranchingFactor,
+    PrintTrace (..),
+  )
+where
+
+import Control.Monad.IOSim (ExplorationOptions, withBranching, withScheduleBound)
+import Data.Maybe (fromMaybe)
+import Data.Monoid (Endo (..))
+import Data.Tagged (Tagged (..))
+import Test.Tasty (TestTree, askOption, localOption)
+import Test.Tasty.Options
+  ( IsOption (..),
+    mkFlagCLParser,
+    safeRead,
+    safeReadBool,
+  )
+import Test.Tasty.QuickCheck
+  ( QuickCheckTests (QuickCheckTests),
+  )
+
+setNumRacyTests :: TestTree -> TestTree
+setNumRacyTests tree =
+  -- These tests are potentially very long. We want a small default (here, 3),
+  -- but with the ability to set it to a larger or smaller number at weill.
+  --
+  -- 'QuickCheckTests' doesn't allow this, as its default is 100, which is much
+  -- too large
+  askOption $ \(NumRacyTests n) ->
+    let numTests = fromMaybe 3 n
+     in localOption (QuickCheckTests numTests) tree
+
+newtype NumRacyTests
+  = NumRacyTests (Maybe Int)
+  deriving (Eq, Ord, Show)
+
+withExplorationOptions :: ((ExplorationOptions -> ExplorationOptions) -> TestTree) -> TestTree
+withExplorationOptions f =
+  askOption $ \(ScheduleBound mBound) ->
+    askOption $ \(BranchingFactor mFactor) ->
+      f
+        ( appEndo $
+            mconcat
+              [ maybe mempty (Endo . withScheduleBound) mBound,
+                maybe mempty (Endo . withBranching) mFactor
+              ]
+        )
+
+instance IsOption NumRacyTests where
+  defaultValue = NumRacyTests Nothing
+  parseValue s = NumRacyTests . Just <$> safeRead s
+  optionName = Tagged "num-racy-tests"
+  optionHelp = Tagged "Number of racy tests to run"
+
+newtype ScheduleBound
+  = ScheduleBound (Maybe Int)
+  deriving (Eq, Ord, Show)
+
+instance IsOption ScheduleBound where
+  defaultValue = ScheduleBound Nothing
+  parseValue s = ScheduleBound . Just <$> safeRead s
+  optionName = Tagged "schedule-bound"
+  optionHelp = Tagged "Upper bound on the number of schedules with race reversals that will be explored."
+
+newtype BranchingFactor
+  = BranchingFactor (Maybe Int)
+  deriving (Eq, Ord, Show)
+
+instance IsOption BranchingFactor where
+  defaultValue = BranchingFactor Nothing
+  parseValue s = BranchingFactor . Just <$> safeRead s
+  optionName = Tagged "branching-factor"
+  optionHelp = Tagged "Number of alternative schedules explored per race reversal."
+
+withPrintTraceOption :: (PrintTrace -> TestTree) -> TestTree
+withPrintTraceOption = askOption
+
+newtype PrintTrace
+  = PrintTrace Bool
+  deriving (Eq, Ord, Show)
+
+instance IsOption PrintTrace where
+  defaultValue = PrintTrace False
+  optionName = Tagged "print-trace"
+  parseValue = fmap PrintTrace . safeReadBool
+  optionHelp = Tagged "Print the execution trace. This is generally only useful for a specific test replay."
+  optionCLParser = mkFlagCLParser mempty (PrintTrace True)
diff --git a/tests/Test/Distributed/Consensus/Raft/Properties.hs b/tests/Test/Distributed/Consensus/Raft/Properties.hs
new file mode 100644
--- /dev/null
+++ b/tests/Test/Distributed/Consensus/Raft/Properties.hs
@@ -0,0 +1,494 @@
+{-# LANGUAGE BangPatterns #-}
+{-# LANGUAGE ExplicitForAll #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE OverloadedStrings #-}
+
+module Test.Distributed.Consensus.Raft.Properties
+  ( FaultInjection (..),
+    allProperties,
+  )
+where
+
+import Control.Monad (unless, void, when)
+import Control.Monitor
+  ( allOf,
+    assert,
+    eventually,
+    predicate,
+    step,
+    whenever,
+    (<?>),
+  )
+import Data.Foldable (for_)
+import Data.Map.Strict (Map)
+import qualified Data.Map.Strict as Map
+import Data.Maybe (fromMaybe)
+import qualified Data.Set as Set
+import qualified Data.Text as Text
+import Distributed.Consensus.Raft (CommandResponse (..), EventContext (..), LogEntry (LogEntryMembershipChange), LogIndex, RaftTrace (..), SnapshotMetadata (SnapshotMetadata), Term)
+import Test.Distributed.Consensus.Raft.Scenario
+  ( Scenario,
+    clusterMembershipChangeCompleted,
+    clusterMembershipChangeInitiated,
+    commandReceived,
+    commandResponded,
+    joinClusterCommandReceived,
+    leaveClusterCommandReceived,
+    membershipSettled,
+  )
+
+-- | Whether we expect the cluster to always respond, or not.
+--
+-- In general, with faults, Raft clusters are not expected to be live.
+-- However, if the fault injector is turned off, we DO expect an answer!
+data FaultInjection
+  = NoFaultInjection
+  | FaultInjection
+
+-- It's still not clear to me why, but without the explicit forall here,
+-- RaftTrace events don't get picked up.
+allProperties ::
+  forall entry node result state.
+  ( Eq entry,
+    Ord node,
+    Show node,
+    Show entry
+  ) =>
+  FaultInjection -> Scenario entry node result state
+allProperties faultInjection =
+  let -- Properties in Figure 3 of the Raft paper
+      coreRaftProperties =
+        [ singleLeaderPerTermProperty,
+          leaderAppendOnlyProperty,
+          logMatchingProperty,
+          leaderCompletenessProperty,
+          stateMachineSafetyProperty
+        ]
+      otherProperties =
+        [ singleVoteCastPerTermProperty,
+          monotonicallyIncreasingTermProperty,
+          indexRelationshipProperty,
+          monotonicallyIncreasingLastAppliedIndexProperty,
+          monotonicallyIncreasingCommitIndexProperty,
+          singleConfigurationChangeInFlight
+        ]
+      noFaultProperties = case faultInjection of
+        NoFaultInjection ->
+          [ allAcceptedCommandReceiveResponseProperty,
+            allAcceptedClusterMembershipRequestsResultInNewClusterConfiguration,
+            allAdminRequestToJoinComplete,
+            allAdminRequestToLeaveComplete
+          ]
+        FaultInjection -> []
+   in void $
+        allOf (coreRaftProperties <> otherProperties <> noFaultProperties)
+
+-- | Ensure that in each term where a leader is elected, no other leader
+-- is elected
+singleLeaderPerTermProperty :: Scenario entry node result state
+singleLeaderPerTermProperty = go mempty <?> "Another leader elected for the same term"
+  where
+    go seenTerms =
+      step
+        ()
+        ( \case
+            LeaderElected (EventContext term _) -> do
+              assert
+                "Expecting at most one leader per term"
+                (Set.notMember term seenTerms)
+              go (Set.insert term seenTerms)
+            _ -> go seenTerms
+        )
+
+-- | Ensure that a node casts at most one vote per term
+--
+-- Note that under fault conditions, the same vote for the same term may be cast multiple
+-- times. I consider this acceptable; votes are idempotent
+singleVoteCastPerTermProperty :: (Ord node, Show node) => Scenario entry node result state
+singleVoteCastPerTermProperty = go mempty <?> "More than one vote cast per term"
+  where
+    go votes =
+      step
+        ()
+        ( \case
+            VotedFor (EventContext voterTerm voterNode) _ candidate -> do
+              assert
+                ("Expecting a node to cast at most one vote per term: " <> Text.show votes)
+                ( case Map.lookup (voterTerm, voterNode) votes of
+                    Nothing -> True
+                    Just candidate' -> candidate == candidate' -- allow multiple identical vote for idempotence
+                )
+              go (Map.insert (voterTerm, voterNode) candidate votes)
+            _ -> go votes
+        )
+
+-- | Ensure that each node witnesses terms that increase monotonically
+monotonicallyIncreasingTermProperty :: (Ord node) => Scenario entry node result state
+monotonicallyIncreasingTermProperty = go mempty <?> "Term not increased monotonically"
+  where
+    go latestKnownTerms =
+      step
+        ()
+        ( \e -> case roleTerm e of
+            Nothing -> go latestKnownTerms
+            Just (node, newTerm) -> do
+              case Map.lookup node latestKnownTerms of
+                Nothing -> pure ()
+                Just latestTerm ->
+                  assert
+                    "Expecting terms to increase monotonically"
+                    (latestTerm <= newTerm)
+              go (Map.insert node newTerm latestKnownTerms)
+        )
+
+    roleTerm (LeaderElected (EventContext t n)) = Just (n, t)
+    roleTerm (BecameCandidate (EventContext t n)) = Just (n, t)
+    roleTerm (BecameFollower (EventContext t n)) = Just (n, t)
+    roleTerm _ = Nothing
+
+-- | Ensure that each node's last applied index increases monotonically.
+monotonicallyIncreasingLastAppliedIndexProperty :: (Ord node) => Scenario entry node result state
+monotonicallyIncreasingLastAppliedIndexProperty = go mempty <?> "Last applied index not increasing monotonically"
+  where
+    go acc =
+      step
+        ()
+        ( \case
+            LastAppliedIndexIncreasedTo (EventContext _ node) lastApplied -> do
+              case Map.lookup node acc of
+                Nothing -> pure ()
+                Just prevLastApplied ->
+                  assert
+                    "Expecting last applied index to increase monotonically"
+                    (prevLastApplied <= lastApplied)
+
+              go (Map.insert node lastApplied acc)
+            Crashed node -> go (Map.delete node acc)
+            _ -> go acc
+        )
+
+-- | Ensure that each node's commit index increases monotonically.
+monotonicallyIncreasingCommitIndexProperty :: (Ord node) => Scenario entry node result state
+monotonicallyIncreasingCommitIndexProperty = go mempty <?> "Commit index not increasing monotonically"
+  where
+    go acc =
+      step
+        ()
+        ( \case
+            CommitIndexIncreasedTo (EventContext _ node) commitIndex -> do
+              case Map.lookup node acc of
+                Nothing -> pure ()
+                Just prevCommitIndex ->
+                  assert
+                    "Expecting commit index to increase monotonically"
+                    (prevCommitIndex <= commitIndex)
+
+              go (Map.insert node commitIndex acc)
+            _ -> go acc
+        )
+
+-- | Ensure that every command that was acknowledged by the leader
+-- receives a response with the same request ID.
+allAcceptedCommandReceiveResponseProperty :: Scenario entry node result state
+allAcceptedCommandReceiveResponseProperty = go
+  where
+    go = void $ whenever commandReceived $ \(_, reqId, _) ->
+      let thisCommandResponded =
+            commandResponded >>= \(_, MkCommandResponse _result' reqId') ->
+              predicate $ \_ -> unless (reqId == reqId') Nothing
+       in eventually thisCommandResponded <?> "Never received a response for " <> Text.show reqId
+
+singleConfigurationChangeInFlight :: (Ord node) => Scenario entry node result state
+singleConfigurationChangeInFlight = go mempty <?> "A leader appended a configuration change while another was not completed"
+  where
+    go leaders =
+      step
+        ()
+        ( \case
+            LeaderElected (EventContext _ node) -> go (Map.insert node False leaders)
+            BecameFollower (EventContext _ node) -> go (Map.delete node leaders)
+            BecameCandidate (EventContext _ node) -> go (Map.delete node leaders)
+            BecameNonMember (EventContext _ node) -> go (Map.delete node leaders)
+            Crashed node -> go (Map.delete node leaders)
+            MembershipChangeApplied (EventContext _ node) _ -> go (Map.adjust (const False) node leaders)
+            LogEntryAppended (EventContext _ node) _ _ (LogEntryMembershipChange _) ->
+              case Map.lookup node leaders of
+                Just True -> assert "Expecting at most one unapplied configuration change" False
+                Just False -> go (Map.insert node True leaders)
+                Nothing -> go leaders
+            _ -> go leaders
+        )
+
+-- | Ensure that every cluster membership change that's accepted by a leader
+-- is seen through by the same leader
+allAcceptedClusterMembershipRequestsResultInNewClusterConfiguration :: (Eq node) => Scenario entry node result state
+allAcceptedClusterMembershipRequestsResultInNewClusterConfiguration =
+  go <?> "An accepted cluster membership request did not result in new configuration"
+  where
+    go = void $ whenever clusterMembershipChangeInitiated $ \ctx ->
+      eventually
+        ( clusterMembershipChangeCompleted >>= \ctx' ->
+            predicate $ \_ -> unless (ctx == ctx') Nothing
+        )
+
+allAdminRequestToJoinComplete :: (Ord node, Show node) => Scenario entry node result state
+allAdminRequestToJoinComplete =
+  go <?> "A command to join a cluster did not result in new cluster membership"
+  where
+    -- The authority on whether a node is in the cluster is the
+    -- leader that applies the new configuration, not the joining node
+    go = void $ whenever joinClusterCommandReceived $ \(EventContext _ nodeJoining) ->
+      eventually (membershipSettled (Set.member nodeJoining) nodeJoining)
+        <?> "A command to "
+        <> Text.show nodeJoining
+        <> " to join a cluster did not result in new cluster membership"
+
+allAdminRequestToLeaveComplete :: (Show node, Ord node) => Scenario entry node result state
+allAdminRequestToLeaveComplete =
+  go
+  where
+    go = void $ whenever leaveClusterCommandReceived $ \(EventContext _ nodeLeaving) ->
+      -- This is quite subtle. Basically, the cluster can replicate, commit, and apply a cluster
+      -- configuration change without the node leaving the cluster ever knowing. Consider a cluster
+      -- of three nodes [A, B, C], where C is leaving; join configurations [A, B] and [A, B, C] have
+      -- quorum with just A and B acknowledging and applying the configuration state.
+      --
+      -- Therefore, the true mark of whether a node has left a cluster is not from the point-of-view
+      -- of that node, but from the point-of-view of the leader, that emits a
+      -- 'MembershipChangeApplied'
+      eventually (membershipSettled (Set.notMember nodeLeaving) nodeLeaving)
+        <?> "A command to "
+        <> Text.show nodeLeaving
+        <> " to leave a cluster did not result in new cluster membership"
+
+data NodeIndexes
+  = MkNodeIndexes
+      -- | Last applied index
+      !LogIndex
+      -- | Commit index
+      !LogIndex
+      -- | Last log index
+      !LogIndex
+
+-- | Ensures that the following relationship holds for each node individually:
+--
+--    appliex index  <=  commit index  <=  log length
+indexRelationshipProperty :: (Ord node) => Scenario entry node result state
+indexRelationshipProperty = go mempty <?> "index relationship did not hold"
+  where
+    checkState node acc =
+      case Map.lookup node acc of
+        Nothing -> assert "Incomplete state" False
+        Just (MkNodeIndexes lastApplied committed lastIndex) -> do
+          assert "last_applied_index <= commit_index violated" (lastApplied <= committed)
+          assert "commit_index <= last_index violated" (committed <= lastIndex)
+    go acc =
+      step
+        ()
+        ( \case
+            LastAppliedIndexIncreasedTo (EventContext _ node) lastApplied -> do
+              let newAcc =
+                    Map.alter
+                      ( \case
+                          Nothing -> Just (MkNodeIndexes lastApplied 0 0)
+                          Just (MkNodeIndexes _ y z) -> Just (MkNodeIndexes lastApplied y z)
+                      )
+                      node
+                      acc
+              checkState node newAcc
+              go newAcc
+            CommitIndexIncreasedTo (EventContext _ node) commitIndex -> do
+              let newAcc =
+                    Map.alter
+                      ( \case
+                          Nothing -> Just (MkNodeIndexes 0 commitIndex 0)
+                          Just (MkNodeIndexes x _ z) -> Just (MkNodeIndexes x commitIndex z)
+                      )
+                      node
+                      acc
+              checkState node newAcc
+              go newAcc
+            LastLogIndexChangedTo (EventContext _ node) lastLogIndex -> do
+              let newAcc =
+                    Map.alter
+                      ( \case
+                          Nothing -> Just (MkNodeIndexes 0 0 lastLogIndex)
+                          Just (MkNodeIndexes x y _) -> Just (MkNodeIndexes x y lastLogIndex)
+                      )
+                      node
+                      acc
+              checkState node newAcc
+              go newAcc
+            Crashed node -> go (Map.delete node acc)
+            _ -> go acc
+        )
+
+-- | If two logs contain an entry with the same index and term, then the
+-- logs are identical in all entries up through the given index
+logMatchingProperty :: (Ord node, Eq entry) => Scenario entry node result state
+logMatchingProperty = go mempty mempty <?> "Conflicting entries appended at the same index and term"
+  where
+    go logs seen =
+      step
+        ()
+        ( \case
+            LogEntryAppended (EventContext _ node) term logIndex entry -> do
+              let prefix = Map.takeWhileAntitone (< logIndex) (Map.findWithDefault mempty node logs)
+
+              assert
+                "Expecting a contiguous log"
+                (logIndex == 1 || Map.member (pred logIndex) prefix)
+
+              case Map.lookup (term, logIndex) seen of
+                Nothing -> pure ()
+                Just (entry', prefix') -> do
+                  assert "Different entries for the same term and log index" (entry == entry')
+                  assert
+                    ( "Log prefix before term "
+                        <> Text.show term
+                        <> " and log index "
+                        <> Text.show logIndex
+                        <> " differs"
+                    )
+                    (prefix == prefix')
+
+              go
+                (Map.insert node (Map.insert logIndex term prefix) logs)
+                (Map.insertWith (\_ old -> old) (term, logIndex) (entry, prefix) seen)
+            -- A snapshot is special because it serves as the log prefix
+            SnapshotApplied (EventContext _ node) (SnapshotMetadata lastLogIndex lastTerm) -> do
+              let thisNode = Map.findWithDefault mempty node logs
+              case Map.lookup (lastTerm, lastLogIndex) seen of
+                Nothing -> do
+                  assert
+                    ( "Expecting a snapshot at term "
+                        <> Text.show lastTerm
+                        <> " and log index "
+                        <> Text.show lastLogIndex
+                    )
+                    False
+                  go logs seen
+                Just (_, prefix) ->
+                  let following
+                        | Map.lookup lastLogIndex thisNode == Just lastTerm = snd (Map.split lastLogIndex thisNode)
+                        | otherwise = mempty
+                   in go
+                        (Map.insert node (Map.insert lastLogIndex lastTerm prefix <> following) logs)
+                        seen
+            _ -> go logs seen
+        )
+
+-- | If a node has applied a log entry at a given index to its state machine, no other node
+-- will ever apply a different log entry for the same index.
+stateMachineSafetyProperty :: (Show entry, Eq entry) => Scenario entry node result state
+stateMachineSafetyProperty = go mempty <?> "Conflicting entries applied at the same index"
+  where
+    go acc =
+      step
+        ()
+        ( \case
+            LogEntryApplied _ term logIndex entry -> do
+              case Map.lookup logIndex acc of
+                -- First time this entry has been seen
+                Nothing -> go (Map.insert logIndex (term, entry) acc)
+                Just (term', entry') ->
+                  assert
+                    ( "Expecting the same entry to be applied at index "
+                        <> Text.show logIndex
+                        <> " but saw "
+                        <> Text.show (term', entry')
+                        <> " and "
+                        <> Text.show (term, entry)
+                    )
+                    (term' == term && entry' == entry)
+            _ -> go acc
+        )
+
+leaderAppendOnlyProperty :: (Ord node) => Scenario entry node result state
+leaderAppendOnlyProperty = go mempty mempty <?> "A leader overwrite or deleted an entry from its own log"
+  where
+    go !lastIx !leaders =
+      step
+        ()
+        ( \case
+            LeaderElected (EventContext _ n) -> go lastIx (Set.insert n leaders)
+            BecameFollower (EventContext _ n) -> go lastIx (Set.delete n leaders)
+            BecameCandidate (EventContext _ n) -> go lastIx (Set.delete n leaders)
+            BecameNonMember (EventContext _ n) -> go lastIx (Set.delete n leaders)
+            GracefulShutdown (EventContext _ n) -> go lastIx (Set.delete n leaders)
+            Crashed n -> go (Map.delete n lastIx) (Set.delete n leaders)
+            LogEntryAppended (EventContext _ n) _ ix _ -> do
+              when (n `Set.member` leaders) $
+                case Map.lookup n lastIx of
+                  Nothing -> pure ()
+                  Just prev ->
+                    assert
+                      ("Leader appended at index " <> Text.show ix <> " but its last index was " <> Text.show prev)
+                      (ix == succ prev)
+              go (Map.insert n ix lastIx) leaders
+            LastLogIndexChangedTo (EventContext _ n) ix -> do
+              when (n `Set.member` leaders) $
+                case Map.lookup n lastIx of
+                  Nothing -> pure ()
+                  Just prev ->
+                    assert
+                      "Leader's last log index regressed"
+                      (ix >= prev)
+              go (Map.insert n ix lastIx) leaders
+            _ -> go lastIx leaders
+        )
+
+data NodeLog = MkNodeLog !LogIndex !(Map LogIndex Term)
+
+data Committed
+  = NothingCommitted
+  | Committed !LogIndex !Term
+
+leaderCompletenessProperty :: (Ord node) => Scenario entry node result state
+leaderCompletenessProperty = go mempty NothingCommitted <?> "A leader is missing an entry that was previously committed"
+  where
+    go !logs !committed =
+      step
+        ()
+        ( \case
+            LogEntryAppended (EventContext _ n) t ix _ ->
+              go (Map.alter (Just . appendEntry ix t . fromMaybe emptyNodeLog) n logs) committed
+            LastLogIndexChangedTo (EventContext _ n) ix ->
+              go (Map.adjust (\(MkNodeLog _ runs) -> MkNodeLog ix runs) n logs) committed
+            SnapshotApplied (EventContext _ n) (SnapshotMetadata ix t) -> do
+              let update l@(MkNodeLog lastIx runs)
+                    | termAt ix l == Just t = l
+                    | otherwise = MkNodeLog (max ix lastIx) (Map.insert ix t (Map.dropWhileAntitone (<= ix) runs))
+               in go (Map.alter (Just . update . fromMaybe emptyNodeLog) n logs) committed
+            CommitIndexIncreasedTo (EventContext _ n) c
+              | Just t <- Map.lookup n logs >>= termAt c -> case committed of
+                  Committed c' t' | c == c' -> do
+                    assert ("Index " <> Text.show c <> "committed in two separate terms: " <> Text.show t <> " and " <> Text.show t') (t == t')
+                    go logs committed
+                  Committed c' _ | c < c' -> go logs committed
+                  _ -> go logs (Committed c t)
+            LeaderElected (EventContext term n) -> do
+              case committed of
+                NothingCommitted -> pure ()
+                Committed c t -> do
+                  let nodeLog = Map.findWithDefault emptyNodeLog n logs
+                      MkNodeLog lastIx _ = nodeLog
+
+                  assert ("Incongruent last index for leader of term " <> Text.show term) (lastIx >= c)
+
+                  for_ (termAt c nodeLog) $ \t' ->
+                    assert ("Incongruent terms for leader at term " <> Text.show term) (t' == t)
+
+              go logs committed
+            _ -> go logs committed
+        )
+      where
+        emptyNodeLog = MkNodeLog 0 mempty
+
+        appendEntry !ix !t (MkNodeLog _ runs) =
+          let kept = Map.takeWhileAntitone (< ix) runs
+           in MkNodeLog ix $ case Map.lookupMax kept of
+                Just (_, t') | t' == t -> kept
+                _ -> Map.insert ix t kept
+
+        termAt ix (MkNodeLog _ runs) = snd <$> Map.lookupLE ix runs
diff --git a/tests/Test/Distributed/Consensus/Raft/Scenario.hs b/tests/Test/Distributed/Consensus/Raft/Scenario.hs
new file mode 100644
--- /dev/null
+++ b/tests/Test/Distributed/Consensus/Raft/Scenario.hs
@@ -0,0 +1,174 @@
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+module Test.Distributed.Consensus.Raft.Scenario
+  ( Scenario,
+    checkScenario,
+    module Control.Monitor,
+
+    -- * Helpers
+    stateRestored,
+    leaderElected,
+    votedFor,
+    commandReceived,
+    commandResponded,
+    joinClusterCommandReceived,
+    leaveClusterCommandReceived,
+    joinedCluster,
+    clusterMembershipChangeInitiated,
+    clusterMembershipChangeCompleted,
+    clusterMembershipChangeApplied,
+    commitIndexIncreased,
+    logEntryApplied,
+    rpcReceived,
+    rpcResultReceived,
+    crashed,
+    membershipSettled,
+  )
+where
+
+import Control.Monad.IOSim (SimEvent, SimEventType (EventLog), SimResult, Trace, selectTraceEvents)
+import Control.Monitor (Monitor, Predicate, ppReasonsWithTrace, predicate, runMonitor)
+import Data.Dynamic (Typeable, fromDynamic)
+import Data.Set (Set)
+import qualified Data.Text as Text
+import Distributed.Consensus.Raft
+  ( ClientRequestId,
+    ClusterConfiguration (..),
+    CommandResponse,
+    Event (..),
+    EventContext,
+    Log,
+    LogEntry,
+    LogIndex,
+    RPC (..),
+    RPCResult,
+    RaftTrace (..),
+    Request (..),
+    Term,
+  )
+import Distributed.Consensus.Raft.Admin (AdminCommand (..))
+import Distributed.Consensus.Raft.Client (ClientResult)
+import Test.Tasty.QuickCheck (Property, counterexample)
+
+type Scenario entry node result state =
+  Monitor (RaftTrace entry node result state) ()
+
+-- | Check a scenario over a 'Trace'.
+checkScenario ::
+  ( Show entry,
+    Show result,
+    Show node,
+    Show state,
+    Typeable entry,
+    Typeable result,
+    Typeable node,
+    Typeable state
+  ) =>
+  Scenario entry node result state ->
+  Trace (SimResult a) SimEvent ->
+  Property
+checkScenario scenario trace' =
+  let evs = raftTrace trace'
+   in case runMonitor scenario evs of
+        (Left errs) -> counterexample (Text.unpack $ ppReasonsWithTrace Text.show 3 (zip [0 ..] evs) errs) False
+        -- There have been instances in the past of tests trivially passing
+        -- because no events were emitted!
+        (Right _) -> counterexample "No events emitted" (not (null evs))
+
+raftTrace ::
+  (Typeable entry, Typeable result, Typeable node, Typeable state) =>
+  Trace (SimResult a) SimEvent -> [RaftTrace entry node result state]
+raftTrace =
+  selectTraceEvents
+    ( \_ ev -> case ev of
+        EventLog dyn -> fromDynamic dyn
+        _ -> Nothing -- internal io-sim event
+    )
+
+stateRestored :: Predicate (RaftTrace entry node result state) (EventContext node, Maybe node, Log (LogEntry entry node) node)
+stateRestored = predicate $ \case
+  StateRestored ctx mVote logEntries -> Just (ctx, mVote, logEntries)
+  _ -> Nothing
+
+leaderElected :: Predicate (RaftTrace entry node result state) (EventContext node)
+leaderElected = predicate $ \case
+  (LeaderElected ctx) -> Just ctx
+  _ -> Nothing
+
+votedFor :: Predicate (RaftTrace entry node result state) (EventContext node, Term, node)
+votedFor = predicate $ \case
+  VotedFor ctx candidateTerm candidateNode -> Just (ctx, candidateTerm, candidateNode)
+  _ -> Nothing
+
+commandReceived :: Predicate (RaftTrace entry node result state) (EventContext node, ClientRequestId, entry)
+commandReceived = predicate $ \case
+  (CommandReceived ctx reqId entry) -> Just (ctx, reqId, entry)
+  _ -> Nothing
+
+commandResponded :: Predicate (RaftTrace entry node result state) (EventContext node, CommandResponse node (ClientResult result))
+commandResponded = predicate $ \case
+  (CommandResultResponded ctx response) -> Just (ctx, response)
+  _ -> Nothing
+
+joinClusterCommandReceived :: Predicate (RaftTrace entry node result state) (EventContext node)
+joinClusterCommandReceived = predicate $ \case
+  (AdminRequestReceived ctx (MkRequest _ _ (JoinCluster _))) -> Just ctx
+  _ -> Nothing
+
+leaveClusterCommandReceived :: Predicate (RaftTrace entry node result state) (EventContext node)
+leaveClusterCommandReceived = predicate $ \case
+  (AdminRequestReceived ctx (MkRequest _ _ LeaveCluster)) -> Just ctx
+  _ -> Nothing
+
+joinedCluster :: Predicate (RaftTrace entry node result state) (EventContext node)
+joinedCluster = predicate $ \case
+  JoinedCluster ctx -> Just ctx
+  _ -> Nothing
+
+clusterMembershipChangeInitiated :: Predicate (RaftTrace entry node result state) (EventContext node)
+clusterMembershipChangeInitiated = predicate $ \case
+  MembershipChangeInitiated ctx -> pure ctx
+  _ -> Nothing
+
+clusterMembershipChangeCompleted :: Predicate (RaftTrace entry node result state) (EventContext node)
+clusterMembershipChangeCompleted = predicate $ \case
+  MembershipChangeCompleted ctx -> pure ctx
+  _ -> Nothing
+
+clusterMembershipChangeApplied :: Predicate (RaftTrace entry node result state) (EventContext node, ClusterConfiguration node)
+clusterMembershipChangeApplied = predicate $ \case
+  MembershipChangeApplied ctx clusterConf -> pure (ctx, clusterConf)
+  _ -> Nothing
+
+rpcReceived :: Predicate (RaftTrace entry node result state) (EventContext node, RPC entry node state)
+rpcReceived = predicate $ \case
+  (EventReceived ctx (EventRPC rpc)) -> Just (ctx, rpc)
+  _ -> Nothing
+
+rpcResultReceived :: Predicate (RaftTrace entry node result state) (EventContext node, RPCResult node result)
+rpcResultReceived = predicate $ \case
+  (EventReceived ctx (EventRPCResult resp)) -> Just (ctx, resp)
+  _ -> Nothing
+
+commitIndexIncreased :: Predicate (RaftTrace entry node result state) (EventContext node, LogIndex)
+commitIndexIncreased = predicate $ \case
+  (CommitIndexIncreasedTo ctx logIndex) -> Just (ctx, logIndex)
+  _ -> Nothing
+
+logEntryApplied :: Predicate (RaftTrace entry node result state) (EventContext node, (Term, LogIndex, entry))
+logEntryApplied = predicate $ \case
+  (LogEntryApplied ctx entryTerm entryLog entry) -> Just (ctx, (entryTerm, entryLog, entry))
+  _ -> Nothing
+
+crashed :: Predicate (RaftTrace entry node result state) node
+crashed = predicate $ \case
+  Crashed node -> Just node
+  _ -> Nothing
+
+membershipSettled :: (Eq node) => (Set node -> Bool) -> node -> Predicate (RaftTrace entry node result state) ()
+membershipSettled wanted node = predicate $ \case
+  MembershipChangeApplied _ (Joint _ _) -> Just ()
+  MembershipChangeApplied _ (Simple cluster) | wanted cluster -> Just ()
+  MembershipChangeAlreadySettled _ node' | node' == node -> Just ()
+  _ -> Nothing
diff --git a/tests/Test/StateMachine.hs b/tests/Test/StateMachine.hs
new file mode 100644
--- /dev/null
+++ b/tests/Test/StateMachine.hs
@@ -0,0 +1,52 @@
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+
+module Test.StateMachine
+  ( Node (..),
+    State,
+    Key (..),
+    Command (..),
+    Result (..),
+    step,
+  )
+where
+
+import Data.Map.Strict (Map)
+import qualified Data.Map.Strict as Map
+import Distributed.Consensus.Raft (StateMachineStep (..))
+import Test.Tasty.QuickCheck (Arbitrary (arbitrary), chooseInt, elements, oneof)
+
+-- Simple key-value store
+
+newtype Node = Node Int
+  deriving (Eq, Show, Bounded, Enum, Num, Ord, Real, Integral)
+
+type State = Map Key Int
+
+data Command
+  = Insert Key Int
+  | Delete Key
+  | Get Key
+  deriving (Eq, Ord, Show)
+
+data Key = A | B | C
+  deriving (Eq, Ord, Show, Enum, Bounded)
+
+instance Arbitrary Command where
+  arbitrary =
+    let possibleKeys = enumFromTo minBound maxBound
+     in oneof
+          [ Insert <$> elements possibleKeys <*> chooseInt (0, 10),
+            Delete <$> elements possibleKeys,
+            Get <$> elements possibleKeys
+          ]
+
+data Result
+  = Value Int
+  | Ok
+  | Err
+  deriving (Eq, Ord, Show)
+
+step :: Command -> StateMachineStep Result State
+step (Insert k v) = Transition $ \state -> (Map.insert k v state, Ok)
+step (Delete k) = Transition $ \state -> (Map.delete k state, Ok)
+step (Get k) = Read $ \state -> maybe Err Value (Map.lookup k state)
