Estimate number of events in category

We are trying to count number of events in category with the following projection:

fromCategory(‘WB’)

.when({

$init: function () {

return { count: 0 }; // initial state

},

$any: function (s, e) {

s.count += 1;

return s;

}

})

The problem is that we often have an error during event store start with following message

[10780,16,08:06:20.783] The ‘$by_category’ projection faulted due to ‘An event emitted in recovery differ from the originally emitted event. Existing(’$>’, ‘C:258101323/P:258100652’). New(’$>’, ‘C:254898199/P:254896947’)’

After that projection stops counting events. We do reset it, but after doing that number of counted events is doubled. I understand that resetting of projections forces category stream to be rewritten once again but with new indexes.

Should we filter empty events somehow in the projection code?

To estimate events in category just read the last event from the stream its number is what you are looking for no need to fold over them

That was the initial implementation, but that number is doubled after projection $by_category reset. Thought that it could be solved by projections, isn’t it?