Skip to content
Proyek

oskardudycz/EventSourcing.JVM

Lihat di GitHub

Tentang

Contoh dan tutorial Event Sourcing dalam bahasa JVM

Pembelajaran dan pendidikan

Cara angka ini diukur

Pertumbuhan bintang terukur

dalam 24 jam
0
dalam 7 hari
+1
dalam 15 hari
+4
dalam 1 bulan
Mengumpulkan riwayat

Perubahan bersih pada periode yang tumpang tindih, bukan total harian. Pengukuran yang belum tersedia dibiarkan kosong. Bintang menunjukkan perhatian, bukan kualitas.

README.md

Asli

Github Sponsors blog Architecture Weekly LinkedIn

EventSourcing.JVM

Tutorial, practical samples and other resources about Event Sourcing in JVM. See also my similar repositories for .NET and NodeJS.

Event Sourcing

What is Event Sourcing?

Event Sourcing is a design pattern in which results of business operations are stored as a series of events.

It is an alternative way to persist data. In contrast with state-oriented persistence that only keeps the latest version of the entity state, Event Sourcing stores each state change as a separate event.

Thanks for that, no business data is lost. Each operation results in the event stored in the databse. That enables extended auditing and diagnostics capabilities (both technically and business-wise). What's more, as events contains the business context, it allows wide business analysis and reporting.

In this repository I'm showing different aspects, patterns around Event Sourcing. From the basic to advanced practices.

Read more in my article:

What is Event?

Events, represent facts in the past. They carry information about something accomplished. It should be named in the past tense, e.g. "user added", "order confirmed". Events are not directed to a specific recipient - they're broadcasted information. It's like telling a story at a party. We hope that someone listens to us, but we may quickly realise that no one is paying attention.

Events:

  • are immutable: "What has been seen, cannot be unseen".
  • can be ignored but cannot be retracted (as you cannot change the past).
  • can be interpreted differently. The basketball match result is a fact. Winning team fans will interpret it positively. Losing team fans - not so much.

Read more in my articles:

What is Stream?

Events are logically grouped into streams. In Event Sourcing, streams are the representation of the entities. All the entity state mutations ends up as the persisted events. Entity state is retrieved by reading all the stream events and applying them one by one in the order of appearance.

A stream should have a unique identifier representing the specific object. Each event has its own unique position within a stream. This position is usually represented by a numeric, incremental value. This number can be used to define the order of the events while retrieving the state. It can be also used to detect concurrency issues.

Event representation

Technically events are messages.

They may be represented, e.g. in JSON, Binary, XML format. Besides the data, they usually contain:

  • id: unique event identifier.
  • type: name of the event, e.g. "invoice issued".
  • stream id: object id for which event was registered (e.g. invoice id).
  • stream position (also named version, order of occurrence, etc.): the number used to decide the order of the event's occurrence for the specific object (stream).
  • timestamp: representing a time at which the event happened.
  • other metadata like correlation id, causation id, etc.

Sample event JSON can look like:

{
  "id": "e44f813c-1a2f-4747-aed5-086805c6450e",
  "type": "invoice-issued",
  "streamId": "INV/2021/11/01",
  "streamPosition": 1,
  "timestamp": "2021-11-01T00:05:32.000Z",

  "data":
  {
    "issuedTo": {
      "name": "Oscar the Grouch",
      "address": "123 Sesame Street",
    },
    "amount": 34.12,
    "number": "INV/2021/11/01",
    "issuedAt": "2021-11-01T00:05:32.000Z"
  },

  "metadata": 
  {
    "correlationId": "1fecc92e-3197-4191-b929-bd306e1110a4",
    "causationId": "c3cf07e8-9f2f-4c2d-a8e9-f8a612b4a7f1"
  }
}

Retrieving the current state from events

In Event Sourcing, the state is stored in events. Events are logically grouped into streams. Streams can be thought of as the entities' representation. Traditionally (e.g. in relational or document approach), each entity is stored as a separate record.

Id IssuerName IssuerAddress Amount Number IssuedAt
e44f813c Oscar the Grouch 123 Sesame Street 34.12 INV/2021/11/01 2021-11-01

In Event Sourcing, the entity is stored as the series of events that happened for this specific object, e.g. InvoiceInitiated, InvoiceIssued, InvoiceSent.

[
    {
        "id": "e44f813c-1a2f-4747-aed5-086805c6450e",
        "type": "invoice-initiated",
        "streamId": "INV/2021/11/01",
        "streamPosition": 1,
        "timestamp": "2021-11-01T00:05:32.000Z",

        "data":
        {
            "issuedTo": {
                "name": "Oscar the Grouch",
                "address": "123 Sesame Street",
            },
            "amount": 34.12,
            "number": "INV/2021/11/01",
            "initiatedAt": "2021-11-01T00:05:32.000Z"
        }
    },        
    {
        "id": "5421d67d-d0fe-4c4c-b232-ff284810fb59",
        "type": "invoice-issued",
        "streamId": "INV/2021/11/01",
        "streamPosition": 2,
        "timestamp": "2021-11-01T00:11:32.000Z",

        "data":
        {
            "issuedTo": "Cookie Monster",
            "issuedAt": "2021-11-01T00:11:32.000Z"
        }
    },        
    {
        "id": "637cfe0f-ed38-4595-8b17-2534cc706abf",
        "type": "invoice-sent",
        "streamId": "INV/2021/11/01",
        "streamPosition": 3,
        "timestamp": "2021-11-01T00:12:01.000Z",

        "data":
        {
            "sentVia": "email",
            "sentAt": "2021-11-01T00:12:01.000Z"
        }
    }
]

All of those events shares the stream id ("streamId": "INV/2021/11/01"), and have incremented stream position. We can get to conclusion that in Event Sourcing entity is represented by stream, so sequence of event correlated by the stream id ordered by stream position.

