Frequently Asked Questions
Use the Fastify framework with the MessageBird API and a Redis queue. The Fastify app receives SMS requests, adds them to a BullMQ job queue managed by Redis, and a background worker processes these jobs to send messages via the MessageBird API asynchronously.
The MessageBird Node.js SDK (@messagebird/api) simplifies interaction with the MessageBird REST API, making it easier to send SMS messages within your Node.js application. It handles the low-level details of making API calls, managing responses, and error handling.
Redis and BullMQ provide an asynchronous job queue system. This prevents blocking the main application thread when sending large volumes of SMS messages, improving responsiveness and scalability. BullMQ uses Redis as its message broker.
Prisma is optional but recommended for tracking message status. Use it if you need a robust way to persist message data (e.g., recipient, status, delivery reports) in a database like PostgreSQL.
Store your MessageBird API key securely in a .env file in your project's root directory. The provided code example uses dotenv to load environment variables, so your key will be available via process.env.MESSAGEBIRD_API_KEY. Never commit your .env file.
The example Fastify route includes error handling for queue failures using try-catch blocks around each addSmsJob call. Failed jobs are recorded and logged. The route is designed to continue processing and enqueueing other messages even if some queue additions fail.
The background worker listens to the Redis queue (using BullMQ) for new SMS sending jobs. It processes each job, extracting recipient and message data, and makes calls to the MessageBird API to send the actual SMS messages.
The worker example includes a limiter option with max and duration to control the number of jobs processed within a specified time window. Adjust these values according to your MessageBird account's specific rate limits to avoid exceeding them.
The guide recommends Node.js v18 or later. This ensures compatibility with Fastify, BullMQ, the MessageBird SDK, and other dependencies.
You can use a purchased Virtual Mobile Number (VMN) or an Alphanumeric Sender ID (if available in your target region). VMNs allow two-way communication (receiving replies), while Alphanumeric IDs (e.g., company name) might have country restrictions and don't receive replies. Configure it using the MESSAGEBIRD_ORIGINATOR environment variable.
Fastify is a high-performance Node.js web framework. It is chosen for its speed, extensibility, and developer-friendly features like schema validation and logging, which make it suitable for building robust and scalable APIs.
Create a config/redis.js file to set up the Redis connection. Provide your Redis host, port, and password (if necessary) using environment variables loaded with dotenv. Alternatively, you can use the REDIS_URL environment variable with a connection string.
The .gitignore file excludes sensitive information (like .env) and unnecessary files (like node_modules) from your Git repository. This is crucial for security and avoids bloating your project's version history.
Yes, Prisma supports various databases (PostgreSQL, MySQL, SQLite, and more). You'll need to adjust the datasource provider and connection string in your Prisma schema and .env file accordingly.
Use the concurrently package and the "dev" script defined in package.json. This script simultaneously runs both the API server with nodemon (auto-restarts) and the worker process with nodemon.
Build a Bulk SMS System with MessageBird, Node.js, and Fastify
Learn how to build a production-ready bulk SMS broadcasting system using MessageBird API with Node.js and Fastify. This comprehensive guide shows you how to create a scalable SMS broadcast application that efficiently handles high-volume messaging using asynchronous job queues with BullMQ and Redis. You'll implement the MessageBird Node.js SDK, build a high-performance Fastify REST API, and configure background workers for reliable SMS delivery at scale.
This step-by-step tutorial walks you through building a complete Node.js application using the Fastify framework to send bulk or broadcast SMS messages via the MessageBird API. You'll cover everything from project setup and core logic to asynchronous processing, error handling, and production deployment best practices.
Create a system that efficiently handles sending large volumes of SMS messages without blocking your main application thread, incorporating best practices for reliability and scalability. Perfect for marketing campaigns, notification systems, and mass communication needs.
Technologies Used:
messagebird): Official Node.js client that simplifies interaction with the MessageBird REST API.envfileSystem Architecture:
Here's how the components interact:
What You'll Build:
By the end of this guide, you will have:
Prerequisites:
originatorInstall Redis using one of these methods:
1. Setting Up Your Node.js Bulk SMS Project
Initialize your Node.js project and install the necessary dependencies for building a MessageBird SMS integration with Fastify.
1.1 Create Project Directory and Initialize
Open your terminal and create a new directory for your project, then navigate into it.
Initialize the Node.js project using npm (or yarn):
This creates a
package.jsonfile.1.2 Install Dependencies
Install Fastify, the MessageBird SDK, BullMQ, Redis client, dotenv, and Prisma (if using database tracking).
fastify: The web frameworkmessagebird: The official MessageBird Node.js SDK (formerly referenced as@messagebird/apiin some examples)bullmq: The job queue libraryioredis: A robust Redis client needed by BullMQdotenv: Loads environment variables from a.envfileprisma,@prisma/client,pg: For database interaction (ORM, client, PostgreSQL driver)nodemon: Automatically restarts the server during development on file changesconcurrently: Runs multiple commands concurrently (useful for running the API and worker)1.3 Project Structure
Create the following directory structure within your project root:
Your project structure:
1.4 Configure Environment Variables
Create a
.envfile in the project root. This file holds your sensitive credentials and configuration. Never commit this file to version control.Also create a
.env.examplefile to show the required variables..env.example:Copy
.env.exampleto.envand fill in your actual credentials:MESSAGEBIRD_API_KEY: Your live API access key from the MessageBird dashboard (Developers → API access → Show key)MESSAGEBIRD_ORIGINATOR: The sender ID for your SMS messages. This can be:+12025550147)MyCompany, max 11 characters). Note: Alphanumeric IDs are not supported in all countries (e.g., the US) and cannot receive replies. Check MessageBird's country restrictions. Use a number for broader compatibilityREDIS_HOST,REDIS_PORT,REDIS_PASSWORD/REDIS_URL: Connection details for your Redis serverDATABASE_URL: (Optional) Connection string for your PostgreSQL database if using Prisma. Follow the format specified in the Prisma documentation for your specific databaseAPI_PORT,API_HOST: Network configuration for the Fastify serverQUEUE_NAME: A name for the BullMQ job queue1.5 Configure
.gitignoreCreate a
.gitignorefile in the root to prevent sensitive files and unnecessary folders from being committed:.gitignore:1.6 (Optional) Initialize Prisma
If you're using the database for tracking, initialize Prisma:
This creates the
prisma/directory and aschema.prismafile.Example Prisma Schema for Message Tracking:
Update
prisma/schema.prisma:Run the migration:
1.7 Configure
package.jsonScriptsAdd scripts to your
package.jsonfor easier development and execution:package.json(add/update thescriptssection):start:api/start:worker: Run the API server and worker in productiondev:api/dev:worker: Run the API server and worker usingnodemonfor development (auto-restarts on changes)dev: Runs both the API and worker concurrently for development usingconcurrentlydb:migrate,db:studio: (Optional) Prisma commands for database migrations and GUIYour basic project structure and configuration are now complete.
2. Implementing MessageBird API Integration and Job Queue
Implement the core logic for sending messages via MessageBird and set up the asynchronous queue.
2.1 Configure MessageBird Service for SMS Sending
Create a service file to encapsulate MessageBird interactions.
src/services/messagebirdService.js:messagebirdpackage. Includes error handling for missing keys or initialization failuressendSmsfunction:recipientandbodyas argumentsparamsobject required bymessagebirdClient.messages.createPromiseto handle the callback-based MessageBird SDK APINote on Bulk Sending: For sending to multiple recipients efficiently, MessageBird also provides a Batch API that allows sending different messages to up to 50 recipients per request. This can be more efficient than individual calls for very large batches.
2.2 Configure Redis and BullMQ for Asynchronous SMS Processing
Set up the connection to Redis and define the BullMQ queue.
src/config/redis.js:.envREDIS_URLsrc/jobs/smsQueue.js:Queueinstance, connecting it to Redis via the shared connectiondefaultJobOptions: Configures crucial settings:attempts,backoff,removeOnComplete/removeOnFailaddSmsJobfunction: Adds a new job to the queue with recipient and body data2.3 Create the Background Worker for SMS Job Processing
This process listens to the queue and executes the jobs.
src/worker.js:Workerinstance listening to the queueprocessSmsJobFunction: The core job execution logic, callingsendSms. Handles errors and re-throws them for BullMQ retries. Includes optional Prisma integration points3. Building the Fastify REST API for Bulk SMS
Create the Fastify server and the API endpoint to receive bulk SMS requests.
src/api.js:bulkSmsSchema): Defines request body structure, including E.164 regex. Defines202 Acceptedresponse schema/send-bulkRoute: Validates input, iterates recipients, callsaddSmsJobfor each, handles queuing errors, returns202 Accepted. Includes optional Prisma integration points/healthRoute: Basic health check endpoint4. MessageBird API Integration Guide
The core integration with MessageBird happens within the
src/services/messagebirdService.jsfile, which was created in Section 2.1.Key Integration Points:
messagebird(process.env.MESSAGEBIRD_API_KEY)securely initializes the SDK using the API key from environment variablesmessagebirdClient.messages.create(params, callback)is the method used to send individual SMS messages. ThesendSmsfunction wraps this logicMESSAGEBIRD_ORIGINATORenvironment variable determines the sender ID.envfileObtaining API Credentials:
MESSAGEBIRD_API_KEYin your.envfileEnvironment Variable Summary:
MESSAGEBIRD_API_KEYlive_xxxxx...)MESSAGEBIRD_ORIGINATOR+12025550147) or alphanumeric (max 11 chars, e.g.,MyCompany)Alternative for Large Volumes: For larger volumes (50+ recipients with same message), consider using the MessageBird Batch API which allows up to 50 recipients per request for improved efficiency.
5. Running Your Bulk SMS Application
Start your bulk SMS system using the npm scripts configured earlier.
5.1 Development Mode
Run both the API server and worker concurrently with auto-restart on file changes:
Or run them separately in different terminals:
5.2 Production Mode
Run the API and worker as separate processes:
Process Manager Recommendation: Use a process manager like PM2 for production deployments:
5.3 Testing the Bulk SMS API
Send a test bulk SMS request using curl:
Expected response (202 Accepted):
Monitor the worker logs to see job processing in real-time.
6. Next Steps and Best Practices
6.1 Security Best Practices
/send-bulkendpoint@fastify/rate-limitto prevent abuse.envfiles. Use secret management services in production (e.g., AWS Secrets Manager, HashiCorp Vault)6.2 Monitoring and Observability
6.3 Performance Optimization
concurrencysetting in your worker based on your server resources and MessageBird rate limits6.4 Error Handling and Recovery
6.5 Cost Optimization
Conclusion
You now have a production-ready bulk SMS broadcast system using MessageBird, Node.js, Fastify, and BullMQ. This architecture handles large message volumes efficiently through asynchronous processing, includes retry logic for reliability, and provides a foundation for scaling.
The key architectural decisions – using BullMQ for job queuing, Redis for persistence, and Fastify for high-performance API handling – create a robust system that can grow with your needs.
Related Resources:
Additional Documentation: