A production-ready NestJS microservice implementing Domain-Driven Design (DDD) and SOLID principles for scalable email processing with Redis-powered queue management.
This microservice provides a robust, enterprise-grade solution for email processing with:
- Domain-Driven Design architecture for maintainable business logic
- SOLID Principles implementation for clean, testable code
- Queue-based Processing with BullMQ and Redis for reliability
- SendGrid Integration for professional email delivery
- Docker Support with AWS ECS deployment ready
- Type Safety with full TypeScript coverage
- Framework: NestJS v11.0.1
- Language: TypeScript v5.7.3
- Queue Management: BullMQ v5.59.0 + Redis v7
- Email Service: SendGrid v8.1.6
- Validation: class-validator + class-transformer
- Testing: Jest v30.0.0
- Container: Docker (multi-stage Alpine-based)
- Cloud: AWS ECS ready with health checks
This application follows Domain-Driven Design principles with clear separation of concerns:
- Email Entity: Core business logic for email management
- Value Objects: EmailAddress, EmailContent with validation
- Repository Interface: Abstract email storage contract
- Use Cases: SendEmailUseCase, QueueEmailUseCase
- Service Interfaces: EmailDeliveryService interface
- SendGrid Integration: Email delivery implementation
- Repository Implementation: In-memory email storage
- Controllers: Domain-driven email endpoints
- DTOs: Request/response validation
- β Domain-Driven Design Architecture
- β Queue-based Email Processing with BullMQ
- β SendGrid Integration for reliable email delivery
- β Email Counter tracking sent emails
- β Request Validation with class-validator
- β Redis Queue Management
- Node.js (v18 or higher)
- Docker (for Redis)
- SendGrid API Key (see SENDGRID-SETUP.md)
- Environment Configuration: Copy
.env.exampleto.envand configure your credentials
Important: Don't forget to copy
.env.exampleto.envand add your SendGrid API key before starting the application!
Create a docker-compose.yml file in your project root:
version: '3.8'
services:
redis:
image: redis:7-alpine
container_name: nest-worker-redis
ports:
- "6379:6379"
volumes:
- redis_data:/data
command: redis-server --appendonly yes
restart: unless-stopped
redis-insight:
image: redis/redisinsight:latest
container_name: nest-worker-redis-insight
ports:
- "5540:5540"
environment:
- REDIS_HOSTS=local:redis:6379
depends_on:
- redis
restart: unless-stopped
volumes:
redis_data:** Note**: These Docker services are for Redis only. You still need to configure your
.envfile for the NestJS application (see Prerequisites section above).
# Start Redis and Redis Insight
docker-compose up -d
# Check if services are running
docker-compose ps
# View logs
docker-compose logs redis
docker-compose logs redis-insightIf you prefer to run only Redis:
# Pull and run Redis
docker run -d \
--name nest-worker-redis \
-p 6379:6379 \
-v redis_data:/data \
redis:7-alpine redis-server --appendonly yes
# Check Redis is running
docker ps | grep redisWeb-based Redis GUI with advanced features:
-
Access: http://localhost:5540
-
Features:
- Real-time monitoring
- Queue visualization for BullMQ
- Memory analysis
- Key-value browser
- Query profiler
-
Connect to Redis:
- Host:
redis(if using docker-compose) orlocalhost - Port:
6379 - No password required for development
- Host:
docker run -d \
--name redis-commander \
-p 8081:8081 \
-e REDIS_HOSTS=local:redis:6379 \
rediscommander/redis-commander:latestAccess: http://localhost:8081
- Download from official websites
- Connect to
localhost:6379
Use the included redis-dev.sh script for easy Redis management:
# Start all Redis services
./redis-dev.sh start
# Check service status
./redis-dev.sh status
# Monitor queue activity
./redis-dev.sh queue-status
# Connect to Redis CLI
./redis-dev.sh cli
# Open Redis Insight in browser
./redis-dev.sh insight
# View all available commands
./redis-dev.sh help# Connect to Redis
docker exec -it nest-worker-redis redis-cli
# Monitor Redis operations
docker exec -it nest-worker-redis redis-cli monitor
# Check Redis info
docker exec -it nest-worker-redis redis-cli info
# List all keys
docker exec -it nest-worker-redis redis-cli keys "*"
# BullMQ specific commands
docker exec -it nest-worker-redis redis-cli keys "bull:email-queue:*"# List queue jobs
LLEN bull:email-queue:waiting
LLEN bull:email-queue:active
LLEN bull:email-queue:completed
LLEN bull:email-queue:failed
# View job data
LRANGE bull:email-queue:waiting 0 -1
LRANGE bull:email-queue:completed 0 10
# Clear all jobs (be careful!)
FLUSHALL** Note**: The current BullMQ configuration uses
defaultJobOptions.removeOnComplete = falsespecifically for visualization purposes in Redis Insight and other monitoring tools. This allows you to see completed jobs in the Redis interface for debugging and monitoring.** Next Update**: In the next version, completed job data will be saved to a database for permanent storage and analytics, allowing us to set
removeOnComplete = truefor better Redis memory management.
$ npm install# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prodGET /health
curl http://localhost:3000/healthResponse:
{
"status": "ok",
"timestamp": "2025-12-06T...",
"service": "NestJS Email Worker",
"version": "0.0.1"
}POST /email/send
curl -X POST http://localhost:3000/email/send \
-H "Content-Type: application/json" \
-d '{
"from": "your-email@example.com",
"to": "recipient@example.com",
"subject": "Hello from NestJS DDD",
"textContent": "This is a test email from our domain-driven architecture!",
"htmlContent": "<h1>Hello!</h1><p>This is a test email from our domain-driven architecture!</p>"
}'GET /email/stats
curl http://localhost:3000/email/statsResponse:
{
"totalEmailsSent": 42,
"timestamp": "2025-12-06T...",
"service": "Domain-Driven Email Service"
}GET /queue/status
curl http://localhost:3000/queue/statusUse the included test script:
./test-queue-email.shThis project strictly follows SOLID principles for maintainable, testable code:
- Helpers:
IdGeneratorandEmailValidatorhandle specific utilities - Use Cases: Each use case has one clear responsibility
- Value Objects: EmailAddress and EmailContent manage their own validation
- Domain Exceptions: Extensible hierarchy for new exception types
- Repository Pattern: Easy to add new storage implementations
- Configuration Service: Open for extension without modifying core logic
- Repository Interfaces: All implementations are interchangeable
- Service Interfaces: Consistent contracts across implementations
- Segregated Repositories:
EmailWriteRepositoryandEmailQueryRepository - Focused Interfaces: Clients depend only on methods they use
- Configuration Interfaces: Specific interfaces for email and app config
- Abstraction-based Dependencies: All services depend on interfaces
- Dependency Injection: NestJS IoC container manages all dependencies
- Configuration Abstraction: Environment access through
ConfigurationService
- Clean Architecture: Clear separation between domain, application, infrastructure, and presentation layers
- Testability: Easily mockable dependencies and isolated business logic
- Maintainability: Changes to external services don't affect business logic
- Scalability: Queue-based processing with Redis and BullMQ
- Type Safety: Full TypeScript coverage with strict validation
- SOLID Compliance: Professional code quality following industry best practices
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov# Clone the repository
git clone <your-repo>
cd nest-worker
# Run automated setup script (handles dependencies, .env, and Redis)
./setup.sh** The setup script automatically copies
.env.exampleto.envfor you!**
-
Clone and Install:
git clone <your-repo> cd nest-worker npm install
-
Setup Redis with Docker:
./redis-dev.sh start
-
Configure Environment ( Required):
cp .env.example .env # Edit .env with your SendGrid credentialsNote: The application will not work without proper environment configuration!
-
Start Development Server:
npm run start:dev
-
Monitor with Redis Insight:
- Open http://localhost:5540
- Connect to Redis at
localhost:6379
-
Check Queue Status:
./redis-dev.sh queue-status curl http://localhost:3000/queue/status
-
Monitor Queue Activity:
./redis-dev.sh monitor
-
Send Test Email:
./test-queue-email.sh
-
View in Redis Insight:
- Go to Browser tab
- Look for keys starting with
bull:email-queue:
- Use Redis Cluster for high availability
- Configure Redis password authentication
- Set up proper monitoring and alerting
- Use Redis persistence (RDB + AOF)
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the deployment documentation for more information.
If you are looking for a cloud-based platform to deploy your NestJS application, check out Mau, our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
$ npm install -g @nestjs/mau
$ mau deployWith Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
Check out a few resources that may come in handy when working with NestJS:
- Visit the NestJS Documentation to learn more about the framework.
- For questions and support, please visit our Discord channel.
- To dive deeper and get more hands-on experience, check out our official video courses.
- Deploy your application to AWS with the help of NestJS Mau in just a few clicks.
- Visualize your application graph and interact with the NestJS application in real-time using NestJS Devtools.
- Need help with your project (part-time to full-time)? Check out our official enterprise support.
- To stay in the loop and get updates, follow us on X and LinkedIn.
- Looking for a job, or have a job to offer? Check out our official Jobs board.
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please read more here.
- Author - Kamil MyΕliwiec
- Website - https://nestjs.com
- Twitter - @nestframework
Nest is MIT licensed.