How can I get the last event from an Event Store stream with only one HTTP request?

Viewed 1477

All the docs I can find seem to suggest I need two http requests to do this: one to the stream, giving me a link to the last event, and then one to follow that link.

That seems bizarre, isn't there a way to do this with just one request?

3 Answers

If using the .NET Client you can also use the read backwards API

Task<StreamEventsSlice> ReadStreamEventsBackwardAsync(string stream, int start, int count, bool resolveLinkTos)

Where

  • Start - Generally if you know which event number to start from but in this case we do not know so we can StreamPosition.End (-1) to start from the end.
  • Count - How many events to get going backwards

So this code will get you the last event on the stream (with linkTos enabled if its a projection)

 StreamEventsSlice slice = await Connection.ReadStreamEventsBackwardAsync("StreamName", StreamPosition.End, 1, true, creds);

The keyword is 'head', like git. So the last event is at [url of the stream]/head.

An alternative if you are using the EventStore gRPC client.

_client.ReadStreamAsync(Direction.Backwards, _streamName, StreamPosition.End, 1)

Very similar to the .NET version. You're requesting the stream to be read backwards starting at the end of the stream, and to return only one event.

Your result is then an iterable that will contain only one item - the latest event

Reading from a stream - reading backwards

Related