To get the current state of entity we need to perform the stream aggregation process. We're translating the set of events into a single entity. This can be done with the following the steps:

  1. Read all events for the specific stream.
  2. Order them ascending in the order of appearance (by the event's stream position).
  3. Construct the empty object of the entity type (e.g. with default constructor).
  4. Apply each event on the entity.

This process is called also stream aggregation or state rehydration.

Read more in my article:

Event Store

Event Sourcing is not related to any type of storage implementation. As long as it fulfils the assumptions, it can be implemented having any backing database (relational, document, etc.). The state has to be represented by the append-only log of events. The events are stored in chronological order, and new events are appended to the previous event. Event Stores are the databases' category explicitly designed for such purpose.

In the further samples, I'll use KurrentDB. It's the battle-tested OSS database created and maintained by the Event Sourcing authorities. It supports many dev environments via gRPC clients, including JVM.

Read more in my article:

Videos

Practical introduction to Event Sourcing with Spring Boot and EventStoreDB

Practical introduction to Event Sourcing with Spring Boot and EventStoreDB

Facts and Myths about CQRS

Facts and Myths about CQRS

Let's build the worst Event Sourcing system!

Let's build the worst Event Sourcing system!

The Light and The Dark Side of the Event-Driven Design

The Light and The Dark Side of the Event-Driven Design

Conversation with Yves Lorphelin about CQRS

Event Store Conversations: Yves Lorphelin talks to Oskar Dudycz about CQRS (EN)

How to deal with privacy and GDPR in Event-Sourced systems

How to deal with privacy and GDPR in Event-Sourced systems

Support

Feel free to create an issue if you have any questions or request for more explanation or samples. I also take Pull Requests!

๐Ÿ’– If this repository helped you - I'd be more than happy if you join the group of my official supporters at:

๐Ÿ‘‰ Github Sponsors

โญ Star on GitHub or sharing with your friends will also help!

Introduction to Event Sourcing self-paced kit

Event Sourcing is perceived as a complex pattern. Some believe that it's like Nessie, everyone's heard about it, but rarely seen it. In fact, Event Sourcing is a pretty practical and straightforward concept. It helps build predictable applications closer to business. Nowadays, storage is cheap, and information is priceless. In Event Sourcing, no data is lost.

The workshop aims to build the knowledge of the general concept and its related patterns for the participants. The acquired knowledge will allow for the conscious design of architectural solutions and the analysis of associated risks.

The emphasis will be on a pragmatic understanding of architectures and applying it in practice using Marten and KurrentDB.

  1. Introduction to Event-Driven Architectures. Differences from the classical approach are foundations and terminology (event, event streams, command, query).
  2. What is Event Sourcing, and how is it different from Event Streaming. Advantages and disadvantages.
  3. Write model, data consistency guarantees on examples from Marten and KurrentDB.
  4. Various ways of handling business logic: Aggregates, Command Handlers, functional approach.
  5. Projections, best practices and concerns for building read models from events on the examples from Marten and KurrentDB.
  6. Challenges in Event Sourcing and EDA: deliverability guarantees, sequence of event handling, idempotency, etc.
  7. Saga, Choreography, Process Manager, distributed processes in practice.
  8. Event Sourcing in the context of application architecture, integration with other approaches (CQRS, microservices, messaging, etc.).
  9. Good and bad practices in event modelling.
  10. Event Sourcing on production, evolution, events' schema versioning, etc.

You can do the workshop as a self-paced kit. That should give you a good foundation for starting your journey with Event Sourcing and learning tools like Marten and KurrentDB. If you'd like to get full coverage with all nuances of the private workshop, feel free to contact me via email.

Read also more in my article Introduction to Event Sourcing - Self Paced Kit.

Exercises

  1. Events definition.
  2. Getting State from events.
  3. Appending Events:
  4. Getting State from events read from event store:
  5. Business logic:
  6. Application logic with WebApi in Spring Boot:
  7. Optimistic Concurrency:
  8. Projections:
  9. Business Processes:

Event-Driven Architecture Workshop

The workshop builds Event-Driven Architecture knowledge step by step on a single domain, a hotel's guest stays and group checkouts. You start with modelling events and entities, then coordinate a business process across modules, first in memory and then on real message brokers.

Event-Driven Architecture exercises

Follow the instructions in exercises folders. See the workshop README for setup.

  1. Events definition.
  2. Entities definition.
  3. Business processes.
  4. Idempotency.
  5. Optimistic concurrency.
  6. Consistency.

Light and Dark Side of Event-Driven Architecture self-paced kit

The kit runs the e-commerce sample and makes it go wrong on purpose, the same way on every machine: lost trace context, duplicates, a broker outage, dead letters, a stuck subscription. A shopper keeps buying, so the dashboards and alerts have traffic. You find out what happened with the browser tools (Grafana, Kafbat UI, the RabbitMQ management UI, pgweb, EventCatalog, Swagger, Springwolf) and with an AI agent that reads the same data through read-only MCP servers. You need only Docker. See the kit's README for setup.

  1. Tools.
  2. Integration.
  3. Observability.
  4. Idempotency.
  5. Delivery guarantees.
  6. Concurrency and consistency.
  7. Ordering.
  8. Compensation and deadlines.
  9. Events versioning, in a later version of the kit.
  10. Incidents.
  11. Test-driven instrumentation.

Build Your Own Event Store Self-Paced Kit

The workshop teaches the event store basics by showing how to build your own Event Store on a relational database. It starts with the tables setup, goes through appending events and event store methods, and finishes with stream aggregation and time travelling. See the workshop README for setup.

  1. Streams and Events Tables
  2. Appending Events
  3. Event Store Methods
  4. Stream Aggregation
  5. Time Travelling

Samples

See also fully working, real-world samples of Event Sourcing and CQRS applications in the samples folder. Each sample is a separate Gradle build with its own README.

Samples are using CQRS architecture. They're sliced based on the business modules and operations. Read more about the assumptions in "How to slice the codebase effectively?".

Event Sourcing with Spring Boot and KurrentDB

Overview

Sample is showing basic Event Sourcing flow. It uses KurrentDB for event storage and Spring Data JPA backed with PostgreSQL for read models.

The presented use case is Shopping Cart flow:

  1. The customer may add a product to the shopping cart only after opening it.
  2. When selecting and adding a product to the basket customer needs to provide the quantity chosen. The product price is calculated by the system based on the current price list.
  3. The customer may remove a product with a given price from the cart.
  4. The customer can confirm the shopping cart and start the order fulfilment process.
  5. The customer may also cancel the shopping cart and reject all selected products.
  6. After shopping cart confirmation or cancellation, the product can no longer be added or removed from the cart.

Technically it's modelled as Web API written in Spring Boot and Java 22.

There are two variations of those samples:

Main assumptions

  • explain basics of Event Sourcing, both from the write model (KurrentDB) and read model part (PostgreSQL and Spring Data JPA),
  • present that you can join classical approach with Event Sourcing without making a massive revolution,
  • CQRS architecture sliced by business features, keeping code that changes together at the same place. Read more in How to slice the codebase effectively?,
  • clean, composable (pure) functions for command, events, projections, query handling, minimising the need for marker interfaces. Thanks to that testability and easier maintenance.
  • easy to use and self-explanatory fluent API for registering commands and projections with possible fallbacks,
  • registering everything into regular DI containers to integrate with other application services.
  • pushing the type/signature enforcement on edge, so when plugging to DI.

Prerequisites

For running the Event Store examples you need to have:

  1. Java JDK 22 or newer - https://www.oracle.com/java/technologies/downloads/. The build compiles and tests with the JDK you start Gradle with. If that JDK is older than 22 (Gradle needs at least 17), Gradle uses an installed JDK 22 or downloads it. CI checks JDK 22, 25 and 27.
  2. Installed IntelliJ, Eclipse, VSCode or other preferred IDE.
  3. Docker installed.

Tools used

  1. KurrentDB - Event Store
  2. PostgreSQL - Read Models
  3. Spring Boot - Web Application framework

Event Versioning

Shows how to handle basic event schema versioning scenarios using event and stream transformations (e.g. upcasting):

Uniqueness

Shows how to handle unique constraint checks in an event-sources system. Explains various techniques, like:

  • talking to business,
  • stream id design,
  • reservation pattern.

Read more in How to ensure uniqueness in Event Sourcing.

Hotel Management: Group Checkout

Shows how to handle a distributed process in Event Sourcing on a batch operation, the group checkout of hotel guests. Compares three styles:

  • saga,
  • process manager,
  • choreography.

Read more in Saga and Process Manager - distributed processes in practice.

E-Commerce: Purchase with Compensation

Shows how to handle a distributed process across modules of an online shop, where a later step can fail after earlier steps have finished. The Light and Dark Side of Event-Driven Architecture self-paced kit runs it with faults switched on. Explains:

  • compensating failures,
  • internal vs external events,
  • channels and queues on Kafka and RabbitMQ,
  • delivering messages reliably with the event store as outbox, on KurrentDB, PostgreSQL or in memory,
  • a web API and shop pages that read eventually consistent views without showing errors,
  • testing the whole application from the outside: its web API, its messages and its pages in a browser,
  • tracing a purchase in Grafana, with dashboards, business metrics and alerts,
  • documenting the messages and the context map in EventCatalog.

HOWTO.md takes you through one purchase, step by step. Read more in No, it can never happen!.

Stream Metadata

Shows, as tests, how KurrentDB's stream metadata limits what a stream read returns: $maxCount keeps the last events, $maxAge keeps the events younger than a given age, and $tb (truncate before) hides the events before a position.

Talk: Shopping Cart

The shopping cart code used in a talk: its commands, events and command handler, stored in KurrentDB.

Articles

Read also more on the Event Sourcing and CQRS topics in my blog posts:

Working on this repository

Each sample and each workshop folder is a separate Gradle build. You can open the whole repository or just one of those folders, for example samples/e-commerce: each folder has its own dev container and editor setup, so it works the same on its own.

Dev container

The quickest start is the dev container. It ships with the JDK, the recommended VS Code extensions, and the Git hooks already configured:

  1. Install Docker and VS Code with the Dev Containers extension.
  2. Open the repository root, or one sample or workshop folder, and run Dev Containers: Reopen in Container.

A sample's or workshop's container mounts the whole repository and opens that folder, so Git and the hooks work there too. The container uses your machine's Docker, so the tests can start KurrentDB, PostgreSQL and MongoDB with Testcontainers. One exception: if the Docker Compose Kafka from workshops/event-driven-architecture runs, the Kafka tests in the container fail, because that Kafka advertises localhost:9092, which inside the container is the container itself. Stop it, and the tests start their own Kafka.

Your own machine

Install Java 22 or newer, and Docker. The builds compile for Java 22, and Gradle builds and tests with the JDK you start it with, so a newer JDK works too. If that JDK is older than 22 (Gradle needs at least 17), Gradle uses an installed JDK 22 or downloads it. CI checks JDK 22, 25 and 27.

Then build and test from a sample or workshop folder:

cd samples/uniqueness
./gradlew build

The tests start their databases with Testcontainers. To reuse a running KurrentDB instead, start it with Docker Compose from the repository root (docker compose --profile kurrentdb up), and the tests connect to it.

Editor setup

VS Code - open a sample or workshop folder, or the root workspace file: code EventSourcing.JVM.code-workspace. Accept the recommended extensions when prompted (or run the Install All Recommended Extensions task). Format-on-save then matches the build exactly, so your changes stay clean as you type.

The common Gradle commands are also VS Code tasks (Ctrl+Shift+P โ†’ Run Task); compile is the default build (Ctrl+Shift+B). In a sample or workshop folder, the tasks run in that build. At the repository root, they run in the build that holds the file open in the editor.

IntelliJ IDEA - import a sample or workshop folder as a Gradle project and accept the prompt to install the palantir-java-format plugin. Enabling palantir-java-format keeps editor formatting in step with the build.

Formatting and the pre-commit hook

Spotless formats the Java code with palantir-java-format, with each folder's Gradle build as the single source of truth. The editor integrations and the pre-commit hook both defer to this same config, so once your environment is set up you rarely touch it directly. ./gradlew spotlessApply reformats everything in a build. Formatting never fails a build or CI, but the pre-commit hook stops a commit with unformatted code.

To get the pre-commit hook on your own machine, point Git at the shared hooks once (the dev containers already do this for you):

git config core.hooksPath .githooks

Before each commit, it runs the formatter in each build that has staged Java files. If the formatter changes a staged file, the hook stops the commit and lists the files. It doesn't stage the changes, so you can review them with git diff, stage them and commit again.

EventSourcing.JVM is Copyright ยฉ 2022 Oskar Dudycz and other contributors under the MIT license.

Jelajahi proyek terkait

Memuatโ€ฆ