WhatsApp API Messaging Best Practices for Developers
Any statistics or percentages in this article are general industry figures or illustrations, not QuackAPI measurements or promises. Results depend on your audience, consent and sending patterns. QuackAPI connects to WhatsApp as a linked device (an unofficial method), so read our risk and acceptable use policy before sending.
Rate Limiting and Throttling
Implement a message queue to control the rate at which messages are sent. Sending too many messages too quickly can overwhelm the API and trigger rate limits or bans. A simple queue with configurable delay ensures smooth, compliant delivery.
class MessageQueue {
constructor(delayMs = 1000) {
this.queue = [];
this.delayMs = delayMs;
this.processing = false;
}
add(message) {
this.queue.push(message);
if (!this.processing) this.process();
}
async process() {
this.processing = true;
while (this.queue.length > 0) {
const msg = this.queue.shift();
try {
await this.send(msg);
} catch (error) {
console.error("Send failed:", error.message);
// Re-queue with backoff if needed
}
await this.delay(this.delayMs);
}
this.processing = false;
}
async send(msg) {
const axios = require("axios");
return axios.post("https://quackapi.com/v1/messages/send", msg, {
headers: {
"Content-Type": "application/json",
"x-api-key": process.env.QUACKAPI_API_KEY
}
});
}
delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
const queue = new MessageQueue(1500);
queue.add({ deviceId: 1, to: "923001234567", content: "Hello!", type: "text" });Error Handling Patterns
Robust error handling is essential for production messaging systems. Categorize errors into retriable (network timeouts, 500 errors) and non-retriable (invalid API key, malformed request). Handle each category differently to avoid wasting resources on permanent failures.
async function sendWithErrorHandling(payload) {
try {
const response = await axios.post(BASE_URL, payload, { headers });
return { success: true, data: response.data };
} catch (error) {
const status = error.response?.status;
const message = error.response?.data?.message || error.message;
if (status === 401) {
console.error("Invalid API key. Check QUACKAPI_API_KEY.");
return { success: false, retriable: false, error: message };
}
if (status === 429) {
console.warn("Rate limited. Slowing down...");
return { success: false, retriable: true, error: message };
}
if (status >= 500) {
console.warn("Server error. Will retry.");
return { success: false, retriable: true, error: message };
}
console.error("Request failed:", message);
return { success: false, retriable: false, error: message };
}
}Message Formatting Tips
WhatsApp supports basic text formatting that can improve readability. Use *bold* for emphasis, _italic_ for subtle highlights, and ~strikethrough~ for corrections. Combine these to create well-structured, scannable messages.
Keep messages concise and action-oriented. Break long content into multiple shorter messages rather than one wall of text. Use line breaks and bullet points to organize information logically.
Include clear calls to action in every message. Tell the user exactly what you want them to do next, whether it is replying with a keyword, clicking a link, or calling a number.
Media Optimization
Optimize images before sending to reduce delivery time and data usage. Compress images to under 1MB when possible. WhatsApp supports JPEG, PNG, and WebP formats. JPEG is recommended for photographs, while PNG is better for graphics with text.
For documents, keep PDF files under 10MB. Use descriptive filenames that help users identify the document content. Supported document types include PDF, DOC, DOCX, XLS, XLSX, and PPT.
Video files should be compressed to under 16MB and use MP4 format with H.264 encoding for maximum compatibility. Keep videos under 3 minutes for optimal user engagement.
Retry Logic with Exponential Backoff
Implement exponential backoff for retrying failed requests. This prevents overwhelming the API during outages and gives the server time to recover. Cap the maximum number of retries and the maximum delay to avoid indefinite waits.
async function sendWithRetry(payload, maxRetries = 3) {
let lastError;
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await axios.post(
"https://quackapi.com/v1/messages/send",
payload,
{
headers: {
"Content-Type": "application/json",
"x-api-key": process.env.QUACKAPI_API_KEY
},
timeout: 10000
}
);
return response.data;
} catch (error) {
lastError = error;
const status = error.response?.status;
// Don't retry client errors (except rate limiting)
if (status && status >= 400 && status < 500 && status !== 429) {
throw error;
}
// Exponential backoff: 1s, 2s, 4s
const delayMs = Math.min(1000 * Math.pow(2, attempt), 10000);
console.log(`Retry ${attempt + 1}/${maxRetries} in ${delayMs}ms`);
await new Promise(resolve => setTimeout(resolve, delayMs));
}
}
throw lastError;
}Monitoring and Logging
Log every API request and response with timestamps, recipient numbers (masked for privacy), message types, and status codes. This data is invaluable for debugging delivery issues and optimizing your messaging strategy.
Track key metrics like delivery success rate, average response time, and error frequency. Set up alerts when error rates exceed thresholds, for example if more than 5% of messages fail in a 10-minute window.
Use structured logging with JSON format so you can easily search and aggregate logs. Include correlation IDs to trace a single message through your entire pipeline from creation to delivery confirmation.