Search Results for

    Show / Hide Table of Contents

    AK1006 - Warning

    Calling Persist() or PersistAsync() inside a loop is an anti-pattern and is non-performant. Consider collecting all events in a collection and then call PersistAll() or PersistAllAsync() after the loop instead.

    Cause

    Akka.NET persistence tries its best to batch consecutive calls to Persist() or PersistAsync() methods, but there is no guarantee that all of them will be batched properly. \

    For example, lets assume that for each command, you generate 10 Persist() operations. This can potentially create 10 asynchronous database connection to complete:

    using Akka.Persistence;
    
    public class MyActor: ReceivePersistentActor
    {
        public override string PersistenceId { get; }
        public MyActor(string persistenceId)
        {
            PersistenceId = persistenceId;
            CommandAny(obj =>
            {
                for (var i=0; i<10; i++)
                {
                    Persist(i, o => {});
                }
            });
        }
    }
    

    Resolution

    If you know that a group of events need to be batched, it is a lot more performant to batch all Persist() operations into a single PersistAll() operation after the loop

    using Akka.Persistence;
    
    public class MyActor: ReceivePersistentActor
    {
        public override string PersistenceId { get; }
        public MyActor(string persistenceId)
        {
            PersistenceId = persistenceId;
            CommandAny(obj =>
            {
                var events = new List<int>();
                for (var i=0; i<10; i++)
                {
                    events.Add(i);
                }
                PersistAll(events, o => {});
            });
        }
    }
    

    The persist success callback will be called for each event that are successfully persisted, so you do not need to change your logic inside the callback.

    In this article
    • githubEdit this page
    Back to top
    Contribute
    • Project Chat
    • Discussion Forum
    • Source Code
    Support
    • Akka.NET Support Plans
    • Akka.NET Observability Tools
    • Akka.NET Training & Consulting
    Maintained By
    • Petabridge - The Akka.NET Company
    • Learn Akka.NET