Build a Bulk SMS System with MessageBird and NestJS (2025 Guide)
Learn how to build a production-ready bulk SMS broadcasting system using MessageBird API and NestJS. Complete TypeScript guide with rate limiting, retry logic, and Prisma database integration.
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.
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 /messages API 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:
Accepts bulk SMS requests through a REST API
Validates phone numbers in E.164 format
Processes messages in batches through MessageBird's SMS API (max 50 recipients per request)
Handles rate limiting with exponential backoff retry logic
Tracks delivery status for each message
Stores campaign history in a PostgreSQL database via Prisma
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:
Node.js (v18 LTS or later recommended) and npm/pnpm/yarn installed
A MessageBird account with an active API key. Sign up at MessageBird if you don't have one
PostgreSQL installed locally or access to a hosted instance (e.g., Supabase, Neon, or Railway)
Basic familiarity with NestJS, TypeScript, and REST APIs
Step 1: Set Up Your NestJS Project for MessageBird Integration
Create a new NestJS project:
Bash
nest new nestjs-messagebird-bulk
cd nestjs-messagebird-bulk
Step 3: Set Up Prisma Database Schema for SMS Campaign Tracking
Initialize Prisma:
Bash
npx prisma init
This command creates a prisma directory with a schema.prisma file. Update it to define your SMS campaign and message models:
Performance indexes: The schema below includes strategic indexes to optimize common query patterns. Index campaignId on SmsMessage for fast campaign lookups, status for filtering by delivery state, and createdAt for time-based queries. Composite index on (campaignId, status) accelerates dashboard queries showing campaign status breakdowns. For high-volume systems (>1M messages), consider partitioning the SmsMessage table by createdAt month.
Update prisma/schema.prisma:
Prisma
model SmsCampaign {
id Int @id @default(autoincrement())
name String
totalMessages Int @default(0)
successCount Int @default(0)
failureCount Int @default(0)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
messages SmsMessage[]
@@index([createdAt])
}
model SmsMessage {
id Int @id @default(autoincrement())
campaignId Int
campaign SmsCampaign @relation(fields: [campaignId], references: [id])
recipient String
originator String
body String
status String
messageBirdResponse Json?
errorMessage String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([campaignId])
@@index([status])
@@index([createdAt])
@@index([campaignId, status])
}
Schema explanation:
SmsCampaign – Stores campaign metadata, total message count, and success/failure tallies
SmsMessage – Tracks individual messages with recipient, status, and MessageBird response data
Relations connect campaigns to their messages via campaignId
Generate the Prisma client and run migrations:
Bash
npx prisma generate
npx prisma migrate dev --name init
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:
TypeScript
import { IsString, IsNotEmpty, IsArray, ArrayNotEmpty, ArrayMaxSize, ValidateNested, Matches, MaxLength } from'class-validator';
import { Type } from'class-transformer';
classMessageDto {
@IsArray()
@ArrayNotEmpty({ message: 'Recipients array cannot be empty.' })
@ArrayMaxSize(50, { message: 'Cannot process more than 50 messages per batch request due to MessageBird API limits.' })
@IsString({ each: true })
@Matches(/^\+[1-9]\d{1,14}$/, { each: true, message: 'Each recipient must be in E.164 format (e.g., +14155552671).' })
recipients: string[];
@IsString()
@IsNotEmpty({ message: 'Originator (sender ID) is required.' })
@MaxLength(11, { message: 'Originator cannot exceed 11 characters.' })
originator: string;
@IsString()
@IsNotEmpty({ message: 'Message body is required.' })
@MaxLength(1600, { message: 'Message body cannot exceed 1600 characters (10 concatenated SMS segments).' })
body: string;
}
exportclassCreateBulkSmsDto {
@IsString()
@IsNotEmpty({ message: 'Campaign name is required.' })
campaignName: string;
@IsArray()
@ArrayNotEmpty({ message: 'Messages array cannot be empty.' })
@ValidateNested({ each: true })
@Type(() =>MessageDto)
messages: MessageDto[];
}
Key validations:
E.164 format – Ensures phone numbers include country code (e.g., +14155552671)
50 recipients max – Matches MessageBird's standard API limit per request
Originator length – Alphanumeric sender IDs max 11 characters; numeric max 16 digits
Message length – Allows up to 10 concatenated SMS segments (160 chars × 10 = 1600 chars)
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 opossum or 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.ts to handle MessageBird API interactions, retry logic, and database persistence:
Step 9: Test Your MessageBird Bulk SMS Integration
Testing best practices:
Use test numbers: MessageBird provides test credentials that return success without sending real SMS. Check MessageBird Testing Documentation for test phone numbers
Start small: Test with 2–3 recipients before scaling to larger batches
Verify E.164 format: Use a tool like libphonenumber to validate phone numbers before testing
Check logs: Monitor NestJS logs for MessageBird API responses and error details
Inspect database: Query the SmsCampaign and SmsMessage tables to verify persistence
Debugging common issues:
401 Unauthorized: Verify MESSAGEBIRD_API_KEY is correct and not expired
422 Unprocessable Entity: Check phone number format (must be E.164: +14155552671)
Rate limit errors: Reduce request frequency or implement queue system
Database connection errors: Verify DATABASE_URL and PostgreSQL is running
Start your NestJS application:
Bash
npm run start:dev
Send a test bulk SMS request:
Bash
curl -X POST http://localhost:3000/sms/bulk \
-H "Content-Type: application/json" \
-d '{
"campaignName": "Black Friday Sale",
"messages": [
{
"recipients": ["+14155552671", "+14155552672"],
"originator": "YourBrand",
"body": "Get 50% off everything! Use code BF2025. Shop now: https://yourbrand.com"
},
{
"recipients": ["+442071234567"],
"originator": "YourBrand",
"body": "Exclusive UK offer: Free shipping on all orders today!"
}
]
}'
Expected response:
JSON
{"campaignId":1,"totalMessages":2,"successCount":2,"failureCount":0,"results":[{"recipients":["+14155552671","+14155552672"],"originator":"YourBrand","body":"Get 50% off everything!...","messageId":"abc123def456","status":"sent"},{"recipients":["+442071234567"],"originator":"YourBrand","body":"Exclusive UK offer...","messageId":"xyz789ghi012","status":"sent"}]}
Check campaign status:
Bash
curl http://localhost:3000/sms/campaign/1
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:
TypeScript
// In schema.prisma
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
// Add connection pooling// postgresql://user:pass@host:5432/db?connection_limit=20&pool_timeout=10
}
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:
Single NestJS instance: 1,000–5,000 messages/hour (limited by sequential processing)
With BullMQ queue + 5 workers: 25,000–50,000 messages/hour
Use environment variable management services (AWS Secrets Manager, HashiCorp Vault)
Never commit .env files to version control
Rotate API keys regularly
2. Rate Limiting Strategy
MessageBird enforces API rate limits (500 POST requests/second per official documentation). Implement application-level rate limiting:
TypeScript
ThrottlerModule.forRoot([{
ttl: 60000, // 1 minute windowlimit: 100, // 100 requests per minute per IP
}])
For high-volume campaigns, use a queue system (BullMQ, AWS SQS) to throttle requests.
3. Message Queuing for Large Campaigns
Queue system comparison:
Feature
BullMQ (Redis)
RabbitMQ
AWS SQS
Setup complexity
Low (npm install)
Medium (server setup)
Low (AWS account)
Hosting
Self-hosted or Redis Cloud
Self-hosted or CloudAMQP
Fully managed
Max throughput
10K+ jobs/sec
20K+ msgs/sec
3K msgs/sec (standard), unlimited (FIFO limited to 300/sec)
Persistence
Redis AOF/RDB
Durable queues
Durable by default
Best for
Node.js ecosystems, job scheduling
Microservices, complex routing
AWS-native apps, serverless
Cost
Redis hosting (~$10–50/mo)
Server costs (~$20–100/mo)
Pay-per-request ($0.40/million)
Retry/DLQ
Built-in (exponential backoff)
Manual config
Native support
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:
GDPR, TCPA, and CASL require verifiable opt-in consent before sending marketing SMS. Implement a consent management system:
Database schema additions:
Prisma
model Subscriber {
id Int @id @default(autoincrement())
phoneNumber String @unique
consentedAt DateTime
consentSource String // e.g., "website_signup", "in_store", "api"
consentIpAddress String? // Required for TCPA compliance
consentUserAgent String? // Browser/app that captured consent
optedOutAt DateTime?
optOutReason String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([phoneNumber])
@@index([consentedAt])
}
model ConsentAuditLog {
id Int @id @default(autoincrement())
subscriberId Int
action String // "opted_in", "opted_out", "consent_renewed"
timestamp DateTime @default(now())
ipAddress String
metadata Json? // Additional context
}
Compliance requirements by region:
GDPR (EU): Explicit consent required; must provide clear opt-out mechanism; retain consent records for 3 years minimum; allow data export/deletion on request (Article 17 "Right to be forgotten")
TCPA (USA): Prior express written consent for marketing; must include "by clicking you agree to receive SMS" language; maintain opt-in timestamp and IP address; honor opt-outs within 10 business days; prohibited calling hours: before 8 AM or after 9 PM local time
CASL (Canada): Express or implied consent required; include sender identification and unsubscribe mechanism in every message; consent expires after 24 months unless renewed
Verification before sending:
TypeScript
asyncsendBulkSms(dto: CreateBulkSmsDto) {
// Verify all recipients have active consentconst recipients = dto.messages.flatMap(m => m.recipients);
const consented = awaitthis.prisma.subscriber.findMany({
where: {
phoneNumber: { in: recipients },
consentedAt: { not: null },
optedOutAt: null,
},
});
const consentedNumbers = newSet(consented.map(s => s.phoneNumber));
const unauthorized = recipients.filter(r => !consentedNumbers.has(r));
if (unauthorized.length > 0) {
thrownewHttpException(
`Cannot send to ${unauthorized.length} recipients without consent: ${unauthorized.join(', ')}`,
HttpStatus.FORBIDDEN
);
}
// Proceed with sending...
}
Ensure legal compliance:
GDPR (EU) – Obtain explicit consent before sending promotional messages
TCPA (USA) – Maintain opt-in records for marketing messages
CASL (Canada) – Include unsubscribe mechanisms in all commercial messages
Store consent timestamps in your database:
Prisma
model Subscriber {
id Int @id @default(autoincrement())
phoneNumber String @unique
consentedAt DateTime
optedOutAt DateTime?
}
6. Cost Optimization
Practical cost calculations:
MessageBird charges per message segment. Here's how pricing works:
Example 1: Standard promotional campaign
Message: "Flash sale! 40% off all items. Shop now: example.com/sale" (68 chars)
Encoding: GSM-7 (no special characters)
Segments: 1 (≤160 chars)
Recipients: 10,000
Cost: 10,000 × $0.0175 (US rate) = $175
Example 2: Unicode message with emoji
Message: "🎉 Sale alert! 50% off today 🛍️" (35 chars including emoji)
Encoding: UCS-2 (contains emoji)
Segments: 1 (≤70 chars for Unicode)
Recipients: 10,000
Cost: 10,000 × $0.0175 = $175 (same cost but uses 50% of character budget)
Example 3: Long concatenated message
Message: "Dear valued customer, your exclusive VIP discount code for this month is SAVE25OFF. Use it on any purchase above $50. Valid until end of month. Visit store.example.com for details. Terms and conditions apply." (220 chars)
Encoding: GSM-7
Segments: 2 (splits at 153 chars due to concatenation overhead: 160 - 7 header bytes)
Recipients: 10,000
Cost: 10,000 × 2 × $0.0175 = $350
Cost optimization strategies:
Message length optimization: Keep messages under 160 chars (GSM-7) or 70 chars (Unicode) to avoid concatenation costs
Avoid Unicode when possible: Replace emoji/special chars with GSM-7 equivalents (e.g., "Sale!" instead of "🎉 Sale!")
Use URL shorteners: Reduce long URLs (e.g., bit.ly/promo instead of full URLs)
Batch timing: Send campaigns during off-peak hours for potential volume discounts (contact MessageBird sales)
Segment audience: Target high-value recipients instead of entire database to reduce waste
SSL required for hosted databases: Add ?sslmode=require to connection string
Connection pool exhaustion: Increase pool size in Prisma schema
Network timeouts: Increase connect_timeout parameter in connection string
Frequently Asked Questions (FAQ)
How many recipients can I send to in a single MessageBird API request?
MessageBird's standard /messages endpoint 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 SmsService includes a sendWithRetry() 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) and SmsMessage (tracks individual messages with recipient, status, and MessageBird response data). This schema enables campaign tracking, delivery reports, and historical analytics. Run npx prisma migrate dev to 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 using libphonenumber-js library 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:
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.
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:
nest new nestjs-messagebird-bulk cd nestjs-messagebird-bulkInstall 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:# MessageBird API Configuration MESSAGEBIRD_API_KEY=YOUR_API_TOKEN_HERE MESSAGEBIRD_API_BASE_URL=https://rest.messagebird.com # Database Configuration DATABASE_URL="postgresql://user:password@localhost:5432/sms_db?schema=public" # Application Settings PORT=3000 NODE_ENV=developmentReplace
YOUR_API_TOKEN_HEREwith your actual MessageBird API key from the MessageBird Dashboard.Update
src/app.module.tsto load environment variables:import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import { ThrottlerModule } from '@nestjs/throttler'; import { PrismaModule } from './prisma/prisma.module'; import { SmsModule } from './sms/sms.module'; @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true }), ThrottlerModule.forRoot([{ ttl: 60000, // 60 seconds limit: 10, // 10 requests per minute }]), PrismaModule, SmsModule, ], }) export class AppModule {}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:import { IsString, IsNotEmpty, IsArray, ArrayNotEmpty, ArrayMaxSize, ValidateNested, Matches, MaxLength } from 'class-validator'; import { Type } from 'class-transformer'; class MessageDto { @IsArray() @ArrayNotEmpty({ message: 'Recipients array cannot be empty.' }) @ArrayMaxSize(50, { message: 'Cannot process more than 50 messages per batch request due to MessageBird API limits.' }) @IsString({ each: true }) @Matches(/^\+[1-9]\d{1,14}$/, { each: true, message: 'Each recipient must be in E.164 format (e.g., +14155552671).' }) recipients: string[]; @IsString() @IsNotEmpty({ message: 'Originator (sender ID) is required.' }) @MaxLength(11, { message: 'Originator cannot exceed 11 characters.' }) originator: string; @IsString() @IsNotEmpty({ message: 'Message body is required.' }) @MaxLength(1600, { message: 'Message body cannot exceed 1600 characters (10 concatenated SMS segments).' }) body: string; } export class CreateBulkSmsDto { @IsString() @IsNotEmpty({ message: 'Campaign name is required.' }) campaignName: string; @IsArray() @ArrayNotEmpty({ message: 'Messages array cannot be empty.' }) @ValidateNested({ each: true }) @Type(() => MessageDto) messages: MessageDto[]; }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:import { Injectable, Logger, HttpException, HttpStatus } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { HttpService } from '@nestjs/axios'; import { PrismaService } from '../prisma/prisma.service'; import { CreateBulkSmsDto } from './dto/create-bulk-sms.dto'; import { firstValueFrom } from 'rxjs'; import { AxiosError } from 'axios'; interface MessageBirdResponseItem { recipients: string[]; originator: string; body: string; messageId?: string; status?: string; error?: string; } @Injectable() export class SmsService { private readonly logger = new Logger(SmsService.name); private readonly apiKey: string; private readonly baseUrl: string; private readonly messageApiEndpoint = '/messages'; private readonly maxRetries = 3; private readonly retryDelayMs = 1000; constructor( private readonly configService: ConfigService, private readonly httpService: HttpService, private readonly prisma: PrismaService, ) { this.apiKey = this.configService.get<string>('MESSAGEBIRD_API_KEY'); this.baseUrl = this.configService.get<string>('MESSAGEBIRD_API_BASE_URL', 'https://rest.messagebird.com'); if (!this.apiKey) { throw new Error('MESSAGEBIRD_API_KEY is not configured. Check your .env file.'); } } async sendBulkSms(createBulkSmsDto: CreateBulkSmsDto) { const { campaignName, messages } = createBulkSmsDto; // Create campaign record const campaign = await this.prisma.smsCampaign.create({ data: { name: campaignName, totalMessages: messages.reduce((sum, msg) => sum + msg.recipients.length, 0), }, }); this.logger.log(`Created campaign: ${campaign.name} (ID: ${campaign.id})`); // Process messages with retry logic const results: MessageBirdResponseItem[] = []; for (const message of messages) { const payload = { recipients: message.recipients, originator: message.originator, body: message.body, }; try { const response = await this.sendWithRetry(payload); results.push({ ...message, messageId: response.id, status: 'sent', }); // Store successful messages in database await this.storeMessages(campaign.id, message.recipients, message.originator, message.body, 'sent', response); } catch (error) { this.logger.error(`Failed to send message after ${this.maxRetries} retries:`, error); results.push({ ...message, status: 'failed', error: error.message, }); // Store failed messages await this.storeMessages(campaign.id, message.recipients, message.originator, message.body, 'failed', null, error.message); } } // Update campaign statistics const successCount = results.filter((r) => r.status === 'sent').length; const failureCount = results.filter((r) => r.status === 'failed').length; await this.prisma.smsCampaign.update({ where: { id: campaign.id }, data: { successCount, failureCount, }, }); return { campaignId: campaign.id, totalMessages: messages.length, successCount, failureCount, results, }; } private async sendWithRetry(payload: any, attempt = 1): Promise<any> { try { const response = await firstValueFrom( this.httpService.post(`${this.baseUrl}${this.messageApiEndpoint}`, payload, { headers: { 'Authorization': `AccessKey ${this.apiKey}`, 'Content-Type': 'application/json', }, }), ); return response.data; } catch (error) { const axiosError = error as AxiosError; const statusCode = axiosError.response?.status; // Retry on rate limit (429) or server errors (5xx) let shouldRetry = false; if (!statusCode || statusCode === 429 || (statusCode >= 500 && statusCode <= 599)) { shouldRetry = true; } if (shouldRetry && attempt < this.maxRetries) { const delay = this.retryDelayMs * Math.pow(2, attempt - 1); // Exponential backoff this.logger.warn(`Retry attempt ${attempt}/${this.maxRetries} after ${delay}ms due to status ${statusCode || 'network error'}`); await this.sleep(delay); return this.sendWithRetry(payload, attempt + 1); } // Exhausted retries or non-retriable error this.logger.error(`MessageBird API error: ${axiosError.message}`, axiosError.response?.data); throw new HttpException( axiosError.response?.data || 'Failed to send SMS via MessageBird', statusCode || HttpStatus.INTERNAL_SERVER_ERROR, ); } } private async storeMessages( campaignId: number, recipients: string[], originator: string, body: string, status: string, response?: any, error?: string, ) { const messageData = recipients.map((recipient) => ({ campaignId, recipient, originator, body, status, messageBirdResponse: response ? JSON.stringify(response) : null, errorMessage: error || null, })); await this.prisma.smsMessage.createMany({ data: messageData }); } private sleep(ms: number): Promise<void> { return new Promise((resolve) => setTimeout(resolve, ms)); } async getCampaignStatus(campaignId: number) { const campaign = await this.prisma.smsCampaign.findUnique({ where: { id: campaignId }, include: { messages: true }, }); if (!campaign) { throw new HttpException('Campaign not found', HttpStatus.NOT_FOUND); } return campaign; } }Key features:
Step 6: Create the NestJS SMS Controller with Rate Limiting
Create
src/sms/sms.controller.tsto expose REST endpoints:import { Controller, Post, Get, Body, Param, ParseIntPipe, UseGuards } from '@nestjs/common'; import { ThrottlerGuard } from '@nestjs/throttler'; import { SmsService } from './sms.service'; import { CreateBulkSmsDto } from './dto/create-bulk-sms.dto'; @Controller('sms') @UseGuards(ThrottlerGuard) // Rate limiting: 10 requests per minute by default export class SmsController { constructor(private readonly smsService: SmsService) {} @Post('bulk') async sendBulkSms(@Body() createBulkSmsDto: CreateBulkSmsDto) { return this.smsService.sendBulkSms(createBulkSmsDto); } @Get('campaign/:id') async getCampaignStatus(@Param('id', ParseIntPipe) id: number) { return this.smsService.getCampaignStatus(id); } }Step 7: Create the Prisma Service Module
Create
src/prisma/prisma.service.ts:import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common'; import { PrismaClient } from '@prisma/client'; @Injectable() export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy { async onModuleInit() { await this.$connect(); } async onModuleDestroy() { await this.$disconnect(); } }Create
src/prisma/prisma.module.ts:import { Module, Global } from '@nestjs/common'; import { PrismaService } from './prisma.service'; @Global() @Module({ providers: [PrismaService], exports: [PrismaService], }) export class PrismaModule {}Step 8: Wire Up the SMS Module
Create
src/sms/sms.module.ts:import { Module } from '@nestjs/common'; import { HttpModule } from '@nestjs/axios'; import { SmsService } from './sms.service'; import { SmsController } from './sms.controller'; @Module({ imports: [HttpModule], controllers: [SmsController], providers: [SmsService], }) export class SmsModule {}Update
src/app.module.ts:import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import { ThrottlerModule } from '@nestjs/throttler'; import { PrismaModule } from './prisma/prisma.module'; import { SmsModule } from './sms/sms.module'; @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true }), ThrottlerModule.forRoot([{ ttl: 60000, // 60 seconds limit: 10, // 10 requests per minute }]), PrismaModule, SmsModule, ], }) export class AppModule {}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:
curl -X POST http://localhost:3000/sms/bulk \ -H "Content-Type: application/json" \ -d '{ "campaignName": "Black Friday Sale", "messages": [ { "recipients": ["+14155552671", "+14155552672"], "originator": "YourBrand", "body": "Get 50% off everything! Use code BF2025. Shop now: https://yourbrand.com" }, { "recipients": ["+442071234567"], "originator": "YourBrand", "body": "Exclusive UK offer: Free shipping on all orders today!" } ] }'Expected response:
{ "campaignId": 1, "totalMessages": 2, "successCount": 2, "failureCount": 0, "results": [ { "recipients": ["+14155552671", "+14155552672"], "originator": "YourBrand", "body": "Get 50% off everything!...", "messageId": "abc123def456", "status": "sent" }, { "recipients": ["+442071234567"], "originator": "YourBrand", "body": "Exclusive UK offer...", "messageId": "xyz789ghi012", "status": "sent" } ] }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:
// In schema.prisma datasource db { provider = "postgresql" url = env("DATABASE_URL") // Add connection pooling // postgresql://user:pass@host:5432/db?connection_limit=20&pool_timeout=10 }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:
ThrottlerModule.forRoot([{ ttl: 60000, // 1 minute window limit: 100, // 100 requests per minute per IP }])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:import { InjectQueue } from '@nestjs/bull'; import { Queue } from 'bull'; @Injectable() export class SmsService { constructor(@InjectQueue('sms') private smsQueue: Queue) {} async sendBulkSms(dto: CreateBulkSmsDto) { for (const message of dto.messages) { await this.smsQueue.add('send-sms', message, { attempts: 3, backoff: { type: 'exponential', delay: 2000 }, }); } } }4. Monitoring and Logging
Critical metrics to monitor:
Monitoring stack setup:
Integrate application performance monitoring (APM):
Add structured logging:
this.logger.log({ event: 'bulk_sms_sent', campaignId: campaign.id, successCount, failureCount, timestamp: new Date().toISOString(), });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:
async sendBulkSms(dto: CreateBulkSmsDto) { // Verify all recipients have active consent const recipients = dto.messages.flatMap(m => m.recipients); const consented = await this.prisma.subscriber.findMany({ where: { phoneNumber: { in: recipients }, consentedAt: { not: null }, optedOutAt: null, }, }); const consentedNumbers = new Set(consented.map(s => s.phoneNumber)); const unauthorized = recipients.filter(r => !consentedNumbers.has(r)); if (unauthorized.length > 0) { throw new HttpException( `Cannot send to ${unauthorized.length} recipients without consent: ${unauthorized.join(', ')}`, HttpStatus.FORBIDDEN ); } // Proceed with 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:
function calculateSegments(body: string): number { const isUnicode = /[^\x00-\x7F]/.test(body); const maxLength = isUnicode ? 70 : 160; return Math.ceil(body.length / maxLength); }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:
import { parsePhoneNumber } from 'libphonenumber-js'; function validateE164(phone: string): boolean { try { const parsed = parsePhoneNumber(phone); return parsed.isValid() && parsed.format('E.164') === phone; } catch { return false; } }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:
// Add to SmsService private tokenBucket = { tokens: 500, maxTokens: 500, refillRate: 500, // tokens per second lastRefill: Date.now(), }; private async acquireToken(): Promise<void> { const now = Date.now(); const elapsed = (now - this.tokenBucket.lastRefill) / 1000; this.tokenBucket.tokens = Math.min( this.tokenBucket.maxTokens, this.tokenBucket.tokens + elapsed * this.tokenBucket.refillRate ); this.tokenBucket.lastRefill = now; if (this.tokenBucket.tokens < 1) { const waitTime = (1 - this.tokenBucket.tokens) / this.tokenBucket.refillRate * 1000; await this.sleep(waitTime); return this.acquireToken(); } this.tokenBucket.tokens -= 1; }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:
DATABASE_URL="postgresql://username:password@localhost:5432/database_name?schema=public"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:
// src/sms/sms.controller.ts import { Controller, Post, Body, Headers, HttpCode, HttpStatus } from '@nestjs/common'; @Controller('sms') export class SmsController { constructor(private readonly smsService: SmsService) {} @Post('webhook/status') @HttpCode(HttpStatus.OK) async handleDeliveryStatus( @Body() payload: any, @Headers('messagebird-signature') signature: string, ) { // Verify webhook signature (recommended for production) // See MessageBird webhook security documentation await this.smsService.updateMessageStatus(payload); return { status: 'received' }; } }2. Add status update method to service:
// src/sms/sms.service.ts async updateMessageStatus(payload: any) { const { id: messageBirdId, status, statusDatetime } = payload; // Find message by MessageBird ID and update status await this.prisma.smsMessage.updateMany({ where: { messageBirdResponse: { path: ['id'], equals: messageBirdId } }, data: { status, updatedAt: new Date(statusDatetime) }, }); this.logger.log(`Updated message ${messageBirdId} to status: ${status}`); }3. Configure webhook in MessageBird Dashboard:
Navigate to MessageBird Dashboard → Developers → Webhooks → Add Webhook:
https://yourdomain.com/sms/webhook/status4. Secure webhook endpoint:
import * as crypto from 'crypto'; function verifyWebhookSignature( payload: string, signature: string, secret: string ): boolean { const hash = crypto .createHmac('sha256', secret) .update(payload) .digest('hex'); return hash === signature; }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: