- C# 90%
- TypeScript 10%
Implementing Event Sourcing and CQRS #
DISCLAIMER:
"Cogito ergo sum" - "I think, therefore I am"
Or as I put it: "I think, therefore I have opinions"
In this repository you will find my opinions on how to implement event sourcing and CQRS, "ports & adapters", project structure and various different things. It is ok, that your opinions differ. Neither of us may be "right" - whatever "being right" actually means. 🤷
What we might agree on: context mattersAnd I won't go into the details of the different technologies used here. I assume you basically know enough about all this. If not, there are tons of resources out there to all of these topics.
Some of my requirements are
- On-Premise: No "cloud only" features like Azure Tables etc.
- Cheap: Low/no license costs
- Scalable: If really needed - not "globally with millions of concurrent users", but maybe to hundreds or even a thousand users.
Status of this project #
Not even alpha
I still am in the phase of figuring things out and I publish breaking changes all the time. Sometimes multiple times per day.
Build Requirements #
- Aspire: https://aspire.dev/
- .NET: https://dot.net/
- NodeJS: https://nodejs.org/
- pnpm: https://pnpm.io/
Quickstart #
I try to use the latest bits, so update frequently.
aspire update --self --channel stable
dotnet tool restore
npm install --global corepack@latest
corepack enable pnpm
Restore, build, and test.
dotnet cake.cs --install --rebuild --target Test
Run.
aspire run
Or use the devcontainer or your compatible IDE of choice.
Why Microsoft Orleans? #
- Grains are single-threaded (non-reentrant)
➡️ Queuing of commands sent to handlers - Grains are kept in memory for some time
➡️ Caching of active projections - Streaming
➡️ Easy notifications of events
➡️ Abstract integration with different message brokers - Extensible providers for storage/streaming
➡️ Integration with custom storage/message broker
...and I always wanted to try this, so why not? 🤷
Why PostgreSQL? #
Almost every application needs to store data. There are a lot of different kinds of storage, like filesystems, relational databases, NoSQL databases etc.. Some of them are "cloud only" like Azure Tables, others may need complex setup and configuration.
PostgreSQL is a mature relational database with some interesting features. It can be easily installed locally, run as a container or purchased as a managed service.
And it has this feature of "logical replication" which I always wanted to try using it as an outbox. Because with every kind of "event store" you are really interested in having some kind of outbox to publish these events for consumers like projections. Please read this post by Oskar Dudycz for more information.
Why NATS/Redis/Entity Framework Core/ASP.NET Core/Angular? #
"Well, actually" these don't matter.
Orleans needs some kind of storage for making its clustering work. And you should separate that from your grains' storage. In this repository I use Redis for that. But you can use whatever you need - even "localhost clustering" works.
Speaking of "grain storage", since there's already a PostgreSQL database involved, I just use the Ado.Net storage provider of Orleans. But as Orleans is highly configurable, use what you need.
For accessing a database there are a lot tools out there. You can write raw SQL or use some kind of helper like Dapper. I chose Entity Framework Core, because I know how to use that. And it's "batteries included" when it comes to managing migrations. Finally this repository is not about how to store data. If your projections have to fulfill different needs, use the right tool for the job.
Additionally for Orleans Streams you need some kind of backbone. NATS seems cool and there's some built-in provider for that.
An application is useless if it doesn't provide some kind of API. The most used one is some kind of HTTP/JSON API. I know how to use ASP.NET Core and it integrates very well with Orleans.
Handcrafting HTTP requests with curl or http-files is a good point to start. But in the end you want some kind of frontend, which is accessable. Angular is the framework where I'm comfortable with.
Glossary #
DISCLAIMER: Work in Progress - not used consistently throughout this repository.
Domain #
The bounded context where the domain-events have a dedicated meaning.
Domain-Event #
A data structure containing metadata and a payload. It describes a changed to a "thing" inside a domain.
Domain-Event-Metadata #
Common data available on every domain-event like the Event-Id, Stream-Type, Stream-Id, Stream-Version, Tenant-Id, Created-At timestamp, User-Id, Trace-Id, and Span-Id
Payload #
Application defined part of the domain-event. Can be empty.
Public-Message #
Like a domain-event but used for communication with other systems. It has meaning outside of the domain and must be handled like a public api.
Event-Store #
The part of the persistence layer where all the domain-events and public-messages are stored.
Event-Stream / Stream #
The sequence of domain events sharing the same stream-type and stream-id ordered by their stream-version.
Stream-Type #
A string describing the type of the stream represented by a collection of domain-events.
Stream-Id #
A unique identifier represented by a UUID (Guid), the id of the "thing" behind this stream.
Stream-Version #
A consecutive numbering on the domain-events of one stream. They start at 1 and have no gaps. The combination of stream-id and stream-version is unique in the whole system.
Projection #
Aggregation of one or multiple event-streams into a data structure. Can be used as a read-model or as the state of a command-handler. A projection can be persisted or held in memory.
Command #
A data structure send to a command-handler describing an intent to changing a stream.
Command-Handler #
The business logic that decides if a command can be executed on the current state of a stream. It emits one or more domain-events which will be added to the event-stream.
Execute Command #
- Frontend sends a command to the WebApi
- After validating the command the WebApi forwards it to the Orleans cluster
- Orleans activates the command-handler grain and restores its state from the event store (PostgreSQL)
- It handles the command and returns the created events
- Orleans stores the events in the event store and apply them to the state (in memory)
- Success is reported back to the WebApi and Frontend
- After a timeout Orleans deactivates the grain and releases its resources
Execute Commands In Parallel #
While Orleans is executing a command on a grain, incoming additional commands are queued in the inbox of the grain. Only after finishing the first command, the next command will be executed. Since the state stays in memory, restoring from the event store is not needed.
Persistent Projections #
AKA "persisted views"
- Orleans stores the event in the event store (PostgreSQL)
- PostgreSQL publishes the event with its logical replication feature
- The Outbox is listening on its replication slot and publishes the events on a message queue (NATS)
- NATS is forwarding the events back into the Orleans cluster
- Orleans activates a projection grain which updates the corresponding row in a database table
- The projection grains stays in memory, speeding up the updates
- Multiple events are processed in order one at the time (like command queuing)
- After a timeout Orleans deactivates the projection grain and releases its resources
Query Persisted Views #
- Frontend sends a query to the WebApi
- After validating the request the WebApi executes the query against the database
- The response is sent back to the Frontend
Rebuild Persistent Projections #
If you have to change the logic of your persisted projection (add/remove fields, interpret events in a different way), you have the problem, that you have a database full of data, that's not conforming to the new kind of projection.
But event sourcing has you covered! You can "just" delete all of the projected data and rebuild the database with replaying all the events that are important to the projection. But doing this manually can be tedious.
To make this easier, there's an IPersistentProjection interface, that encapsulate the rebuild logic.
There's also an EF Core implementation EntityFrameworkCorePersistentProjection, from which you can derive your projection and filling in the details like the DbContext, the type of the projection entity and the basetype of the events.
All IPersistentProjections are registered as keyed services in the dependency injection container including a version number.
Whenever the projection has to be rebuilt, increase the version registered in DI.
With this in place the migration command can iterate over all persistent projections which are outdated and call the RebuildAsync method.
The actual version of the projection is stored as an PersistentProjectionEvent in the event store.
If needed this can be extended with a --force option to rebuild all projections regardless of their version.
This might be useful if only the event store is restored from a backup.
Ad-hoc Projections #
You don't always need to persist a projection to some database. If your stream is not that long (and it shouldn't be very long, otherwise "you're holding it wrong") you can just read the events from the event store and project them in-memory. The advantage is, that you are always free to adjust the logic of your projection. Just redeploy your application and you will have a fresh view on the world of your data.
And this is where the lifecycle of Orleans grains seems like a perfect fit. If you call a grain and it's not activated yet, Orleans will do that for you. On activation the grain can read state, like building up the projection in-memory. Additionally it can explicitly subscribe to the stream of the events it is interested in. It will receive updates automatically and can apply them to the in-memory projection. If the API calls this grain again while it's been active, it can just return the data. It's (more or less) guaranteed to be up-to-date. As up-to-date as eventually consistency is.
Query In-Memory Views #
- Frontend sends a query to the WebApi
- After validating the request the WebApi forwards it to the Orleans cluster
- Orleans activates the view grain and restores its state from the event store (PostgreSQL)
- The view grain subscribes for updates on this view on the message queue
- The response is sent back to the WebApi and Frontend
- While the view grain is activated it updates itself in memory
- The next request can be answered directly from memory, speeding up the response time
- After a timeout Orleans deactivates the view grain and releases its resources
Various Notes #
Find Out-Of-Date Persistent Projections #
When the event stream and the persistent projection is stored in the same database
you can easily query outdated projections with a JOIN.
Example:
select m."StreamId", max(l."Version") as "actual version", max(m."StreamVersion") as "expected version"
from "EventSourcing"."Message" as m
left join "ToDo"."ListItem" as l on m."StreamId" = l."ToDoId"
where m."StreamType" = 'ToDo_TaskEvent'
and (l."Version" is null or l."Version" < m."StreamVersion")
group by m."StreamType", m."StreamId"
Bombardier #
With Grain:
bombardier --http2 -l -c 300 -n 1000 -t 30s -m POST -H "Content-Type: application/json" -b "{""Content"":""Dummy""}" http://localhost:5188/api/measure/webapi-grain