Search code examples
microservicesevent-sourcing

Event sourcing - Event streams clarification


I got into a microservice project and I faced this problem. Suppose you have a table reservation service composed of two microservices:

  • Restaurant service (which manages restaurant information like name, owner, tables).
  • Reservation service (which manages the reservation validation workflow).

The event stream for the "Restaurant" entity was pretty simple: the streamId is the restaurantId and every event like "tableAdded" or "tableRemoved" has a incremental eventId. Replaying every event and getting the aggregate is trivial.

What about reservations? My current event stream design uses the restaurantId as streamId and every event like "reservationAccepted" or "reservationRefused" is appended to that stream.

The algorithm responsible of the validation of a reservation request needs to know the previous and following reservations (within 3 hours from the booking time of the incoming request).

Regardless of this no reservation with booking time older than now should be taken into account and its event should not be replayed, but with this design every event is replayed for every request.

To summarize: if I ask for a reservation for tomorrow, the system will replay reservations from 6 months ago that usually are not related with the incoming request because they refers to a moment in the past.

This leads to inefficiencies over time as result of the huge amount of unnecessary events that are replayed. I thought to solve it using daily snapshots but it seems the wrong way to do it.

Any ideas?

Thanks in advance for any kind of help!


Solution

  • I suggest learning about CQRS https://martinfowler.com/bliki/CQRS.html which is an important piece of the puzzle when using event driven.

    Simply put, it is reasonable that you keep a view of the events that are relevant to a business requirement in a separate entity that you can query with the relevant data.

    In your example, there is a business requirement concerning the validation of requests, so it makes sense that you build a table from the events that you can ask simply for the last 3 hours of reservations to receive the relevant information before you create a new event that is valid.

    This is sometimes also referred to as a projection: https://dzone.com/articles/the-good-of-event-sourcing-projections

    Projections can be

    1. computed when the validation occurs (could be inefficient like you stated)

    2. recomputed or updated when a new event that is related to that projection occurs.

    3. Anything in between those options that makes sense to you.