Overview
PriceSignal uses NATS JetStream for reliable, distributed messaging between microservices. TheNatsService provides a robust pub/sub interface with guaranteed delivery and message persistence.
Architecture
Implemented insrc/Infrastructure/PubSub/NatsService.cs, the service implements the IPubSub interface and provides both publishing and subscription capabilities.
Dependencies
Service Configuration
NatsSettings
appsettings.json
Initialization
Publishing Messages
ThePublishAsync method serializes messages to JSON and publishes them to JetStream:
Usage Example
Subscribing to Messages
TheSubscribe method creates a consumer and processes messages:
Usage Example
Stream Configuration
Notifications Stream
Created automatically on service initialization:notifications.*, including:
notifications.telegram- Telegram notificationsnotifications.init.telegram- User registration eventsnotifications.email- Email notifications (future)notifications.webhook- Webhook notifications (future)
Consumer Configuration
Consumers are created with durable names for reliability:Consumer Features
- Durable: Consumer state persists across restarts
- Automatic acknowledgment: Messages are acked after successful processing
- Subject filtering: Optional filtering by subject pattern
Message Serialization
JSON Options
Example Message Format
Cleanup and Disposal
Dependency Injection Setup
Program.cs
Message Flow Patterns
Alert Notifications
- Rule engine triggers alert
- Alert handler publishes to
notifications.telegram - Telegram bot consumes message
- User receives notification
User Registration
- User messages Telegram bot
- Bot publishes to
notifications.init.telegram - .NET service consumes message
- User info saved to database
Error Handling
- Publish failures:
EnsureSuccess()throws if message not acknowledged - Deserialization errors: Null messages are skipped
- Consumer errors: Logged but don’t stop subscription
Performance Features
- Persistent connections: Single connection reused for all operations
- Async/await: Non-blocking message processing
- JetStream: Guaranteed delivery and message persistence
- Subject filtering: Reduces unnecessary message processing
Monitoring
All operations are logged with structured logging:Related Components
- Telegram Bot Service - Go-based consumer of NATS notifications
- Rule Engine - Publishes triggered alerts to NATS
- Price Fetcher Service - May publish price updates to NATS