package ddata
- Alphabetic
- Public
- Protected
Type Members
- abstract class AbstractDeltaReplicatedData[A <: AbstractDeltaReplicatedData[A, B], B <: ReplicatedDelta] extends AbstractReplicatedData[A] with DeltaReplicatedData
Java API: Interface for implementing a DeltaReplicatedData in Java.
Java API: Interface for implementing a DeltaReplicatedData in Java.
The type parameter
A
is a self-recursive type to be defined by the concrete implementation. E.g.class TwoPhaseSet extends AbstractDeltaReplicatedData<TwoPhaseSet, TwoPhaseSet>
- abstract class AbstractReplicatedData[A <: AbstractReplicatedData[A]] extends ReplicatedData
Java API: Interface for implementing a ReplicatedData in Java.
Java API: Interface for implementing a ReplicatedData in Java.
The type parameter
A
is a self-recursive type to be defined by the concrete implementation. E.g.class TwoPhaseSet extends AbstractReplicatedData<TwoPhaseSet>
- trait DeltaReplicatedData extends ReplicatedData
ReplicatedData with additional support for delta-CRDT replication.
ReplicatedData with additional support for delta-CRDT replication. delta-CRDT is a way to reduce the need for sending the full state for updates. For example adding element 'c' and 'd' to set {'a', 'b'} would result in sending the delta {'c', 'd'} and merge that with the state on the receiving side, resulting in set {'a', 'b', 'c', 'd'}.
Learn more about this in the paper Delta State Replicated Data Types.
- class DistributedData extends Extension
Pekko extension for convenient configuration and use of the Replicator.
Pekko extension for convenient configuration and use of the Replicator. Configuration settings are defined in the
pekko.cluster.ddata
section, seereference.conf
. - final case class Flag(enabled: Boolean) extends ReplicatedData with ReplicatedDataSerialization with Product with Serializable
Implements a boolean flag CRDT that is initialized to
false
and can be switched totrue
.Implements a boolean flag CRDT that is initialized to
false
and can be switched totrue
.true
wins overfalse
in merge.This class is immutable, i.e. "modifying" methods return a new instance.
- Annotations
- @SerialVersionUID()
- final case class FlagKey(_id: String) extends Key[Flag] with ReplicatedDataSerialization with Product with Serializable
- Annotations
- @SerialVersionUID()
- final class GCounter extends DeltaReplicatedData with ReplicatedDelta with ReplicatedDataSerialization with RemovedNodePruning with FastMerge
Implements a 'Growing Counter' CRDT, also called a 'G-Counter'.
Implements a 'Growing Counter' CRDT, also called a 'G-Counter'.
It is described in the paper A comprehensive study of Convergent and Commutative Replicated Data Types.
A G-Counter is a increment-only counter (inspired by vector clocks) in which only increment and merge are possible. Incrementing the counter adds 1 to the count for the current node. Divergent histories are resolved by taking the maximum count for each node (like a vector clock merge). The value of the counter is the sum of all node counts.
This class is immutable, i.e. "modifying" methods return a new instance.
- Annotations
- @SerialVersionUID()
- final case class GCounterKey(_id: String) extends Key[GCounter] with ReplicatedDataSerialization with Product with Serializable
- Annotations
- @SerialVersionUID()
- final case class GSet[A] extends DeltaReplicatedData with ReplicatedDelta with ReplicatedDataSerialization with FastMerge with Product with Serializable
Implements a 'Add Set' CRDT, also called a 'G-Set'.
Implements a 'Add Set' CRDT, also called a 'G-Set'. You can't remove elements of a G-Set.
It is described in the paper A comprehensive study of Convergent and Commutative Replicated Data Types.
A G-Set doesn't accumulate any garbage apart from the elements themselves.
This class is immutable, i.e. "modifying" methods return a new instance.
- Annotations
- @SerialVersionUID()
- final case class GSetKey[A](_id: String) extends Key[GSet[A]] with ReplicatedDataSerialization with Product with Serializable
- Annotations
- @SerialVersionUID()
- abstract class Key[+T <: ReplicatedData] extends Serializable
Key for the key-value data in Replicator.
Key for the key-value data in Replicator. The type of the data value is defined in the key. Keys are compared equal if the
id
strings are equal, i.e. use unique identifiers.Specific classes are provided for the built in data types, e.g. ORSetKey, and you can create your own keys.
- final class LWWMap[A, B] extends DeltaReplicatedData with ReplicatedDataSerialization with RemovedNodePruning
Specialized ORMap with LWWRegister values.
Specialized ORMap with LWWRegister values.
LWWRegister
relies on synchronized clocks and should only be used when the choice of value is not important for concurrent updates occurring within the clock skew.Instead of using timestamps based on
System.currentTimeMillis()
time it is possible to use a timestamp value based on something else, for example an increasing version number from a database record that is used for optimistic concurrency control.The
defaultClock
is using max value ofSystem.currentTimeMillis()
andcurrentTimestamp + 1
. This means that the timestamp is increased for changes on the same node that occurs within the same millisecond. It also means that it is safe to use theLWWMap
without synchronized clocks when there is only one active writer, e.g. a Cluster Singleton. Such a single writer should then first read current value withReadMajority
(or more) before changing and writing the value withWriteMajority
(or more).For first-write-wins semantics you can use the LWWRegister#reverseClock instead of the LWWRegister#defaultClock
This class is immutable, i.e. "modifying" methods return a new instance.
- Annotations
- @SerialVersionUID()
- final case class LWWMapKey[A, B](_id: String) extends Key[LWWMap[A, B]] with ReplicatedDataSerialization with Product with Serializable
- Annotations
- @SerialVersionUID()
- final class LWWRegister[A] extends ReplicatedData with ReplicatedDataSerialization
Implements a 'Last Writer Wins Register' CRDT, also called a 'LWW-Register'.
Implements a 'Last Writer Wins Register' CRDT, also called a 'LWW-Register'.
It is described in the paper A comprehensive study of Convergent and Commutative Replicated Data Types.
Merge takes the register with highest timestamp. Note that this relies on synchronized clocks.
LWWRegister
should only be used when the choice of value is not important for concurrent updates occurring within the clock skew.Merge takes the register updated by the node with lowest address (
UniqueAddress
is ordered) if the timestamps are exactly the same.Instead of using timestamps based on
System.currentTimeMillis()
time it is possible to use a timestamp value based on something else, for example an increasing version number from a database record that is used for optimistic concurrency control.The
defaultClock
is using max value ofSystem.currentTimeMillis()
andcurrentTimestamp + 1
. This means that the timestamp is increased for changes on the same node that occurs within the same millisecond. It also means that it is safe to use theLWWRegister
without synchronized clocks when there is only one active writer, e.g. a Cluster Singleton. Such a single writer should then first read current value withReadMajority
(or more) before changing and writing the value withWriteMajority
(or more).For first-write-wins semantics you can use the LWWRegister#reverseClock instead of the LWWRegister#defaultClock
This class is immutable, i.e. "modifying" methods return a new instance.
- Annotations
- @SerialVersionUID()
- final case class LWWRegisterKey[A](_id: String) extends Key[LWWRegister[A]] with ReplicatedDataSerialization with Product with Serializable
- Annotations
- @SerialVersionUID()
- final class LmdbDurableStore extends Actor with ActorLogging
- final case class ManyVersionVector(versions: TreeMap[UniqueAddress, Long]) extends VersionVector with Product with Serializable
- final class ORMap[A, B <: ReplicatedData] extends DeltaReplicatedData with ReplicatedDataSerialization with RemovedNodePruning
Implements a 'Observed Remove Map' CRDT, also called a 'OR-Map'.
Implements a 'Observed Remove Map' CRDT, also called a 'OR-Map'.
It has similar semantics as an ORSet, but in case of concurrent updates the values are merged, and must therefore be ReplicatedData types themselves.
This class is immutable, i.e. "modifying" methods return a new instance.
- Annotations
- @SerialVersionUID()
- final case class ORMapKey[A, B <: ReplicatedData](_id: String) extends Key[ORMap[A, B]] with ReplicatedDataSerialization with Product with Serializable
- Annotations
- @SerialVersionUID()
- final class ORMultiMap[A, B] extends DeltaReplicatedData with ReplicatedDataSerialization with RemovedNodePruning
An immutable multi-map implementation.
An immutable multi-map implementation. This class wraps an ORMap with an ORSet for the map's value.
This class is immutable, i.e. "modifying" methods return a new instance.
Note that on concurrent adds and removals for the same key (on the same set), removals can be lost.
- Annotations
- @SerialVersionUID()
- final case class ORMultiMapKey[A, B](_id: String) extends Key[ORMultiMap[A, B]] with ReplicatedDataSerialization with Product with Serializable
- Annotations
- @SerialVersionUID()
- final class ORSet[A] extends DeltaReplicatedData with ReplicatedDataSerialization with RemovedNodePruning with FastMerge
Implements a 'Observed Remove Set' CRDT, also called a 'OR-Set'.
Implements a 'Observed Remove Set' CRDT, also called a 'OR-Set'. Elements can be added and removed any number of times. Concurrent add wins over remove.
It is not implemented as in the paper A comprehensive study of Convergent and Commutative Replicated Data Types. This is more space efficient and doesn't accumulate garbage for removed elements. It is described in the paper An optimized conflict-free replicated set The implementation is inspired by the Riak DT riak_dt_orswot.
The ORSet has a version vector that is incremented when an element is added to the set. The
node -> count
pair for that increment is stored against the element as its "birth dot". Every time the element is re-added to the set, its "birth dot" is updated to that of thenode -> count
version vector entry resulting from the add. When an element is removed, we simply drop it, no tombstones.When an element exists in replica A and not replica B, is it because A added it and B has not yet seen that, or that B removed it and A has not yet seen that? In this implementation we compare the
dot
of the present element to the version vector in the Set it is absent from. If the element dot is not "seen" by the Set version vector, that means the other set has yet to see this add, and the item is in the merged Set. If the Set version vector dominates the dot, that means the other Set has removed this element already, and the item is not in the merged Set.This class is immutable, i.e. "modifying" methods return a new instance.
- Annotations
- @SerialVersionUID()
- final case class ORSetKey[A](_id: String) extends Key[ORSet[A]] with ReplicatedDataSerialization with Product with Serializable
- Annotations
- @SerialVersionUID()
- final case class OneVersionVector extends VersionVector with Product with Serializable
- final class PNCounter extends DeltaReplicatedData with ReplicatedDelta with ReplicatedDataSerialization with RemovedNodePruning
Implements a 'Increment/Decrement Counter' CRDT, also called a 'PN-Counter'.
Implements a 'Increment/Decrement Counter' CRDT, also called a 'PN-Counter'.
It is described in the paper A comprehensive study of Convergent and Commutative Replicated Data Types.
PN-Counters allow the counter to be incremented by tracking the increments (P) separate from the decrements (N). Both P and N are represented as two internal GCounters. Merge is handled by merging the internal P and N counters. The value of the counter is the value of the P counter minus the value of the N counter.
This class is immutable, i.e. "modifying" methods return a new instance.
- Annotations
- @SerialVersionUID()
- final case class PNCounterKey(_id: String) extends Key[PNCounter] with ReplicatedDataSerialization with Product with Serializable
- Annotations
- @SerialVersionUID()
- final class PNCounterMap[A] extends DeltaReplicatedData with ReplicatedDataSerialization with RemovedNodePruning
Map of named counters.
- final case class PNCounterMapKey[A](_id: String) extends Key[PNCounterMap[A]] with ReplicatedDataSerialization with Product with Serializable
- Annotations
- @SerialVersionUID()
- trait RemovedNodePruning extends ReplicatedData
ReplicatedData that has support for pruning of data belonging to a specific node may implement this interface.
ReplicatedData that has support for pruning of data belonging to a specific node may implement this interface. When a node is removed from the cluster these methods will be used by the Replicator to collapse data from the removed node into some other node in the cluster.
See process description in the 'CRDT Garbage' section of the Replicator documentation.
- trait ReplicatedData extends AnyRef
Interface for implementing a state based convergent replicated data type (CvRDT).
Interface for implementing a state based convergent replicated data type (CvRDT).
ReplicatedData types must be serializable with an Akka Serializer. It is highly recommended to implement a serializer with Protobuf or similar. The built in data types are marked with ReplicatedDataSerialization and serialized with pekko.cluster.ddata.protobuf.ReplicatedDataSerializer.
Serialization of the data types are used in remote messages and also for creating message digests (SHA-1) to detect changes. Therefore it is important that the serialization produce the same bytes for the same content. For example sets and maps should be sorted deterministically in the serialization.
ReplicatedData types should be immutable, i.e. "modifying" methods should return a new instance.
Implement the additional methods of DeltaReplicatedData if it has support for delta-CRDT replication.
- trait ReplicatedDataSerialization extends Serializable
Marker trait for
ReplicatedData
serialized by pekko.cluster.ddata.protobuf.ReplicatedDataSerializer. - trait ReplicatedDelta extends ReplicatedData
The delta must implement this type.
- trait ReplicatedDeltaSize extends AnyRef
Some complex deltas grow in size for each update and above a configured threshold such deltas are discarded and sent as full state instead.
Some complex deltas grow in size for each update and above a configured threshold such deltas are discarded and sent as full state instead. This interface should be implemented by such deltas to define its size. This is number of elements or similar size hint, not size in bytes. The threshold is defined in
pekko.cluster.distributed-data.delta-crdt.max-delta-size
or corresponding ReplicatorSettings. - final class Replicator extends Actor with ActorLogging
A replicated in-memory data store supporting low latency and high availability requirements.
A replicated in-memory data store supporting low latency and high availability requirements.
The
Replicator
actor takes care of direct replication and gossip based dissemination of Conflict Free Replicated Data Types (CRDTs) to replicas in the the cluster. The data types must be convergent CRDTs and implement ReplicatedData, i.e. they provide a monotonic merge function and the state changes always converge.You can use your own custom ReplicatedData or DeltaReplicatedData types, and several types are provided by this package, such as:
- Counters: GCounter, PNCounter
- Registers: LWWRegister, Flag
- Sets: GSet, ORSet
- Maps: ORMap, ORMultiMap, LWWMap, PNCounterMap
For good introduction to the CRDT subject watch the Eventually Consistent Data Structures talk by Sean Cribbs and and the talk by Mark Shapiro and read the excellent paper A comprehensive study of Convergent and Commutative Replicated Data Types by Mark Shapiro et. al.
The
Replicator
actor must be started on each node in the cluster, or group of nodes tagged with a specific role. It communicates with otherReplicator
instances with the same path (without address) that are running on other nodes . For convenience it can be used with the DistributedData extension but it can also be started as an ordinary actor using theReplicator.props
. If it is started as an ordinary actor it is important that it is given the same name, started on same path, on all nodes.Delta State Replicated Data Types are supported. delta-CRDT is a way to reduce the need for sending the full state for updates. For example adding element 'c' and 'd' to set {'a', 'b'} would result in sending the delta {'c', 'd'} and merge that with the state on the receiving side, resulting in set {'a', 'b', 'c', 'd'}.
The protocol for replicating the deltas supports causal consistency if the data type is marked with RequiresCausalDeliveryOfDeltas. Otherwise it is only eventually consistent. Without causal consistency it means that if elements 'c' and 'd' are added in two separate
Update
operations these deltas may occasionally be propagated to nodes in different order than the causal order of the updates. For this example it can result in that set {'a', 'b', 'd'} can be seen before element 'c' is seen. Eventually it will be {'a', 'b', 'c', 'd'}.Update
To modify and replicate a ReplicatedData value you send a Replicator.Update message to the local
Replicator
. The current data value for thekey
of theUpdate
is passed as parameter to themodify
function of theUpdate
. The function is supposed to return the new value of the data, which will then be replicated according to the given consistency level.The
modify
function is called by theReplicator
actor and must therefore be a pure function that only uses the data parameter and stable fields from enclosing scope. It must for example not accesssender()
reference of an enclosing actor.Update
is intended to only be sent from an actor running in same localActorSystem
as theReplicator
, because themodify
function is typically not serializable.You supply a write consistency level which has the following meaning:
WriteLocal
the value will immediately only be written to the local replica, and later disseminated with gossipWriteTo(n)
the value will immediately be written to at leastn
replicas, including the local replicaWriteMajority
the value will immediately be written to a majority of replicas, i.e. at leastN/2 + 1
replicas, where N is the number of nodes in the cluster (or cluster role group)WriteAll
the value will immediately be written to all nodes in the cluster (or all nodes in the cluster role group)
As reply of the
Update
a Replicator.UpdateSuccess is sent to the sender of theUpdate
if the value was successfully replicated according to the supplied consistency level within the supplied timeout. Otherwise a Replicator.UpdateFailure subclass is sent back. Note that a Replicator.UpdateTimeout reply does not mean that the update completely failed or was rolled back. It may still have been replicated to some nodes, and will eventually be replicated to all nodes with the gossip protocol.You will always see your own writes. For example if you send two
Update
messages changing the value of the samekey
, themodify
function of the second message will see the change that was performed by the firstUpdate
message.In the
Update
message you can pass an optional request context, which theReplicator
does not care about, but is included in the reply messages. This is a convenient way to pass contextual information (e.g. original sender) without having to useask
or local correlation data structures.Get
To retrieve the current value of a data you send Replicator.Get message to the
Replicator
. You supply a consistency level which has the following meaning:ReadLocal
the value will only be read from the local replicaReadFrom(n)
the value will be read and merged fromn
replicas, including the local replicaReadMajority
the value will be read and merged from a majority of replicas, i.e. at leastN/2 + 1
replicas, where N is the number of nodes in the cluster (or cluster role group)ReadAll
the value will be read and merged from all nodes in the cluster (or all nodes in the cluster role group)
As reply of the
Get
a Replicator.GetSuccess is sent to the sender of theGet
if the value was successfully retrieved according to the supplied consistency level within the supplied timeout. Otherwise a Replicator.GetFailure is sent. If the key does not exist the reply will be Replicator.NotFound.You will always read your own writes. For example if you send a
Update
message followed by aGet
of the samekey
theGet
will retrieve the change that was performed by the precedingUpdate
message. However, the order of the reply messages are not defined, i.e. in the previous example you may receive theGetSuccess
before theUpdateSuccess
.In the
Get
message you can pass an optional request context in the same way as for theUpdate
message, described above. For example the original sender can be passed and replied to after receiving and transformingGetSuccess
.Subscribe
You may also register interest in change notifications by sending Replicator.Subscribe message to the
Replicator
. It will send Replicator.Changed messages to the registered subscriber when the data for the subscribed key is updated. Subscribers will be notified periodically with the configurednotify-subscribers-interval
, and it is also possible to send an explicitReplicator.FlushChanges
message to theReplicator
to notify the subscribers immediately.The subscriber is automatically removed if the subscriber is terminated. A subscriber can also be deregistered with the Replicator.Unsubscribe message.
Delete
A data entry can be deleted by sending a Replicator.Delete message to the local local
Replicator
. As reply of theDelete
a Replicator.DeleteSuccess is sent to the sender of theDelete
if the value was successfully deleted according to the supplied consistency level within the supplied timeout. Otherwise a Replicator.ReplicationDeleteFailure is sent. Note thatReplicationDeleteFailure
does not mean that the delete completely failed or was rolled back. It may still have been replicated to some nodes, and may eventually be replicated to all nodes.A deleted key cannot be reused again, but it is still recommended to delete unused data entries because that reduces the replication overhead when new nodes join the cluster. Subsequent
Delete
,Update
andGet
requests will be replied with Replicator.DataDeleted, Replicator.UpdateDataDeleted and Replicator.GetDataDeleted respectively. Subscribers will receive Replicator.Deleted.In the
Delete
message you can pass an optional request context in the same way as for theUpdate
message, described above. For example the original sender can be passed and replied to after receiving and transformingDeleteSuccess
.CRDT Garbage
One thing that can be problematic with CRDTs is that some data types accumulate history (garbage). For example a
GCounter
keeps track of one counter per node. If aGCounter
has been updated from one node it will associate the identifier of that node forever. That can become a problem for long running systems with many cluster nodes being added and removed. To solve this problem theReplicator
performs pruning of data associated with nodes that have been removed from the cluster. Data types that need pruning have to implement RemovedNodePruning. The pruning consists of several steps:- When a node is removed from the cluster it is first important that all updates that were
done by that node are disseminated to all other nodes. The pruning will not start before the
maxPruningDissemination
duration has elapsed. The time measurement is stopped when any replica is unreachable, but it's still recommended to configure this with certain margin. It should be in the magnitude of minutes. - The nodes are ordered by their address and the node ordered first is called leader.
The leader initiates the pruning by adding a
PruningInitialized
marker in the data envelope. This is gossiped to all other nodes and they mark it as seen when they receive it. - When the leader sees that all other nodes have seen the
PruningInitialized
marker the leader performs the pruning and changes the marker toPruningPerformed
so that nobody else will redo the pruning. The data envelope with this pruning state is a CRDT itself. The pruning is typically performed by "moving" the part of the data associated with the removed node to the leader node. For example, aGCounter
is aMap
with the node as key and the counts done by that node as value. When pruning the value of the removed node is moved to the entry owned by the leader node. See RemovedNodePruning#prune. - Thereafter the data is always cleared from parts associated with the removed node so that it does not come back when merging. See RemovedNodePruning#pruningCleanup
- After another
maxPruningDissemination
duration after pruning the last entry from the removed node thePruningPerformed
markers in the data envelope are collapsed into a single tombstone entry, for efficiency. Clients may continue to use old data and therefore all data are always cleared from parts associated with tombstoned nodes.
- final class ReplicatorSettings extends AnyRef
- trait RequiresCausalDeliveryOfDeltas extends ReplicatedDelta
Marker that specifies that the deltas must be applied in causal order.
Marker that specifies that the deltas must be applied in causal order. There is some overhead of managing the causal delivery so it should only be used for types that need it.
Note that if the full state type
T
is different from the delta typeD
it is the deltaD
that should be marked with this. - final case class SelfUniqueAddress(uniqueAddress: UniqueAddress) extends Product with Serializable
Cluster non-specific (typed vs classic) wrapper for pekko.cluster.UniqueAddress.
Cluster non-specific (typed vs classic) wrapper for pekko.cluster.UniqueAddress.
- Annotations
- @SerialVersionUID()
- sealed abstract class VersionVector extends ReplicatedData with ReplicatedDataSerialization with RemovedNodePruning
Representation of a Vector-based clock (counting clock), inspired by Lamport logical clocks.
Representation of a Vector-based clock (counting clock), inspired by Lamport logical clocks.
Reference: 1) Leslie Lamport (1978). "Time, clocks, and the ordering of events in a distributed system". Communications of the ACM 21 (7): 558-565. 2) Friedemann Mattern (1988). "Virtual Time and Global States of Distributed Systems". Workshop on Parallel and Distributed Algorithms: pp. 215-226
Based on code from
org.apache.pekko.cluster.VectorClock
.This class is immutable, i.e. "modifying" methods return a new instance.
- Annotations
- @SerialVersionUID()
Value Members
- object DistributedData extends ExtensionId[DistributedData] with ExtensionIdProvider
- object DurableStore
An actor implementing the durable store for the Distributed Data
Replicator
has to implement the protocol with the messages defined here.An actor implementing the durable store for the Distributed Data
Replicator
has to implement the protocol with the messages defined here.At startup the
Replicator
creates the durable store actor and sends theLoad
message to it. It must then reply with 0 or moreLoadData
messages followed by oneLoadAllCompleted
message to thesender
(theReplicator
).If the
LoadAll
fails it can throwLoadFailed
and theReplicator
supervisor will stop itself and the durable store.When the
Replicator
needs to store a value it sends aStore
message to the durable store actor, which must then reply with thesuccessMsg
orfailureMsg
to thereplyTo
. - object Flag extends Serializable
- object FlagKey extends Serializable
- object GCounter extends Serializable
- object GCounterKey extends Serializable
- object GSet extends Serializable
- object GSetKey extends Serializable
- object Key extends Serializable
- object LWWMap extends Serializable
- object LWWMapKey extends Serializable
- object LWWRegister extends Serializable
- object LWWRegisterKey extends Serializable
- object LmdbDurableStore
- object ORMap extends Serializable
- object ORMapKey extends Serializable
- object ORMultiMap extends Serializable
- object ORMultiMapKey extends Serializable
- object ORSet extends Serializable
- object ORSetKey extends Serializable
- object PNCounter extends Serializable
- object PNCounterKey extends Serializable
- object PNCounterMap extends Serializable
- object PNCounterMapKey extends Serializable
- object Replicator
- object ReplicatorSettings
- Annotations
- @ccompatUsedUntil213()
- object VersionVector extends Serializable
VersionVector module with helper classes and methods.