Events
Medusa’s event system enables loose coupling between modules through asynchronous event-driven communication. The Event Bus distributes events to subscribers, allowing you to react to domain events without tight dependencies.Event Bus
The Event Bus is responsible for:- Publishing events - Emit events from services and workflows
- Routing events - Deliver events to registered subscribers
- Queuing - Handle event delivery asynchronously
- Grouping - Batch events within transactions
Medusa provides two Event Bus implementations:
event-bus-local for development and event-bus-redis for production with distributed workers.Event Bus Service
The Event Bus service manages event distribution:packages/modules/event-bus-local/src/services/event-bus-local.ts:24-79
Emitting Events
From Services with @EmitEvents
The@EmitEvents decorator automatically emits events after service methods:
packages/modules/api-key/src/services/api-key-module-service.ts:123-133
Events are automatically named: {entityName}.{operation}
apiKey.createdproduct.updatedorder.deleted
From Workflows with createHook
Workflows emit events using hooks:packages/core/core-flows/src/api-key/workflows/create-api-keys.ts:51-64
Manual Event Emission
Emit events manually using the event bus:Emit Multiple Events
Emit multiple events at once:Event Subscribers
Subscribers listen for events and execute logic in response.Creating a Subscriber
Create a subscriber insrc/subscribers/:
Subscriber Configuration
Theconfig export defines subscriber metadata:
Multiple Events
Subscribe to multiple events:Wildcard Subscribers
Subscribe to all events:Event Data Structure
Events follow a consistent structure:Service Event Data
Service events include entity IDs:Workflow Hook Data
Workflow hooks include custom data:Event Grouping
Group events within transactions to emit them together:Delayed Events
Emit events with a delay:Common Event Patterns
Audit Logging
Send Notifications
Update Search Index
Sync to External System
Event Bus Providers
Local Event Bus
For development and single-server deployments:Redis Event Bus
For production with distributed workers:Best Practices
1
Keep Subscribers Idempotent
Subscribers may be called multiple times for the same event. Design them to handle duplicate calls gracefully.
2
Handle Failures
Wrap subscriber logic in try-catch blocks to prevent one subscriber from blocking others.
3
Avoid Long-Running Operations
Subscribers should be fast. Offload heavy work to background jobs or async workflows.
4
Use Typed Event Data
Define TypeScript types for event payloads to catch errors at compile time.
Subscribers run asynchronously and don’t block the main execution flow. They’re perfect for side effects like notifications, logging, and syncing.
Next Steps
Workflows
Emit events from workflow hooks
Services
Emit events automatically with @EmitEvents