Oskar Dudycz

Pragmatic about programming

Event Sourcing on PostgreSQL in Node.js just became possible with Emmett

2024-07-12 oskar dudyczPostgreSql

2024 07 12 cover

Last week, I announced Pongo - Mongo, but it was on PostgreSQL. So, the Node.js library allows using PostgreSQL as a document database.

Today, I have at least an equally big announcement: I released the PostgreSQL event store for Emmett. Boom!

What’s Emmett? It’s an Event Sourcing library. I announced it some time ago and have worked on it continuously for the last few months. It already supports EventStoreDB, and now it has our favourite PostgreSQL storage!

Read more:

How to use it? Pretty simple. Start with installing npm package:

$ npm add @event-driven-io/emmett-postgresql

Then setup event store using connection string to PostgreSQL:

import { getPostgreSQLEventStore } from '@event-driven-io/emmett-postgresql';

const connectionString =
  "postgresql://dbuser:secretpassword@database.server.com:3211/mydb";

const eventStore = getPostgreSQLEventStore(connectionString);

Internally, it uses the node-postgres package with connection pooling. So you don’t need to do much more. Well, maybe besides gracefully closing it on the application closure:

await eventStore.close();

Cool, but what you can do with it? Check Emmett docs. The same you can do with EventStoreDB storage you can do with PostgreSQL!

Or you can actually do more with PostgreSQL, as…

PostgreSQL has inline projections support. What are inline projections? They’re functions updating your read models in the same transaction as appending events. So either all was stored or nothing. Of course, you need to be careful with them as they can slow your appends, but they’re really useful. Async projections will come in future releases.

Ok, but how to use it? Let’s say that you’d like to build a read model with a summary of your shopping cart:

type ShoppingCartShortInfo = {
  productItemsCount: number;
  totalAmount: number;
};

Transformation function could look like that:

const evolve = (
  document: ShoppingCartShortInfo | null,
  { type, data: event }: ProductItemAdded | DiscountApplied,
): ShoppingCartShortInfo => {
  document = document ?? { productItemsCount: 0, totalAmount: 0 };

  switch (type) {
    case 'ProductItemAdded':
      return {
        totalAmount:
          document.totalAmount +
          event.productItem.price * event.productItem.quantity,
        productItemsCount:
          document.productItemsCount + event.productItem.quantity,
      };
    case 'DiscountApplied':
      return {
        ...document,
        totalAmount: (document.totalAmount * (100 - event.percent)) / 100,
      };
  }
};

It’ll be run for each event of type ProductItemAdded and DiscountApplied that’s appended to the event store.

Let’s say that you’d like to use Pongo and store it as a document in PostgreSQL, then you can define projection as:

const shoppingCartShortInfoCollectionName = 'shoppingCartShortInfo';

const shoppingCartShortInfoProjection = pongoSingleStreamProjection({
  collectionName: shoppingCartShortInfoCollectionName,
  evolve,
  canHandle: ['ProductItemAdded', 'DiscountApplied'],
});

and register it through event store options:

import { projection } from '@event-driven-io/emmett';
import { getPostgreSQLEventStore } from '@event-driven-io/emmett-postgresql';

const connectionString =
  "postgresql://dbuser:secretpassword@database.server.com:3211/mydb";

const eventStore = getPostgreSQLEventStore(connectionString, {
  projections: projections.inline([
    shoppingCartShortInfoProjection,
    customProjection,
  ]),
});

We’re saying that we’d like to update the shoppingCartShortInfo collection using the evolve function for the following set of event types.

Internally, it’ll use the Pongo new feature: a handler that loads the existing document and tries to insert, replace or delete it depending on the result obtained from the function.

It look’s as follows:

const collection = pongo.db().collection<Document>(collectionName);

for (const event of events) {
  await collection.handle(getDocumentId(event), async (document) => {
    return await evolve(document, event);
  });
}

If you’re wondering what getDocumentId is, then for pongoSingleStreamProjection, it’ll automatically use the stream name as the document id.

Suppose you’d like to customise it, e.g. to match events from different streams. In that case, you can use the pongoMultiStreamProjection definition, which allows you to specify the document ID matcher for each event. For instance:

const shoppingCartShortInfoCollectionName = 'shoppingCartShortInfo';

const getDocumentId = ({type}:  ProductItemAdded | DiscountApplied): string => {
  switch(type)
  {
    case 'ProductItemAdded': 
      return event.metadata.streamName;
    case 'DiscountApplied': 
      return event.metadata.streamName;
  }
};

const shoppingCartShortInfoProjection = pongoSingleStreamProjection({
  collectionName: shoppingCartShortInfoCollectionName,
  evolve,
  canHandle: ['ProductItemAdded', 'DiscountApplied'],
  getDocumentId
});

You can also do a free-hand projection using pongoProjection that takes the following handler:

(pongo: PongoClient, events: ReadEvent<EventType>[]) => Promise<void>

Cool, isn’t it?

**Read more details in the follow up article Writing and testing event-driven projections with Emmett, Pongo and PostgreSQL

Of course, those are still experimental features; they need to be optimised, tested extensively, etc. But they work, which makes me happy.

