DEV Community

Cover image for Lightweight implementation of Event Sourcing using PostgreSQL as an event store πŸš€πŸ•—πŸ”™πŸ•˜
Eugene Khyst
Eugene Khyst

Posted on

Lightweight implementation of Event Sourcing using PostgreSQL as an event store πŸš€πŸ•—πŸ”™πŸ•˜

Do you use the Event Sourcing pattern?
If you have a Java Spring Boot application with a PostgreSQL database, you can implement Event Sourcing without introducing new specialized databases or frameworks.

How do I know that I need the Event Sourcing pattern?

If you have an application dealing with an entity called Order, you should adopt Event Sourcing to keep track of all changes, and know how the Order got into the current state.

Event Sourcing gives you:

  1. the true history of the system (audit and traceability),
  2. the ability to put the system in any prior state (debugging),
  3. the ability to create read projections from events as needed to respond to new demands.

Order entity CRUD vs Event Sourcing

Order entity CRUD vs Event Sourcing

There are several well-known specialized frameworks and databases for Event Sourcing: EventStoreDB, Marten, Eventuate, to name a few.

Do I really need a specialized database and framework for Event Sourcing? It would be easier to convince colleagues and management to try Event Sourcing if there was a way to use an existing PostgreSQL database as an event store and implement the Event Sourcing pattern with several classes without specialized frameworks.

Adopting a new framework or database you are not familiar with may stop you from trying the Event Sourcing pattern in your project. But you can actually implement Event Sourcing with a few classes and use PostgreSQL as an event store.

The postgresql-event-sourcing project is a reference implementation of an event-sourced system that uses PostgreSQL as an event store built with Spring Boot. Fork the repository and use it as a template for your projects. Or clone the repository and run end-to-end tests to see how everything works together.

The project describes in detail:

  • database model for storing events,
  • synchronous and asynchronous event handlers,
  • CQRS,
  • Transactional Outbox pattern,
  • Polling Publisher pattern,
  • optimized publisher that uses PostgreSQL LISTEN/NOTIFY capabilities,
  • and more.

PostgreSQL Event Sourcing

PostgreSQL Event Sourcing

This project can be easily extended to comply with your domain model. Event sourcing related code and application specific code are located in separate Gradle subprojects:

  • postgresql-event-sourcing-core: event sourcing and PostgreSQL related code, lightweight shared library,
  • event-sourcing-app: application specific code, simplified ride-hailing sample.

To adapt the project to your domain model, make changes to event-sourcing-app subproject. No changes to postgresql-event-sourcing-core subproject are required.

The source code is available on GitHub.

Top comments (0)