|
| 1 | +# Event bus |
| 2 | + |
| 3 | +This document explains how the EventBus provides cross-instance communication for services that need to react to changes |
| 4 | +happening on other instances. If you've wondered how cache invalidation works across multiple backend replicas, this is |
| 5 | +where that question gets answered. |
| 6 | + |
| 7 | +## The problem |
| 8 | + |
| 9 | +When running multiple instances of the backend (horizontal scaling), each instance has its own in-memory cache. When |
| 10 | +Instance A updates a user's settings, Instance B's cache becomes stale. Without coordination, Instance B would return |
| 11 | +outdated data until its cache TTL expires. |
| 12 | + |
| 13 | +```mermaid |
| 14 | +graph LR |
| 15 | + subgraph "Instance A" |
| 16 | + A1[Update settings] --> A2[Update local cache] |
| 17 | + end |
| 18 | +
|
| 19 | + subgraph "Instance B" |
| 20 | + B1[Stale cache] --> B2[Returns old data] |
| 21 | + end |
| 22 | +
|
| 23 | + A2 -.->|"No communication"| B1 |
| 24 | +``` |
| 25 | + |
| 26 | +The EventBus solves this by providing a Kafka-backed pub/sub mechanism for cross-instance events. |
| 27 | + |
| 28 | +## Architecture |
| 29 | + |
| 30 | +The EventBus uses Kafka as a message broker. When a service publishes an event, it goes to Kafka. Each instance has a |
| 31 | +Kafka listener that receives events from other instances and distributes them to local subscribers. |
| 32 | + |
| 33 | +```mermaid |
| 34 | +graph TB |
| 35 | + subgraph "Instance A" |
| 36 | + PA[Publisher] --> KP[Kafka Producer] |
| 37 | + KCA[Kafka Consumer] --> HA[Local Handlers] |
| 38 | + end |
| 39 | +
|
| 40 | + subgraph "Kafka" |
| 41 | + T[event-bus-stream topic] |
| 42 | + end |
| 43 | +
|
| 44 | + subgraph "Instance B" |
| 45 | + PB[Publisher] --> KPB[Kafka Producer] |
| 46 | + KCB[Kafka Consumer] --> HB[Local Handlers] |
| 47 | + end |
| 48 | +
|
| 49 | + KP --> T |
| 50 | + KPB --> T |
| 51 | + T --> KCA |
| 52 | + T --> KCB |
| 53 | +``` |
| 54 | + |
| 55 | +The key insight is that publishers handle their own state changes directly. They don't need to receive their own events |
| 56 | +back from Kafka. The EventBus filters out self-published messages so handlers only run for events from other instances. |
| 57 | + |
| 58 | +## Self-filtering mechanism |
| 59 | + |
| 60 | +Each EventBus instance has a unique ID. When publishing to Kafka, this ID is included as a message header: |
| 61 | + |
| 62 | +```python |
| 63 | +headers = [("source_instance", self._instance_id.encode("utf-8"))] |
| 64 | +await self.producer.send_and_wait(topic=self._topic, value=value, headers=headers) |
| 65 | +``` |
| 66 | + |
| 67 | +The Kafka listener checks this header and skips messages from itself: |
| 68 | + |
| 69 | +```python |
| 70 | +headers = dict(msg.headers) if msg.headers else {} |
| 71 | +source = headers.get("source_instance", b"").decode("utf-8") |
| 72 | +if source == self._instance_id: |
| 73 | + continue # Skip self-published messages |
| 74 | +``` |
| 75 | + |
| 76 | +This design means: |
| 77 | + |
| 78 | +1. Publishers update their own state before calling `publish()` |
| 79 | +2. The `publish()` call tells other instances about the change |
| 80 | +3. Handlers only run for events from other instances |
| 81 | + |
| 82 | +## Usage pattern |
| 83 | + |
| 84 | +Services that need cross-instance communication follow this pattern: |
| 85 | + |
| 86 | +```python |
| 87 | +class MyService: |
| 88 | + async def initialize(self, event_bus_manager: EventBusManager) -> None: |
| 89 | + bus = await event_bus_manager.get_event_bus() |
| 90 | + |
| 91 | + async def _handle(evt: EventBusEvent) -> None: |
| 92 | + # This only runs for events from OTHER instances |
| 93 | + await self.invalidate_cache(evt.payload["id"]) |
| 94 | + |
| 95 | + await bus.subscribe("my.event.*", _handle) |
| 96 | + |
| 97 | + async def update_something(self, id: str, data: dict) -> None: |
| 98 | + # 1. Update local state |
| 99 | + self._cache[id] = data |
| 100 | + |
| 101 | + # 2. Notify other instances |
| 102 | + bus = await self._event_bus_manager.get_event_bus() |
| 103 | + await bus.publish("my.event.updated", {"id": id}) |
| 104 | +``` |
| 105 | + |
| 106 | +## Pattern matching |
| 107 | + |
| 108 | +Subscriptions support wildcard patterns using `fnmatch` syntax: |
| 109 | + |
| 110 | +| Pattern | Matches | |
| 111 | +|--------------------------|----------------------------------| |
| 112 | +| `execution.*` | All execution events | |
| 113 | +| `execution.123.*` | All events for execution 123 | |
| 114 | +| `*.completed` | All completed events | |
| 115 | +| `user.settings.updated*` | Settings updates with any suffix | |
| 116 | + |
| 117 | +## Flow diagram |
| 118 | + |
| 119 | +Here's what happens when Instance A updates user settings: |
| 120 | + |
| 121 | +```mermaid |
| 122 | +sequenceDiagram |
| 123 | + participant API as Instance A |
| 124 | + participant Cache as Local Cache A |
| 125 | + participant Kafka |
| 126 | + participant ListenerB as Instance B Listener |
| 127 | + participant CacheB as Local Cache B |
| 128 | +
|
| 129 | + API->>Cache: _add_to_cache(user_id, settings) |
| 130 | + API->>Kafka: publish("user.settings.updated", {user_id}) |
| 131 | + Note over Kafka: Message includes source_instance header |
| 132 | +
|
| 133 | + Kafka->>API: Listener receives message |
| 134 | + API->>API: source == self, SKIP |
| 135 | +
|
| 136 | + Kafka->>ListenerB: Listener receives message |
| 137 | + ListenerB->>ListenerB: source != self, PROCESS |
| 138 | + ListenerB->>CacheB: invalidate_cache(user_id) |
| 139 | +``` |
| 140 | + |
| 141 | +## EventBusManager |
| 142 | + |
| 143 | +The `EventBusManager` provides singleton access to the EventBus with proper lifecycle management: |
| 144 | + |
| 145 | +```python |
| 146 | +async def get_event_bus(self) -> EventBus: |
| 147 | + async with self._lock: |
| 148 | + if self._event_bus is None: |
| 149 | + self._event_bus = EventBus(self.settings, self.logger) |
| 150 | + await self._event_bus.__aenter__() |
| 151 | + return self._event_bus |
| 152 | +``` |
| 153 | + |
| 154 | +Services receive the manager via dependency injection and call `get_event_bus()` when needed. |
| 155 | + |
| 156 | +## Key files |
| 157 | + |
| 158 | +| File | Purpose | |
| 159 | +|------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------| |
| 160 | +| [`services/event_bus.py`](https://github.com/HardMax71/Integr8sCode/blob/main/backend/app/services/event_bus.py) | EventBus and EventBusManager implementation | |
| 161 | +| [`services/user_settings_service.py`](https://github.com/HardMax71/Integr8sCode/blob/main/backend/app/services/user_settings_service.py) | Example usage for cache invalidation | |
| 162 | + |
| 163 | +## Related docs |
| 164 | + |
| 165 | +- [User Settings Events](user-settings-events.md) — event sourcing with cache invalidation via EventBus |
| 166 | +- [Event System Design](event-system-design.md) — domain events vs integration events |
| 167 | +- [Kafka Topics](kafka-topic-architecture.md) — topic naming and partitioning |
0 commit comments