As you see, I’m quite thrilled that I could deliver it, as this is a big milestone. This will enable many people to finally do Event Sourcing in Node.js using PostgreSQL and have basic building blocks.

All of that wouldn’t be possible with my recent changes to Pongo.

  1. I managed to close the basic coverage of document manipulation methods. I added initial versions of what was initially missing: replaceOne, drop, rename, countDocuments, count, estimatedDocumentCount, findOneAndDelete, findOneAndReplace, findOneAndUpdate, etc.

Now, a bigger portion that were made as preparations to Emmett PostgreSQL projections you just learned about:

  1. Added option to inject external connection pool and db client to Pongo collection as the first step for transaction handling. Now, you can create transactions outside and inject pool clients. It’s not yet fully the same as Mongo API; it’ll be delivered in follow-up PR.

  2. Strengthened the schema and updated the id from UUID to text. Changed _id type to TEXT. In PostgreSQL, this should be almost equally the same indexable. Of course, it’ll take a bit more storage, but let’s live with that for now. Changing from uuid to text will allow more sophisticated key strategies. Most importantly, it’ll reuse the stream ID as a document ID for Emmett projections.

Also, thanks to the Franck Pachot contribution, we confirmed that Pongo is compatible not only with vanilla Postgres but also databases like Yugabyte!

It was just a week, but I’m extremely happy with how Pongo was taken by the community. I got to HackerNews front page and got over 900 GitHub stars!

Now it’s the time for Emmett! Synergy with Pongo should help with that.

What a week! It’s easy to forget that Pongo was released just 7 days ago!

Now I can go to vacations, next blog will be in August!

Cheers!

Oskar

p.s. Ukraine is still under brutal Russian invasion. A lot of Ukrainian people are hurt, without shelter and need help. You can help in various ways, for instance, directly helping refugees, spreading awareness, putting pressure on your local government or companies. You can also support Ukraine by donating e.g. to Red Cross, Ukraine humanitarian organisation or donate Ambulances for Ukraine.

👋 If you found this article helpful and want to get notification about the next one, subscribe to Architecture Weekly.

✉️ Join over 11500 subscribers, get the best resources to boost your skills, and stay updated with Software Architecture trends!

Loading...
Event-Driven by Oskar Dudycz

cover

Through my window, I see the result of good plans but poor execution. Opposite my flat, there is a partially completed construction place. Buildings were supposed to be eye-catching Mediterranean style apartments. Delivery date? Two years ago. Actual? More and more unknown.

Some time ago, I heard that using Event Sourcing makes creating Event-Driven Architecture easier. The arguments were correct, that if we’re already publishing events to trigger business workflows, then at some point, we may want to also store events to not lose information. Agreed. However, I also heard that keeping the state as events will simplify things. We’ll have a source of truth with a record of the system behaviour. This will allow, e.g. to confront the results of the operations with the recorded state. I’d agree with that, with one distinction. It’s easier as long as you already know Event Sourcing.

Many people in the DDD community claim that the essential is to properly break down the system into autonomous parts called bounded contexts. Once we have it, the rest is secondary and will sort itself out. For sure.

Many seasoned programmers speak similarly about new technologies. They claim that they can translate past experience into new technologies. That’s true that by analogy, they can catch the big picture quicker. But isn’t it a bold assumption to say that Win.Forms specialist will learn Angular quickly?

The end result may differ a lot from the initial ideas. I saw the plan of those buildings next to me. Now I can see the effects of the execution. Or actually, the lack.

I believe that we should carefully acknowledge not only the point of view of our authorities but also their seating point. If we want to find out how to form a wall, do we ask an architect or a foreman? An architect may know the theory, but the practice is what we’re looking for. On the other hand, if you want to know where to put the wall, you prefer the architect to do measurements. At least if you don’t want to have the roof falling to your head.

After I had torn a ligament in my knee, I went to two qualified orthopedists. One said I should have surgery and do a reconstruction. The second stated that there is no need for that; rehabilitation should be enough. Guess which one had a specialization in surgery and which in rehabilitation?

People usually give us advice from the point where they’re currently standing. They are entitled to a biased view. An architect who rarely does programming will tend to downplay the value of implementation and tactical patterns. Midlevel developers will focus on technicalities instead of the global system impact. The team manager or consultant will emphasize the importance of soft skills (or esoteric techniques known only to them).

The truth is that we need all of them. The excellent plan will fall on the bad execution. The best execution for the wrong case will be just a waste of time. We should carefully evaluate the advice considering what we need and what an expert can give us.

Therefore, when we’re reading an article, watching a talk, let’s also pay attention to the place where the person is standing. The perspective from there may be much different from where we are right now. That can be good, as it may push us in the right direction. But it may also be misleading, as we accidentally take biases of this person without understanding the tradeoffs. Personally, I prefer to follow not only people from pedestal but also those that are closer to my position. A bit further in the journey, but not too far. That helps me to calibrate my view as those people are more relative to my daily struggles.

Polish historical leader Józef Piłsudzki reportedly used to say: “Right is like an ass, everyone has its own”.

Cheers!

Oskar