Skip to main content

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_text and send_template with 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
  • migrate
python manage.py migrate
  • 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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

whatsapp_integration-0.2.0.tar.gz (16.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

whatsapp_integration-0.2.0-py3-none-any.whl (17.5 kB view details)

Uploaded Python 3

File details

Details for the file whatsapp_integration-0.2.0.tar.gz.

File metadata

  • Download URL: whatsapp_integration-0.2.0.tar.gz
  • Upload date:
  • Size: 16.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.3

File hashes

Hashes for whatsapp_integration-0.2.0.tar.gz
Algorithm Hash digest
SHA256 92d747234dbeae4406b85e2d2ac45511d511ae9c58d4b2cbb5c0a5d100e643de
MD5 87ee83cd4c93394fb44d7678de47cc07
BLAKE2b-256 5c9cf72a617e30f6e723efc0197da9b68bae737136dfb98af4e93878cfd95e44

See more details on using hashes here.

File details

Details for the file whatsapp_integration-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for whatsapp_integration-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0d454469e8850e72f49f473fcec8bf0a1744136b9fcb1c70e9f46eda78915889
MD5 9b4a6cf6d14224ca24c63f3cdf605027
BLAKE2b-256 862af0963ae37899c6db46946d62c245dde48c72d15c9d537e3bcb12caafd1b5

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page