Files
java-design-patterns/event-driven-architecture
Ilkka Seppälä 6cd2d0353a docs: Content SEO updates (#2990)
* update yaml frontmatter format

* update abstract document

* update abstract factory

* use the new pattern template

* acyclic visitor seo

* adapter seo

* ambassador seo

* acl seo

* aaa seo

* async method invocation seo

* balking seo

* bridge seo

* builder seo

* business delegate and bytecode seo

* caching seo

* callback seo

* chain seo

* update headings

* circuit breaker seo

* client session + collecting parameter seo

* collection pipeline seo

* combinator SEO

* command seo

* cqrs seo

* commander seo

* component seo

* composite seo

* composite entity seo

* composite view seo

* context object seo

* converter seo

* crtp seo

* currying seo

* dao seo

* data bus seo

* data locality seo

* data mapper seo

* dto seo

* decorator seo

* delegation seo

* di seo

* dirty flag seo

* domain model seo

* double buffer seo

* double checked locking seo

* double dispatch seo

* dynamic proxy seo

* event aggregator seo

* event-based asynchronous seo

* eda seo

* event queue seo

* event sourcing seo

* execute around seo

* extension objects seo

* facade seo

* factory seo

* factory kit seo

* factory method seo

* fanout/fanin seo

* feature toggle seo

* filterer seo

* fluent interface seo

* flux seo

* flyweight seo

* front controller seo

* function composition seo

* game loop seo

* gateway seo

* guarded suspension seo

* half-sync/half-async seo

* health check seo

* hexagonal seo

* identity map seo

* intercepting filter seo

* interpreter seo

* iterator seo

* layers seo

* lazy loading seo

* leader election seo

* leader/followers seo

* lockable object seo

* rename and add seo for marker interface

* master-worker seo

* mediator seo

* memento seo

* metadata mapping seo

* microservice aggregator seo

* api gw seo

* microservices log aggregration seo

* mvc seo

* mvi seo

* mvp seo

* mvvm seo

* monad seo

* monitor seo

* monostate seo

* multiton seo

* mute idiom seo

* naked objects & notification seo

* null object seo

* object mother seo

* object pool seo

* observer seo

* optimistic locking seo

* page controller seo

* page object seo

* parameter object seo

* partial response seo

* pipeline seo

* poison pill seo

* presentation model seo

* private class data seo

* producer-consumer seo

* promise seo

* property seo

* prototype seo

* proxy seo

* queue-based load leveling seo

* reactor seo

* registry seo

* repository seo

* RAII seo

* retry seo

* role object seo

* saga seo

* separated interface seo

* serialized entity seo

* serialized lob seo

* servant seo

* server session seo

* service layer seo

* service locator seo

* service to worker seo

* sharding seo

* single table inheritance seo

* singleton seo

* spatial partition seo

* special case seo

* specification seo

* state seo

* step builder seo

* strangler seo

* strategy seo

* subclass sandbox seo

* table module seo

* template method seo

* throttling seo

* tolerant reader seo

* trampoline seo

* transaction script seo

* twin seo

* type object seo

* unit of work seo

* update method seo

* value object seo

* version number seo

* virtual proxy seo

* visitor seo

* seo enhancements

* seo improvements

* SEO enhancements

* SEO improvements

* SEO additions

* SEO improvements

* more SEO improvements

* rename hexagonal + SEO improvements

* SEO improvements

* more SEO stuff

* SEO improvements

* SEO optimizations

* SEO enhancements

* enchance SEO

* improve SEO

* SEO improvements

* update headers
2024-06-08 19:54:44 +03:00
..
2019-12-07 18:03:49 +02:00
2022-09-14 23:22:24 +05:30
2024-06-08 19:54:44 +03:00

title, shortTitle, description, category, language, tag
title shortTitle description category language tag
Event-Driven Architecture Pattern in Java: Building Responsive and Scalable Java Systems Event-Driven Architecture Discover comprehensive guides on Event-Driven Architecture patterns with practical Java examples. Learn to implement effective event-driven systems in your projects. Architectural en
Asynchronous
Decoupling
Enterprise patterns
Event-driven
Messaging
Publish/subscribe
Reactive
Scalability

Also known as

  • Event-Driven System
  • Event-Based Architecture

Intent of Event-Driven Architecture Design Pattern

Event-Driven Architecture (EDA) is designed to orchestrate behavior around the production, detection, consumption of, and reaction to events. This architecture enables highly decoupled, scalable, and dynamic interconnections between event producers and consumers.

Detailed Explanation of Event-Driven Architecture Pattern with Real-World Examples

Real-world example

A real-world example of the Event-Driven Architecture (EDA) pattern is the operation of an air traffic control system. In this system, events such as aircraft entering airspace, changes in weather conditions, and ground vehicle movements trigger specific responses like altering flight paths, scheduling gate assignments, and updating runway usage. This setup allows for highly efficient, responsive, and safe management of airport operations, reflecting EDA's core principles of asynchronous communication and dynamic event handling.

In plain words

Event-Driven Architecture is a design pattern where system behavior is dictated by the occurrence of specific events, allowing for dynamic, efficient, and decoupled responses.

Wikipedia says

Event-driven architecture (EDA) is a software architecture paradigm concerning the production and detection of events.

Programmatic Example of Event-Driven Architecture in Java

The Event-Driven Architecture (EDA) pattern in this module is implemented using several key classes and concepts:

  • Event: This is an abstract class that represents an event. It's the base class for all types of events that can occur in the system.
  • UserCreatedEvent and UserUpdatedEvent: These are concrete classes that extend the Event class. They represent specific types of events that can occur in the system, namely the creation and updating of a user.
  • EventDispatcher: This class is responsible for dispatching events to their respective handlers. It maintains a mapping of event types to handlers.
  • UserCreatedEventHandler and UserUpdatedEventHandler: These are the handler classes for the UserCreatedEvent and UserUpdatedEvent respectively. They contain the logic to execute when these events occur.

First, we'll define the Event abstract class and the concrete event classes UserCreatedEvent and UserUpdatedEvent.

public abstract class Event {
  // Event related properties and methods
}
public class UserCreatedEvent extends Event {
  private User user;

  public UserCreatedEvent(User user) {
    this.user = user;
  }

  public User getUser() {
    return user;
  }
}
public class UserUpdatedEvent extends Event {
  private User user;

  public UserUpdatedEvent(User user) {
    this.user = user;
  }

  public User getUser() {
    return user;
  }
}

Next, we'll define the event handlers UserCreatedEventHandler and UserUpdatedEventHandler.

public class UserCreatedEventHandler {
  public void onUserCreated(UserCreatedEvent event) {
    // Logic to execute when a UserCreatedEvent occurs
  }
}
public class UserUpdatedEventHandler {
  public void onUserUpdated(UserUpdatedEvent event) {
    // Logic to execute when a UserUpdatedEvent occurs
  }
}

Then, we'll define the EventDispatcher class that is responsible for dispatching events to their respective handlers.

public class EventDispatcher {
  private Map<Class<? extends Event>, List<Consumer<Event>>> handlers = new HashMap<>();

  public <E extends Event> void registerHandler(Class<E> eventType, Consumer<E> handler) {
    handlers.computeIfAbsent(eventType, k -> new ArrayList<>()).add(handler::accept);
  }

  public void dispatch(Event event) {
    List<Consumer<Event>> eventHandlers = handlers.get(event.getClass());
    if (eventHandlers != null) {
      eventHandlers.forEach(handler -> handler.accept(event));
    }
  }
}

Finally, we'll demonstrate how to use these classes in the main application.

public class App {
  public static void main(String[] args) {
    // Create an EventDispatcher
    EventDispatcher dispatcher = new EventDispatcher();

    // Register handlers for UserCreatedEvent and UserUpdatedEvent
    dispatcher.registerHandler(UserCreatedEvent.class, new UserCreatedEventHandler()::onUserCreated);
    dispatcher.registerHandler(UserUpdatedEvent.class, new UserUpdatedEventHandler()::onUserUpdated);

    // Create a User
    User user = new User("iluwatar");

    // Dispatch UserCreatedEvent
    dispatcher.dispatch(new UserCreatedEvent(user));

    // Dispatch UserUpdatedEvent
    dispatcher.dispatch(new UserUpdatedEvent(user));
  }
}

Running the example produces the following console output:

22:15:19.997 [main] INFO com.iluwatar.eda.handler.UserCreatedEventHandler -- User 'iluwatar' has been Created!
22:15:20.000 [main] INFO com.iluwatar.eda.handler.UserUpdatedEventHandler -- User 'iluwatar' has been Updated!

This example demonstrates the Event-Driven Architecture pattern, where the occurrence of events drives the flow of the program. The system is designed to respond to events as they occur, which allows for a high degree of flexibility and decoupling between components.

Detailed Explanation of Event-Driven Architecture Pattern with Real-World Examples

Event-Driven Architecture

When to Use the Event-Driven Architecture Pattern in Java

Use an Event-driven architecture when

  • Systems where change detection is crucial.
  • Applications that require real-time features and reactive systems.
  • Systems needing to efficiently handle high throughput and sporadic loads.
  • When integrating with microservices to enhance agility and scalability.

Real-World Applications of Event-Driven Architecture Pattern in Java

  • Real-time data processing applications.
  • Complex event processing systems in finance, such as stock trading platforms.
  • IoT systems for dynamic device and information management.
  • Chargify, a billing API, exposes payment activity through various events (https://docs.chargify.com/api-events)
  • Amazon's AWS Lambda, lets you execute code in response to events such as changes to Amazon S3 buckets, updates to an Amazon DynamoDB table, or custom events generated by your applications or devices. (https://aws.amazon.com/lambda)
  • MySQL runs triggers based on events such as inserts and update events happening on database tables.

Benefits and Trade-offs of Event-Driven Architecture Pattern

Benefits:

  • Scalability: Efficiently processes fluctuating loads with asynchronous processing.
  • Flexibility and Agility: New event types and event consumers can be added with minimal impact on existing components.
  • Responsiveness: Improves responsiveness by decoupling event processing and state management.

Trade-offs:

  • Complexity in Tracking: Can be challenging to debug and track due to loose coupling and asynchronous behaviors.
  • Dependency on Messaging Systems: Heavily relies on robust messaging infrastructures.
  • Event Consistency: Requires careful design to handle event ordering and consistency.
  • Microservices Architecture: Often used together with EDA to enhance agility and scalability.
  • Publish/Subscribe: A common pattern used within EDA for messaging between event producers and consumers.

References and Credits