The transactional outbox pattern implemented in the eShop project ensures reliable message delivery and eventual consistency between services. Here's a detailed overview of the entire flow, based on the provided files:
1. Overview of the Transactional Outbox Pattern
The transactional outbox pattern ensures that messages (Integration Events) are recorded in a database (outbox table) as part of the same transaction as the business logic operation. Once the transaction is committed, a background process or service publishes these events to a message broker (e.g., RabbitMQ). This approach ensures atomicity between database changes and event publishing, avoiding inconsistencies caused by partial failures.
2. Components in the eShop Implementation
The pattern is implemented across multiple layers and components in the eShop project. Here's how they interact:
A. Database Outbox Table
- Files:
- [Redacted InternationalBankingAccountNumber]_Outbox.cs` (Catalog.API)
- [Redacted InternationalBankingAccountNumber]_Outbox.cs` (Ordering.Infrastructure)
The outbox table, named IntegrationEventLog, is created in the database using EF Core migrations. It stores events to be published. The schema varies slightly between services (e.g., ordering.IntegrationEventLog in Ordering service).
Structure of the IntegrationEventLog Table:
- Columns:
EventId: Unique identifier for the event.
EventTypeName: Fully qualified name of the event type (used for deserialization).
State: Current state of the event (NotPublished, InProgress, Published, or PublishedFailed).
TimesSent: Number of attempts to publish the event.
CreationTime: Timestamp when the event was created.
Content: Serialized JSON content of the event.
TransactionId: Identifier of the transaction in which the event was created.
B. Integration Event and Log Entry
- Files:
IntegrationEventLogEntry.cs
IntegrationEvent (not provided directly, but referenced in the code)
The IntegrationEventLogEntry class represents an entry in the IntegrationEventLog table. It serializes and deserializes events using System.Text.Json. Some key methods and properties include:
IntegrationEventLogEntry(IntegrationEvent @event, Guid transactionId): Constructor that initializes a log entry with the event's data and the transaction ID.
DeserializeJsonContent(Type type): Deserializes the event's JSON content back into its original object.
C. Integration Event Log Service
- File:
IntegrationEventLogService.cs
This service provides methods to manage the lifecycle of integration events in the outbox table:
- SaveEventAsync: Adds a new event to the outbox table as part of the current database transaction.
- RetrieveEventLogsPendingToPublishAsync: Fetches events in the
NotPublished state for a specific transaction.
- MarkEventAsInProgressAsync: Marks an event as being processed (state =
InProgress).
- MarkEventAsPublishedAsync: Marks an event as successfully published (state =
Published).
- MarkEventAsFailedAsync: Marks an event as failed to publish (state =
PublishedFailed).
D. Service-Specific Integration Event Services
CatalogIntegrationEventService
- File:
CatalogIntegrationEventService.cs
- Responsibilities:
- SaveEventAndCatalogContextChangesAsync:
- Saves database changes in the
CatalogContext along with the integration event in the outbox table.
- Uses a resilient transaction to ensure atomicity.
- PublishThroughEventBusAsync:
- Publishes the event to the message broker (RabbitMQ) via the
IEventBus.
- Updates the event's state in the outbox table (e.g.,
InProgress, Published, or PublishedFailed).
OrderingIntegrationEventService
- File:
OrderingIntegrationEventService.cs
- Responsibilities:
- AddAndSaveEventAsync:
- Saves an integration event in the outbox table as part of the
OrderingContext transaction.
- PublishEventsThroughEventBusAsync:
- Retrieves all pending events for a specific transaction.
- Publishes each event to RabbitMQ.
- Updates the event's state in the outbox table (e.g.,
InProgress, Published, PublishedFailed).
E. Event Bus
Interface
- File:
IEventBus.cs
- Defines a method
PublishAsync(IntegrationEvent @event) for publishing events.
RabbitMQ Implementation
- File:
RabbitMQEventBus.cs
- Responsibilities:
- Publishes events to a RabbitMQ exchange using a
direct exchange type.
- Serializes events into JSON format before sending.
- Uses OpenTelemetry for tracing and logging.
- Handles retries using Polly for transient failures (e.g., network issues).
3. Transactional Flow
Here’s the complete flow of the transactional outbox pattern in this project:
A. Save Event and Business Logic Changes
- A service (e.g.,
CatalogIntegrationEventService or OrderingIntegrationEventService) initiates a business operation.
- The business operation makes changes to the database (e.g., updating a catalog or placing an order).
- The service creates an
IntegrationEvent and saves it to the IntegrationEventLog table using SaveEventAsync from IntegrationEventLogService. This happens within the same database transaction as the business logic.
- The transaction is committed, ensuring atomicity of the business operation and the event recording.
B. Publish Events
- A background process or explicitly called method retrieves pending events from the
IntegrationEventLog table using RetrieveEventLogsPendingToPublishAsync.
- Each pending event is marked as
InProgress before publishing to avoid duplicate processing.
- The event is published to RabbitMQ via
RabbitMQEventBus.
- On successful publication, the event is marked as
Published. If publishing fails, it is marked as PublishedFailed.
C. Retry Logic
- Events in the
PublishedFailed state can be retried later. The TimesSent column tracks how many times an event has been attempted to publish.
4. Example Scenarios
Catalog Service Workflow
- A product is updated in the
CatalogContext.
- The
CatalogIntegrationEventService adds a corresponding ProductPriceChangedIntegrationEvent to the outbox table.
- The transaction is committed, ensuring both the update and the event are saved.
- Later,
PublishThroughEventBusAsync publishes the event to RabbitMQ and marks it as Published.
Ordering Service Workflow
- An order is placed in the
OrderingContext.
- The
OrderingIntegrationEventService adds an OrderStartedIntegrationEvent to the outbox table.
- A background job retrieves the event and publishes it to RabbitMQ.
- If publishing fails, the event remains in
PublishedFailed state for retry.
5. Benefits
- Atomicity: Ensures that the database operation and event recording happen together.
- Reliability: Events are retried if publishing fails.
- Traceability: State transitions (
NotPublished, InProgress, Published, etc.) provide clear visibility into the event lifecycle.
6. Summary
The eShop project implements the transactional outbox pattern using:
- Outbox table (
IntegrationEventLog) for storing events.
IntegrationEventLogService for managing event state.
- Service-specific integration event services for saving and publishing events.
- RabbitMQ for event delivery.
- OpenTelemetry for tracing and Polly for retry logic.
This ensures data consistency and reliable event delivery across microservices.