Oskar Dudycz

Pragmatic about programming

Events should be as small as possible, right?

2021-04-14 oskar dudyczEvent Sourcing

cover

TV size? The bigger, the better. Debt amount? Opposite. It’s hard to find the right size that suits all. How big should the event be? What amount of information should it contain? Unfortunately, we haven’t managed to standardise the SI unit on that yet. In this post, I’ll discuss basic rules on that topic.

The most common statement is that the event should be as small as possible. It is roughly accurate. What does “as small as possible” mean? The answer is not apparent. Let’s think about the reason for publishing events. An event is information about a fact in the past (Read more about event basics in my other article “What’s the difference between a command and an event?”).

It is an inverted type of communication. In the classic HTTP API, the interested client must request the service. By publishing the event, we inform all listening modules of its occurrence. We might not even know if anyone is interested. We’re unsure and don’t know what will happen after the message is received. That’s okay most of the time, as it allows for decoupling of services and setting correct boundaries.

Contract definition practices and review are pretty standard for Web API. There’s a lot of discussion about whether or not we’re designing a system according to REST practices. For some reason, such an approach is not typical for the events’ definition.

In my opinion, Web API and events’ design are not so different. Both of them should be treated as the public API. Of course, they have other formats, protocols, etc.; however, general design principles are the same. If we’re using an API-first approach, we should define public API as the first step of our design process. By public, I mean “public-public” available for all and an “internal public” API between our services. The API definition should be our starting point for the system design.

The contrary approach is “Backend for frontend”, where API is tailored for the client applications’ needs. In this approach, the client’s preferences are the most important. The client application should be able to use endpoints as effectively as possible.

Both approaches have advantages and disadvantages. “API first” is usually more consistent, more organic. Nevertheless, it can cause difficulties for the clients, as they need to adapt and sometimes do workarounds. “Backend for frontend” allows clients to work more efficiently. However, it moves more effort on the backend. The duplication is more significant, and it may be harder to maintain a consistent vision.

Why am I writing about Web API when I should write about events? By creating an event-based system, we will not avoid these dilemmas. Let’s take the invoicing process as an example. After the final confirmation of the order:

  • The Financial module should issue an invoice.
  • The Shipment module should send it.
  • The Notification module should send an e-mail.

Accordingly, we can define an OrderConfirmed event with all the information collected during the process, e.g. the buyer’s data, address, total amount, and order details. However, it may turn out that the shipment module does not need detailed financial data. It only needs to know where and to whom to send the product. The financial module does not need address data for shipment, but only the company data (which may differ from personal). The notification module, in turn, should not know anything about the buyer except his name and e-mail. The only thing that we’ll be sending in an e-mail is a link to the order page.

Therefore, it may turn out that the OrderConfirmed event in such an amassed form will have redundant data. Adding GDPR into the equation makes things more challenging. We might not want to send all data everywhere. Therefore, instead of one event, you can publish three:

  • OrderConfirmed with necessary order data.
  • OrderReadyForShipment with data for the shipment module (like address, etc.).
  • OrderPaid with financial information.

Thanks to this, each module will be listening to a specific event. Those events can be sent to different stream/queue/topic/subscription. As with “Backend for frontend”, this can cause duplication of data and a slightly higher maintenance cost. However, it can be a much better solution than one event to rule them all. We’re also risking bigger coupling between services. We need to know what other modules need, and our module must adapt.

On the other hand, a common mistake is taking the rule that events should be as granular as possible literally. Let’s go back to our invoicing example. Before we place an order lot of things may happen:

  • User shopping can be initiated.
  • Product may be added to cart.
  • Deliver address may be selected.
  • Product availability may be confirmed or denied.
  • etc.

All of those events are relevant and meaningful for the ordering module. We want to gather as much business information as we can. It’s perfectly fine to have them as granular as possible. However, if we’re going to publish all of them outside, that could be a huge issue. By doing that, we’re asking other modules to:

  • get user data from BucketAssignedToUser.
  • product data from ProductAddedToBucket.
  • address data from DeliveryAddressSelected.

In short, we’re demanding other modules know all the internal details of our process. It is the first step to a distributed monolith.

What if we extend the process by an additional event? What if we change the shape of events? For example, if the financial module does not know that we added the ProductQuantityUpdated event, it might not be able to not generate the correct data for the invoice.

It gets demanding not only for others but also for us. We can ignore other’s needs and provide breaking changes. However, if we care for our product’s success, then we need to develop coordination. Inform others about breaking changes, etc.

I suggest splitting events into Internal and External. Internal are meaningful in the specific module context. External are understandable in the context of the entire system and overall business process.

Can an event be internal and external at the same time? Of course they can, even the previously mentioned OrderConfirmed. However, if we have five events that change the order status, it might not be convenient to pass them externally. If other modules are only interested in information about the status change, we can do an event mapping. We can create an internal Event Handler that will listen for internal events, then map to the external OrderStatusChanged event and publish it outside. In EventStoreDB, you can use projections for events transformations and subscriptions for listening to the projected stream and forwarding it further.

So there is no best answer. As usual: it depends.

Therefore, our events should be as small as possible, but not smaller. When designing them, let’s keep a healthy pragmatism and not forget that they’re also an essential part of our public contract.

Read also the extended follow up to this article Internal and private events, or how to design event-driven API.

Cheers!

Oskar

p.s. Check my two other articles where I expand more on the events in different contexts:

👋 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