Overview
MassTransit is a free, open-source distributed application framework for .NET. It provides an abstraction over message brokers like RabbitMQ, making it easier to implement event-driven architectures.Architecture
BuildingBlocks.Messaging Project
The shared messaging library provides common infrastructure for all services.Project Structure
Extension Method Implementation
InBuildingBlocks.Messaging/MassTransit/Extentions.cs:
Service Configuration
Publisher Configuration (Basket.API)
No consumer assembly - only publishes events:Consumer Configuration (Ordering.API)
With consumer assembly - consumes events:Naming Conventions
MassTransit uses kebab-case naming by default:| C# Type | Exchange Name | Queue Name |
|---|---|---|
BasketCheckoutEvent | basket-checkout-event | {service}-basket-checkout-event |
OrderCreatedEvent | order-created-event | {service}-order-created-event |
PaymentProcessedEvent | payment-processed-event | {service}-payment-processed-event |
Queue Naming Pattern
- Service:
Ordering - Event:
BasketCheckoutEvent - Queue:
ordering-basket-checkout-event
Message Publishing
Using IPublishEndpoint
InjectIPublishEndpoint into your handler:
Publishing with Headers
Message Consumption
Implementing IConsumer
Accessing Context Information
Advanced Configuration
Retry Policy
Circuit Breaker
Rate Limiting
Message Persistence
Consumer Configuration
Custom Queue Configuration
Consumer Definition
For more control, create a consumer definition:Monitoring and Observability
Built-in Health Checks
OpenTelemetry Integration
Logging
MassTransit automatically logs:- Message publishing
- Message consumption
- Retries and failures
- Performance metrics
Testing
In-Memory Test Harness
Best Practices
Use Shared Events Library
Use Shared Events Library
Idempotent Consumers
Idempotent Consumers
Always design consumers to be idempotent. A message may be delivered multiple times.
Use Correlation IDs
Use Correlation IDs
Track events across services using correlation IDs for distributed tracing.
Handle Poison Messages
Handle Poison Messages
Configure error queues and monitor them. Implement logic to handle messages that repeatedly fail.
Version Events
Version Events
Plan for event versioning from the start:
Common Patterns
Saga Pattern
For complex workflows spanning multiple services:Request/Response Pattern
Troubleshooting
Performance Tuning
Prefetch Count
Controls how many messages are fetched from RabbitMQ at once:Concurrent Message Limit
Controls how many messages are processed concurrently:Example Configuration
Next Steps
RabbitMQ Deep Dive
Explore RabbitMQ event flow and patterns
gRPC Communication
Learn about synchronous service calls
