Frequently Asked Questions
Use NestJS with MessageBird's Batch SMS API. Create a NestJS service to interact with the API, define DTOs for validation, and set up a controller endpoint to handle requests. This allows sending multiple messages in a single API call, improving efficiency for large-scale SMS needs.
MessageBird's Batch SMS API lets you send many unique SMS messages to different people with one API request. This is far more efficient than sending individual messages, especially for large volumes, and is ideal for applications needing notifications, alerts, or marketing outreach.
NestJS provides a robust framework with features like dependency injection, modularity, and TypeScript support, making it suitable for building scalable applications. This structure simplifies integrating third-party services like MessageBird and managing complex logic for reliable bulk SMS sending.
Install the required packages, including @nestjs/axios, messagebird, and @nestjs/config, then create a messaging module and service. In the module, use HttpModule.registerAsync with ConfigService to inject your API key and endpoint from environment variables for secure configuration.
Prisma is used as an Object-Relational Mapper (ORM) to simplify database interactions. It makes it easier to log bulk SMS requests, responses, and other relevant data, improving tracking and monitoring capabilities within your NestJS application.
Create a .env file in your project root. Add MESSAGEBIRD_ACCESS_KEY (your API key from the MessageBird dashboard) and MESSAGEBIRD_API_ENDPOINT. The project uses @nestjs/config to load these variables, and it's crucial to add .env to your .gitignore file to prevent exposing your credentials.
The @nestjs/throttler package helps prevent abuse and overload by limiting API requests. In this bulk SMS system, it protects the MessageBird API from excessive calls, ensuring service stability and preventing potential issues due to rate limits.
The endpoint (POST /messages/bulk) expects a JSON object with a "messages" array. Each element in this array represents an individual message with "recipients", "originator", and "body" properties. Validation is handled by DTOs to ensure correct data format and prevent invalid requests.
It's critical to secure this endpoint using API keys, JWT, or other authentication methods. An API key guard is recommended to control access and prevent unauthorized usage of the endpoint in a real-world application.
The MessagingService implements retry logic with exponential backoff for transient errors (5xx status codes). It throws HttpExceptions for both retryable and non-retryable errors. The controller catches these exceptions and returns appropriate error responses to the client.
You'll need Node.js v16+, npm/pnpm/yarn, a MessageBird account and API key, a PostgreSQL database (or other Prisma-supported database), and basic knowledge of NestJS, TypeScript, and REST APIs. The guide provides instructions for setting up the project, dependencies, and configuration.
The BulkMessagesDto validates incoming requests to ensure no more than 100 messages are included per batch request. This limit aligns with typical API constraints and helps manage resource usage and response times.
Use the test API key from your MessageBird dashboard during development to avoid sending real messages and incurring costs. Switch to the live API key for production when you're ready to send actual bulk SMS messages.
The provided code includes a simplified response interface. Refer to the official MessageBird API documentation for the complete response structure and handle different status codes and fields accordingly in your application.
Yes, you can customize the API endpoint by setting the MESSAGEBIRD_API_ENDPOINT environment variable. The default is https://rest.messagebird.com, but you might need to change it if you are using a different MessageBird environment or region.
Build a Bulk SMS Broadcasting System with MessageBird and NestJS
Bulk SMS broadcasting sends promotional campaigns, alerts, or notifications to thousands of recipients efficiently. This guide shows you how to build a production-ready bulk SMS system using MessageBird's SMS API and NestJS.
Common use cases include:
Scale considerations: This architecture handles 1,000–50,000 messages/hour out of the box. For campaigns exceeding 100K recipients or requiring <30 second delivery windows, you'll need horizontal scaling (multiple workers), Redis queue distribution, and potentially MessageBird's enterprise batch endpoints.
Important Note: MessageBird's standard
/messagesAPI endpoint accepts a maximum of 50 recipients per request according to their official documentation. For larger volumes, batch requests on the application side or verify with MessageBird support about enterprise batch endpoints. Always consult the latest MessageBird API documentation for current limits and features.What You'll Build with MessageBird and NestJS
By the end of this tutorial, you'll have a NestJS application that:
Prerequisites for MessageBird NestJS Integration
Skill level: Intermediate (comfortable with TypeScript, REST APIs, and basic database concepts)
Time estimate: 60–90 minutes for initial setup; additional 30–60 minutes for testing and deployment
Before you begin, ensure you have:
Step 1: Set Up Your NestJS Project for MessageBird Integration
Create a new NestJS project:
Install the required dependencies:
Dependency breakdown:
@nestjs/config– Manages environment variables@nestjs/axios– HTTP client module for MessageBird API calls@nestjs/throttler– Rate limiting to prevent API abuse@prisma/clientandprisma– Database ORM for PostgreSQLaxios– HTTP library (peer dependency for @nestjs/axios)Step 2: Configure MessageBird API Environment Variables
Security best practices:
.envto.gitignoreimmediatelymessages:write).envfilesCreate a
.envfile in your project root:Replace
YOUR_API_TOKEN_HEREwith your actual MessageBird API key from the MessageBird Dashboard.Update
src/app.module.tsto load environment variables:Step 3: Set Up Prisma Database Schema for SMS Campaign Tracking
Initialize Prisma:
This command creates a
prismadirectory with aschema.prismafile. Update it to define your SMS campaign and message models:Performance indexes: The schema below includes strategic indexes to optimize common query patterns. Index
campaignIdonSmsMessagefor fast campaign lookups,statusfor filtering by delivery state, andcreatedAtfor time-based queries. Composite index on(campaignId, status)accelerates dashboard queries showing campaign status breakdowns. For high-volume systems (>1M messages), consider partitioning theSmsMessagetable bycreatedAtmonth.Update
prisma/schema.prisma:Schema explanation:
SmsCampaign– Stores campaign metadata, total message count, and success/failure talliesSmsMessage– Tracks individual messages with recipient, status, and MessageBird response datacampaignIdGenerate the Prisma client and run migrations:
Step 4: Create DTOs for MessageBird SMS Request Validation
NestJS uses Data Transfer Objects (DTOs) with class-validator decorators to validate incoming requests.
Create
src/sms/dto/create-bulk-sms.dto.ts:Key validations:
Step 5: Build the MessageBird SMS Service with Retry Logic
Error handling strategies:
The service implements a three-tier error handling approach:
Retriable errors (429 rate limits, 5xx server errors): Automatic retry with exponential backoff (1s → 2s → 4s). These typically resolve within seconds as MessageBird's infrastructure recovers or rate limit windows reset.
Client errors (400 Bad Request, 401 Unauthorized, 403 Forbidden): No retry. Log the error with full context (request payload, response body) and mark message as
failed. These indicate configuration issues (invalid API key, malformed phone numbers) that won't resolve with retries.Network errors (DNS failures, connection timeouts): Retry once after 2 seconds. If still failing, escalate to monitoring alerts as this indicates infrastructure problems.
When to use circuit breakers: For campaigns exceeding 10,000 messages, implement a circuit breaker pattern (using
opossumor similar) to prevent cascading failures. Trip the circuit after 50 consecutive failures and enter half-open state after 30 seconds.Create
src/sms/sms.service.tsto handle MessageBird API interactions, retry logic, and database persistence:Key features:
Step 6: Create the NestJS SMS Controller with Rate Limiting
Create
src/sms/sms.controller.tsto expose REST endpoints:Step 7: Create the Prisma Service Module
Create
src/prisma/prisma.service.ts:Create
src/prisma/prisma.module.ts:Step 8: Wire Up the SMS Module
Create
src/sms/sms.module.ts:Update
src/app.module.ts:Step 9: Test Your MessageBird Bulk SMS Integration
Testing best practices:
SmsCampaignandSmsMessagetables to verify persistenceDebugging common issues:
MESSAGEBIRD_API_KEYis correct and not expired+14155552671)DATABASE_URLand PostgreSQL is runningStart your NestJS application:
Send a test bulk SMS request:
Expected response:
Check campaign status:
Production Considerations for MessageBird SMS at Scale
Scalability Architecture Patterns
Horizontal scaling strategies:
For campaigns exceeding 50,000 messages/hour, implement these patterns:
Worker-based architecture: Deploy multiple NestJS instances behind a load balancer (NGINX, AWS ALB). Use a shared Redis queue (BullMQ) to distribute messages across workers. Each worker processes batches independently, achieving linear scaling (e.g., 10 workers = 500K messages/hour capacity).
Database connection pooling: Configure Prisma with connection pooling to prevent database bottlenecks:
Async processing pattern: Decouple API request acceptance from message sending. Accept requests immediately (return 202 Accepted), queue them in BullMQ/SQS, and process in background workers. This prevents client timeouts and enables retry logic without blocking API responses.
Geographic distribution: For global campaigns, deploy workers in multiple regions (US-East, EU-West, APAC) to reduce latency to MessageBird's regional endpoints. Use GeoDNS or AWS Global Accelerator for routing.
Throughput benchmarks:
1. Environment Variables Security
Store sensitive credentials securely:
.envfiles to version control2. Rate Limiting Strategy
MessageBird enforces API rate limits (500 POST requests/second per official documentation). Implement application-level rate limiting:
For high-volume campaigns, use a queue system (BullMQ, AWS SQS) to throttle requests.
3. Message Queuing for Large Campaigns
Queue system comparison:
Recommendation: Use BullMQ for Node.js projects with <100K messages/hour. Use RabbitMQ for polyglot systems needing advanced routing. Use AWS SQS for serverless or AWS-native architectures.
For campaigns exceeding 10,000 messages, integrate a job queue:
Update
sms.service.tsto queue messages:4. Monitoring and Logging
Critical metrics to monitor:
Monitoring stack setup:
Integrate application performance monitoring (APM):
Add structured logging:
5. Compliance and Consent Management
Implementation details for consent tracking:
GDPR, TCPA, and CASL require verifiable opt-in consent before sending marketing SMS. Implement a consent management system:
Database schema additions:
Compliance requirements by region:
Verification before sending:
Ensure legal compliance:
Store consent timestamps in your database:
6. Cost Optimization
Practical cost calculations:
MessageBird charges per message segment. Here's how pricing works:
Example 1: Standard promotional campaign
Example 2: Unicode message with emoji
Example 3: Long concatenated message
Cost optimization strategies:
bit.ly/promoinstead of full URLs)MessageBird charges per message segment:
Optimize message length:
Display segment count in your API response to help users optimize costs.
Troubleshooting MessageBird NestJS Integration Issues
Diagnostic steps and resolution guide:
1. "Invalid phone number format" Error
Cause: Phone numbers must be in E.164 format (+[country code][number]).
Diagnostic steps:
console.log('Phone number:', phoneNumber)Fix: Validate numbers before sending:
Prevention: Add validation to your DTO or use a pre-processing step to normalize phone numbers on input.
2. Rate Limit 429 Errors
Cause: Exceeding MessageBird's rate limits (500 POST requests/second per official documentation).
Diagnostic steps:
console.log('Requests/sec:', requestCount / timeWindow)Fix: Implement exponential backoff (already included in the service above) or use a queue system to throttle requests.
Advanced solution: Implement token bucket rate limiting in your service:
3. Messages Not Delivering
Possible causes:
Debug steps:
Resolution:
4. Database Connection Issues
Cause: Incorrect
DATABASE_URLin.envfile.Diagnostic steps:
pg_isready -h localhost -p 5432psql "postgresql://username:password@localhost:5432/database_name"GRANT ALL ON DATABASE sms_db TO username;Fix: Verify PostgreSQL connection string format:
Test connection:
Common issues:
?sslmode=requireto connection stringconnect_timeoutparameter in connection stringFrequently Asked Questions (FAQ)
How many recipients can I send to in a single MessageBird API request?
MessageBird's standard
/messagesendpoint accepts a maximum of 50 recipients per request according to their official documentation. For campaigns exceeding 50 recipients, batch requests on the application side (as demonstrated in this tutorial) or contact MessageBird support about enterprise batch endpoints. The code example above automatically handles batching by looping through messages.What is MessageBird's rate limit for SMS API requests?
MessageBird enforces a rate limit of 500 POST requests per second for SMS messaging according to their official documentation. The NestJS service in this tutorial includes exponential backoff retry logic to handle 429 (rate limit) errors automatically. For high-volume campaigns, implement a queue system like BullMQ to throttle requests and stay within limits.
How do I handle MessageBird API failures and retry logic in NestJS?
The tutorial's
SmsServiceincludes asendWithRetry()method with exponential backoff. It automatically retries failed requests up to 3 times with increasing delays (1s, 2s, 4s). The service retries on 429 (rate limit) and 5xx (server error) status codes. All failed messages log to the database with error details for monitoring.What database schema do I need for MessageBird bulk SMS campaigns?
The Prisma schema includes two models:
SmsCampaign(stores campaign metadata, success/failure counts) andSmsMessage(tracks individual messages with recipient, status, and MessageBird response data). This schema enables campaign tracking, delivery reports, and historical analytics. Runnpx prisma migrate devto create the tables.How do I validate phone numbers for MessageBird SMS API?
MessageBird requires phone numbers in E.164 format (e.g., +14155552671). The tutorial uses class-validator with a regex pattern
/^\+[1-9]\d{1,14}$/to validate E.164 format. For production, consider usinglibphonenumber-jslibrary for more robust validation including country code verification and number type detection.Can I send Unicode (emoji) messages through MessageBird?
Yes, MessageBird supports Unicode messages using UCS-2 encoding. However, Unicode messages have a reduced character limit of 70 characters per segment (vs. 160 for GSM-7). The tutorial's DTO allows up to 1,600 characters (10 concatenated segments). Calculate costs carefully – Unicode messages consume more segments and cost more.
How do I implement MessageBird delivery status webhooks in NestJS?
Complete webhook implementation:
MessageBird can send delivery status updates (delivered, failed, expired) via webhooks. Here's a production-ready implementation:
1. Add webhook endpoint to your controller:
2. Add status update method to service:
3. Configure webhook in MessageBird Dashboard:
Navigate to MessageBird Dashboard → Developers → Webhooks → Add Webhook:
https://yourdomain.com/sms/webhook/status4. Secure webhook endpoint:
For complete details, see the MessageBird NestJS Delivery Status Webhooks guide.
What NestJS modules do I need for MessageBird SMS integration?
The core dependencies are:
@nestjs/config(environment variables),@nestjs/axios(HTTP client for MessageBird API),@nestjs/throttler(rate limiting),@prisma/client(database ORM), andaxios(HTTP library). Install withnpm install @nestjs/config @nestjs/axios @nestjs/throttler @prisma/client axios. Additionally, installprismaas a dev dependency for schema management.Next Steps: Enhance Your MessageBird NestJS SMS System
Detailed enhancement roadmap:
Implementation priorities:
Phase 1 (Week 1): Unsubscribe management + Delivery webhooks – Ensures compliance and visibility Phase 2 (Week 2-3): Scheduled campaigns + Template system – Improves operational efficiency Phase 3 (Month 2): A/B testing + Multi-channel support – Drives engagement and ROI
Now that you have a working bulk SMS system, consider these enhancements:
Additional Resources
Related Guides: