eGo is a minimal library for building event-sourced and durable-state CQRS applications in Go. It lets you model your commands, events, and state with Protocol Buffers while relying on Go-Akt for actor-based execution, clustering, and scalable persistence.
The main branch currently targets the v4 API surface. See the changelog for the full release
history and migration details.
go get github.com/tochemey/ego/v4- Protobuf-first modeling for commands, events, and state
- Event-sourced and durable-state behaviors under one API
- Built-in support for CQRS projections and event streaming
- Snapshot-based recovery for faster replay
- Event batching to amortize persistence cost across commands
- Event adapters for schema evolution
- OpenTelemetry-ready tracing and metrics
- Encryption support for events and snapshots
- Saga/process manager support for long-running workflows
- Testkit and mocks for fast feedback
Version v4 introduces a major refresh across persistence, observability, operability, and developer experience.
- Snapshot Store: persist snapshots independently from events with
SnapshotStore,WithSnapshotStore(), andWithSnapshotInterval() - Event Batching: amortize store round-trips by accumulating events across multiple commands and flushing them in a
single write with
WithBatchThreshold()andWithBatchFlushWindow() - Event Adapters: evolve persisted event schemas during replay and projection consumption with the
eventadapterpackage - OpenTelemetry Integration: instrument command processing, persistence, projections, and active entities with
traces and metrics via
WithTelemetry() - Dead Letter Handler: capture projection failures after retry exhaustion with
DeadLetterHandler - Projection Rebuild: replay a projection from a chosen point in time using
Engine.RebuildProjection() - Scenario-based Testkit: Given/When/Then APIs for event-sourced and durable-state behaviors
- Migration Utility: migrate legacy inline state into snapshots with the
migrationpackage - Projection Lag Monitoring: inspect lag per shard with
Engine.ProjectionLag()and dedicated metrics - Retention Policies: automatically clean up old events and snapshots after successful snapshot writes
- Encryption / GDPR Support: encrypt payloads at rest and erase entity data with
Engine.EraseEntity() - Pluggable Logger: use any logging backend through the
Loggerinterface andWithLogger() - Saga / Process Manager: coordinate long-running workflows with compensation support
EventSourcedBehavior is eGo's core abstraction for domain models where state changes are represented as events.
Commands are processed sequentially, resulting events are persisted, and state is rebuilt by replaying those events.
In v4, event-sourced entities also benefit from:
- Snapshot-based recovery to reduce replay time
- Event batching for higher throughput under sustained command load
- Event adapters for schema evolution
- Retention policies to control storage growth
- Transparent encryption of events and snapshots
Typical workflow:
- Define protobuf messages for state, commands, and events.
- Implement your
EventSourcedBehavior. - Provide an
EventsStoreand, ideally, aSnapshotStore. - Configure runtime options such as snapshots, batching, retention, telemetry, or encryption.
- Start the entity with the eGo engine.
When an entity handles a high volume of commands, each individual store write becomes a throughput bottleneck. Event batching addresses this by accumulating events from multiple commands and flushing them in a single write.
Enable batching with two spawn options:
engine.Entity(ctx, behavior,
ego.WithBatchThreshold(10), // flush after 10 commands
ego.WithBatchFlushWindow(5*time.Millisecond), // or after 5ms, whichever comes first
)While a batch is being written, the actor stashes incoming commands and replays them once the write completes. Commands are processed optimistically against pending state, so callers do not observe any ordering anomalies.
A threshold of 0 (the default) disables batching entirely, preserving the one-command-one-write behavior.
DurableStateBehavior is a simpler model for cases where you only need the latest state instead of a full event log.
Each successful command produces a new state version, and only the latest version is persisted.
This is a good fit for:
- Configuration-style entities
- Lower-overhead persistence needs
- Use cases where audit replay is not required
Typical workflow:
- Define protobuf messages for state and commands.
- Implement your
DurableStateBehavior. - Provide a durable state store with
WithStateStore(). - Start the entity with the engine.
| Aspect | EventSourcedBehavior |
DurableStateBehavior |
|---|---|---|
| Persistence model | Persists domain events | Persists the latest state |
| Recovery | Replays events, optionally from snapshots | Loads the latest state |
| History | Full audit trail | No historical log |
| Complexity | Higher | Lower |
| Best fit | Traceable, business-critical workflows | Simpler CRUD-like aggregates |
eGo ships with in-memory stores for testing, but production deployments require durable persistence backends. The ego-contrib repository provides ready-to-use store implementations:
- Postgres event store, snapshot store, offset store, and durable state store
- MongoDB event store, snapshot store, offset store, and durable state store
To use a contrib store, import the relevant module alongside eGo:
import (
"github.com/tochemey/ego-contrib/eventstore/postgres"
"github.com/tochemey/ego-contrib/snapshotstore/postgres"
"github.com/tochemey/ego-contrib/offsetstore/postgres"
)You can also implement
persistence.EventsStore,persistence.SnapshotStore, orpersistence.StateStoredirectly to plug in any storage backend.
eGo can sustain hundreds of thousands of commands per second on a single node with an in-memory store, and tens of thousands with durable backends like Postgres. This section outlines the recommended approach to maximize throughput and minimize memory cost.
Batching amortizes the cost of a single store write across multiple commands. It is most effective when:
- The entity receives commands concurrently (multiple goroutines or upstream services)
- The persistence store has non-trivial write latency (e.g. database round-trip > 100us)
engine.Entity(ctx, behavior,
ego.WithBatchThreshold(10), // flush after 10 accumulated events
ego.WithBatchFlushWindow(5*time.Millisecond), // or after 5ms, whichever comes first
)Sequential command streams do not benefit from batching because each command waits for the flush window before the batch is written. For purely sequential workloads, leave batching disabled (the default).
| Write latency | Recommended threshold | Rationale |
|---|---|---|
| < 100us (in-memory) | Disabled (0) | Batching adds overhead with no I/O to amortize |
| 100us - 1ms | 5 - 10 | Small batches reduce flush window wait |
| 1ms - 10ms | 10 - 50 | Larger batches amortize the I/O cost well |
| > 10ms | 50 - 100 | Maximize events per write to offset high latency |
Without snapshots, recovery replays the full event history. Configure a snapshot interval to bound replay length:
engine.Entity(ctx, behavior,
ego.WithSnapshotInterval(100), // snapshot every 100 events
)Pair this with a SnapshotStore via ego.WithSnapshotStore() on the engine.
When snapshots are enabled, old events and snapshots can be cleaned up automatically:
engine.Entity(ctx, behavior,
ego.WithSnapshotInterval(100),
ego.WithRetentionPolicy(ego.RetentionPolicy{
DeleteEventsOnSnapshot: true,
DeleteSnapshotsOnSnapshot: true,
EventsRetentionCount: 200, // keep 200 most recent events
}),
)eGo's hot path is optimized for low allocation overhead (~22 heap allocations per command round-trip). The dominant allocation cost comes from Protocol Buffers serialization, which is inherent to the persistence model. To keep allocation pressure low:
- Keep command and event protos small. Smaller messages reduce marshal/unmarshal cost.
- Use snapshots. They reduce recovery replay length and the number of events held in the store.
- Avoid large state protos. The state is serialized on every reply; smaller states mean fewer bytes and less GC pressure.
For workloads beyond what a single node can handle, enable clustering to distribute entities across nodes:
engine := ego.NewEngine("myapp", eventStore,
ego.WithCluster(provider, partitions, replicaCount, host, remotingPort, gossipPort, clusterPort),
)Each entity is hashed to a partition and placed on a node. Commands are routed transparently. See the clustering documentation for details on discovery providers and topology configuration.
eGo pushes persisted domain changes to a stream so read models and integrations can react without reading directly from the primary store.
Projections consume the write-model stream and build read models using an offset store.
In v4, projections gain several operator-friendly improvements:
- Dead letter handling for unrecoverable projection failures
- Rebuild support from a chosen timestamp
- Lag, offset, and events-behind metrics per shard
- Event adapter support during consumption
- Automatic decryption before handlers process encrypted events
eGo provides publisher APIs for both write models:
EventPublisherforEventSourcedBehavioreventsStatePublisherforDurableStateBehaviorstate updates
Available connectors:
- Kafka
- Pulsar
- NATS
- WebSocket
Observability is a first-class concern in v4.
With WithTelemetry(), eGo can emit:
- Trace spans for command processing
- Command counters and latency histograms
- Persisted-event counters
- Projection processing counters
- Active entity and projection counts
- Projection lag, latest offset, and approximate events-behind metrics
eGo includes several production-focused capabilities:
- Faster recovery through snapshots
- Storage cleanup through retention policies
- At-rest encryption for events and snapshots
- GDPR-style erasure with
Engine.EraseEntity() - Pluggable structured logging
v4 adds first-class saga support for long-running business processes that coordinate multiple entities.
You can:
- Start a saga with
Engine.Saga() - Inspect it with
Engine.SagaStatus() - Model compensation logic for timeouts and failures
- Persist saga state using the same event-sourced foundations
eGo uses Go-Akt for clustering and entity distribution.
In v4, WithCluster() accepts ego.ClusterProvider, keeping your application code on eGo's abstraction instead of
depending directly on Go-Akt discovery types.
The testkit package helps you validate behavior quickly with in-memory stores and scenario-based testing.
eGo also ships mocks to simplify isolated unit tests around your stores and integrations.
Upgrading from v3 to v4 mainly involves:
- Updating imports from
github.com/tochemey/ego/v3togithub.com/tochemey/ego/v4 - Removing the
state *anypb.Anyparameter from projection handlers - Migrating inline event state into snapshots with the migration utility
- Configuring a
SnapshotStorefor optimal event-sourced recovery - Updating
WithLogger()usage to the newego.Loggerinterface - Switching cluster integrations to
ego.ClusterProvider
See CHANGELOG.md for the full breaking-change list.
Browse the examples directory for runnable samples and integration ideas.
Please follow the contribution guide.
