seahorse
seahorse

Reputation: 2470

Akka - how to configure to guarantee a message reaches another actor?

Akka actors are based off fire and forget mechanism for exchanging messages, how can I configure Akka so that messages are guaranteed to be delivered to another actor?

Upvotes: 0

Views: 140

Answers (1)

Leo C
Leo C

Reputation: 22449

Ordinary Akka actors, by its design principle, don't guarantee message delivery. Akka does however provide an at-least-once delivery option if you use its PersistentActor.

At-least-once delivery essentially ensures that the persistent sender actor will keep sending messages to the receiver at a configurable frequency until it receives confirmation from the receiver (or from some termination routine for canceling ongoing delivery attempts).

With at-least-once delivery, persisted messages will be re-sent until receipt of confirmation. Akka provides method deliver to send each message tagged with a consecutive monotonically increasing deliveryId and, upon receiving a confirmation with the corresponding deliveryId from the receiver, uses method confirmDelivery to signal successful delivery of the message.

The following Scala snippet, which is part of the sample code from the Akka doc, highlights the key at-least-once delivery logic in the sender actor class (which extends PersistentActor with AtLeastOnceDelivery):

override def receiveCommand: Receive = {
  case s: String =>
    persist(MsgSent(s))(updateState)
  case Confirm(deliveryId) =>
    persist(MsgConfirmed(deliveryId))(updateState)
}

override def receiveRecover: Receive = {
  case evt: Evt => updateState(evt)
}

def updateState(evt: Evt): Unit = evt match {
  case MsgSent(s) =>
    deliver(destination)(deliveryId => Msg(deliveryId, s))
  case MsgConfirmed(deliveryId) =>
    confirmDelivery(deliveryId)
}

Note that the same persistence handler updateState is used to persist events corresponding to deliver and confirmDelivery for consistent state recovery.

Upvotes: 1

Related Questions