The "Event Bus" pattern is an architectural approach that allows communication between components of a system through the publication and listening of events. The components do not directly know about each other, enabling loosely coupled interaction based on the "publisher-subscriber" principle.
Usage: This pattern is useful where scalable, extensible interaction between multiple modules is required — for example, in complex web applications, desktop systems, or microservices platforms.
Example code in Python using the pyee library:
from pyee import EventEmitter bus = EventEmitter() def on_user_created(user): print(f"User created: {user}") bus.on('user_created', on_user_created) bus.emit('user_created', {"id": 1, "name": "Ivan"})
Key features:
Should all events in the Event Bus be persistent?
No, not necessarily. In most cases, the Event Bus operates on ephemeral events that are not saved. Persistence is only needed if avoiding event loss is crucial (e.g., through Kafka).
Will an event be lost if no subscriber is registered at the time of publication?
Yes, if the system does not save events (ephemeral), the event will be lost. For guaranteed delivery, a durable Event Bus is required (e.g., RabbitMQ with persistent queues).
Can one Event Bus be used for synchronous and asynchronous code without limitations?
No, a synchronous Event Bus can block the thread until all handlers are completed, which is unacceptable under high load. For scalable systems, asynchronous Event Buses are used, or event processing is offloaded to separate processes/threads (e.g., using Celery).