Persistence
Overview
By default, GoAkt does not provide a built-in persistence mechanism. However, developers can seamlessly integrate a custom persistence layer when implementing the Actor interface to make the given actor a persistent actor depending upon the application needs. This flexibility allows any actor to persist its state according to application needs, ensuring continuity and resilience during failures or migrations.
Implementing Persistence
The decision to persist data is entirely in the hands of the developer. By adding the persistence layer, an actor can become "persistent," maintaining its state even after restarts or migrations. All the developer needs to do is to leverage on the Extensions capabilities and the Actor lifecycle hooks:
The
PreStartThis hook is invoked right before the actor begins processing messages. It is ideal for state recovery. If an actor is restarted—whether due to a crash, a supervisor-triggered restart, a manual stop-start, or even migration within a cluster—thePreStarthook can be used to retrieve and restore its previous state. It is recommended to implement recovery logic here to ensure that any persisted data is loaded and the actor can resume operation with its historical context.The
PostStopCalled after the actor has been successfully shut down. This hook is best suited for flushing or saving any remaining in-memory state to the persistence store. Use thePostStophook to ensure that any final state changes or pending data are securely saved, maintaining data integrity for the next startup.
Best Practices
State Recovery: Always verify and load any previously persisted state during the
PreStartphase to ensure smooth recovery after an unexpected shutdown.Data Integrity: Ensure that any unsaved data is properly flushed during the
PostStopphase to prevent data loss.Modular Design: Keep the persistence logic modular so that it can be updated or replaced without affecting the core actor logic.
Example
A good example of how to implement Persistence can be found here.
Last updated