System ArchitectureBackend Architect

Describe the "Event Bus" pattern, where to apply it, and what pitfalls to consider?

Pass interviews with Hintsage AI assistant

Answer.

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:

  • Increases modularity as services communicate through the bus rather than directly
  • Simplifies adding new event handlers without changing the existing code
  • Can lead to hard-to-trace errors due to implicit dependencies and complicating tracking of business flows

Tricky Questions.

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).