Reusable Django WhatsApp integration (Celery, rate-limiter, webhook, idempotency)
Project description
Whatsapp Integration
A reusable Django app providing enterprise-grade WhatsApp Business API integration with message queuing, Celery task orchestration, Redis-based rate limiting (Lua token bucket), idempotency, and webhook handling.
Designed for production environments and multi-project reusability, this package provides a scalable way to send, track, and process WhatsApp messages across your Django applications.
โจ Features
- โ Reusable Django app โ install once, integrate anywhere
- ๐ Celery task orchestration โ background message processing with exponential backoff
- ๐ง Idempotency & retry safety โ prevents duplicate messages during failures
- ๐ Secure webhook verification โ HMAC validation and token-based verification
- ๐ฌ Unified service API โ
send_textandsend_templatewith optional components - ๐งฉ Redis Lua rate limiter โ atomic token bucket algorithm for scalable throughput
- โ๏ธ Configurable โ all keys & tokens loaded from Django
settings.py - ๐งฑ PostgreSQL-optimized schema โ indexed queries for performance
- ๐งฐ CI/CD & Docker ready โ comes with workflows, Dockerfile, and docker-compose
- ๐ PDF Generator Tool โ generate a full repo snapshot in a single PDF
๐งฉ Architecture Overview
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ | Django App โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ whatsapp_integration โ โ
โ โ โโโ models.py โ WhatsAppMessage, WebhookEvent โ โ
โ โ โโโ services/ โ WhatsAppService abstraction โ โ
โ โ โโโ tasks.py โ Celery async workers โ โ
โ โ โโโ rate_limiter/ โ Redis Lua token bucket โ โ
โ โ โโโ views.py โ Webhook endpoints โ โ
โ โ โโโ commands.py โ Command + Event dispatcher โ โ
โ โ โโโ utils.py โ Error classification, helpers โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ Installation
1๏ธโฃ Install from PyPI (or locally)
pip install whatsapp_integration
โ๏ธ Configuration
- Add the app to your Django settings:
INSTALLED_APPS = [
...
"whatsapp_integration",
]
- Environment Variables / Settings
WHATSAPP_PHONE_NUMBER_ID = "1234567890"
WHATSAPP_ACCESS_TOKEN = "your_long_lived_graph_api_token"
WHATSAPP_VERIFY_TOKEN = "your_webhook_verify_token"
WHATSAPP_APP_SECRET = "facebook_app_secret" # optional but recommended
WHATSAPP_RATE_PER_SECOND = 1.5 # messages per second allowed
REDIS_URL = "redis://localhost:6379/0"
- Make migrations
python manage.py makemigrations
- Celery Setup
In your settings.py:
CELERY_BROKER_URL = "redis://localhost:6379/0"
CELERY_RESULT_BACKEND = "redis://localhost:6379/0"
Then in your project root:
celery -A your_project worker -l info
๐ Sending Messages
Use the service directly or queue messages for asynchronous processing.
Example: Send text message immediately
from whatsapp_integration.services import whatsapp_service
whatsapp_service.default_whatsapp_service.send_text(
recipient="15551234567",
message="Hello from Django WhatsApp Integration!"
)
Example: Queue message for async send via Celery
from whatsapp_integration.models import WhatsAppMessage
from whatsapp_integration.tasks import send_whatsapp_message_task
msg = WhatsAppMessage.objects.create(
recipient="15551234567",
message_type="text",
payload={"body": "Queued message test"}
)
send_whatsapp_message_task.delay(str(msg.id))
๐ฌ Handling Webhooks
Facebook/WhatsApp will send inbound messages or delivery updates to your webhook.
URL Mapping
Add to your root urls.py:
urlpatterns = [
...
path("api/v1/whatsapp/", include("whatsapp_integration.urls")),
]
This registers:
GET api/v1/whatsapp/webhook/verify/ โ for verification handshake
POST api/v1/whatsapp/webhook/ โ for inbound message events
Example verification response
GET api/v1/whatsapp/webhook/verify/?hub.mode=subscribe&hub.verify_token=YOUR_TOKEN&hub.challenge=CHALLENGE
Returns CHALLENGE if token matches.
๐ฆ Rate Limiting (Lua + Redis)
How it works
A token bucket algorithm written in Lua ensures you never exceed Metaโs rate limits:
Each message consumes a โtokenโ.
Tokens regenerate over time according to WHATSAPP_RATE_PER_SECOND.
Fully atomic via Redis EVALSHA (no race conditions).
Lua script: lua_token_bucket.lua
Settings WHATSAPP_RATE_PER_SECOND = 1.0
๐ง Reliability & Idempotency
-
Each message is stored with a unique idempotency_key
-
Retries use the same key to avoid duplicate delivery
-
Failed messages persist for visibility and can be retried manually
Celery Task Behavior
- Exponential backoff retry (2^n seconds)
- acks_late=True to avoid loss on worker crash
- Max 8 retries before marking message as failed
๐ Webhook Security
-
Optional HMAC verification (X-Hub-Signature-256)
-
Prevents spoofed or replayed requests
-
Use your Facebook App Secret for signing
๐งฉ Database Schema
WhatsAppMessage
| Field | Type | Notes |
|---|---|---|
| recipient | CharField |
phone number |
| message_type | text / template |
message category |
| payload | JSONField |
message body / components |
| status | queued / sent / failed / delivered |
lifecycle state |
| idempotency_key | UUID |
prevents duplicates |
| attempts | Integer |
number of retries |
| created_at | DateTime |
timestamp |
WhatsAppWebhookEvent
| Field | Type | Description |
|---|---|---|
| event_id | CharField |
deduplication key |
| payload | JSONField |
raw webhook payload |
| processed | Boolean |
flag to avoid re-handling |
Includes:
-
Webhook verification test
-
Event persistence test
(Extendable for rate limiter and Celery integration)
๐งฑ Deploying
Recommended environment:
-
PostgreSQL
-
Redis 7+
-
Gunicorn with 2โ4 workers
-
Celery worker pool (concurrency >= 4)
-
Nginx reverse proxy for SSL termination
Production tips:
-
Use environment variables for tokens
-
Rotate access tokens periodically
-
Enable HTTPS and secure webhook secret
๐ก Extending Functionality
-
Add custom event handlers via register_handler in commands.py
-
Extend rate limiter for per-tenant quotas
-
Plug in Prometheus metrics to monitor message throughput
-
Integrate with an internal analytics pipeline via Celery chains
๐ Performance Best Practices
-
Use persistent Redis connection pools (max_connections=100)
-
Deploy Celery worker with concurrency matching CPU cores
-
Shard messages across multiple phone numbers if exceeding rate limits
-
Use DB connection pooling (e.g. pgBouncer)
-
Enable GZIP compression on webhook endpoints for large payloads
๐ License
MIT License ยฉ 2025 OFFSIDE INTEGRATED TECHNOLOGY (Somtochukwu Emmanuel)
๐ค Contributing
Fork this repo
Create a feature branch
git checkout -b feature/awesome
Commit changes
git commit -m 'Add awesome feature'
Push branch and open a PR ๐
๐ Support
For enterprise inquiries, please contact offsideint@gmail.com
For bugs, open an issue on GitHub.
Built with โค๏ธ by OFFSIDE INTEGRATED TECHNOLOGY โ because WhatsApp deserves enterprise-grade Django integration.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file whatsapp_integration-0.1.0.tar.gz.
File metadata
- Download URL: whatsapp_integration-0.1.0.tar.gz
- Upload date:
- Size: 16.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3f46f647d633dc0ca4c6f7e5aaa707adc2b477a3b4c7b999fceddbbb0737186e
|
|
| MD5 |
8c186095e4f7871895ae430059c5443b
|
|
| BLAKE2b-256 |
a003cdc0f62615f97f2c4f16787c62b3ed6b250e9d90baa783defce9e30cc636
|
File details
Details for the file whatsapp_integration-0.1.0-py3-none-any.whl.
File metadata
- Download URL: whatsapp_integration-0.1.0-py3-none-any.whl
- Upload date:
- Size: 17.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2a3eba73f541d720f3974e0404619c01be76e78935b642f8317015fe2ec7623c
|
|
| MD5 |
4ff9893e0f99cd9793714e44d7713ee2
|
|
| BLAKE2b-256 |
65b94f099fb410eeb96906f0574ec614d9fe82e69b05777cc00a35d72a6fc6c8
|