Search code examples
c#neventstore

Get NEventStore head revision


I've got a new ES stream that's already got half a million events in it (no snapshots yet... I know, I'm getting there) and a simple client that atm is only appending (even more) events.

NEventStore.OpenStream(int.MinValue, int.MaxValue) takes a very long time to open the stream initially; after which I store the last revision and from then on only NEventStore.OpenStream(lastRevision, int.MaxValue) to append again. The problem's only on initial start.

Is there a mechanism within NEventStore to either simply append without opening, or to determine the head revision without opening the whole stream so I can then open from the last version and append. Of course I could also go direct to the database and query, but that's taking on a dependency I feel I shouldn't need.


Solution

  • You already mentioned a possible solution: Snapshots.

    This example opens a stream from the latest snapshot and adds a new snapshot after events are commited.

    // Get the latest snapshot
    var latestSnapshot = _eventStore.Advanced.GetSnapshot(streamId, int.MaxValue);            
    
    // Open the stream from the snapshot if there is one, otherwise open the stream as normal
    using (var stream = latestSnapshot == null ? 
        _eventStore.OpenStream(streamId) : 
        _eventStore.OpenStream(latestSnapshot, int.MaxValue))
    {
        // Add events and commit
        stream.Add(new EventMessage());
        stream.CommitChanges(Guid.NewGuid());
    
        // Add a new snapshot (with no payload)
        _eventStore.Advanced.AddSnapshot(
            new Snapshot(streamId, stream.StreamRevision, string.Empty));
    }      
    

    It is probably not necessary to add new snapshots this often. It's just an example to show how snapshots work.