DEV Community

Cover image for Handling High-Concurrency Pub/Sub Webhooks and End-to-End AdTech Telemetry in Odoo
Александр «MBIT» Балаш
Александр «MBIT» Балаш

Posted on Originally published at dlab.md

Handling High-Concurrency Pub/Sub Webhooks and End-to-End AdTech Telemetry in Odoo

In modern enterprise architectures, the ERP is no longer an isolated operational island. It serves as the transactional anchor of an omnichannel ecosystem, continuously ingesting high-velocity event streams: incoming WhatsApp messaging webhooks, Google Cloud Pub/Sub message queues, Content Security Policy (CSP) browser violation reports, and programmatic advertising telemetry from Google Ad Manager (GAM).

Operating real-time telemetry and asynchronous webhook endpoints on top of an enterprise Python/PostgreSQL framework like Odoo presents acute engineering challenges. By default, Odoo’s web controllers are optimized for synchronous user interactions. When subjected to bursty, high-concurrency event ingestion, naive implementations rapidly trigger four failure modes:

  1. Message queues guarantee at-least-once delivery, so duplicate webhook deliveries under high concurrency trigger race conditions that process the same payment or inventory reservation multiple times when idempotency checks are missing.
  2. Combining server-side rendered (SSR) advertising slots with Odoo's single-page application (SPA) frontend framework allows direct DOM manipulation by third-party scripts to cause memory leaks, zombie event listeners, and OWL virtual DOM reconciliation crashes.
  3. Unchecked browser telemetry endpoints (such as /csp-violation) open dedicated database cursors on every bot scan, exhausting PostgreSQL connection pools (db_maxconn) and bringing the core business application offline.
  4. Automation agents communicating over XML-RPC discover that rich HTML notes posted to Discuss threads have their markup escaped into visible <div> entities due to internal markupsafe.Markup boundaries.

This production post-mortem documents our architectural solutions to these four challenges, detailing the exact patterns deployed across our production infrastructure.

📊 Interactive Engineering Benchmark: Explore the live chart, matrix & dataset in the full report on Dlab.md →

Why Pub/Sub Ingestion Requires type='http'

When integrating Google Cloud Pub/Sub push subscriptions with Odoo, junior developers instinctively configure controller routes using Odoo's native JSON decorator:

@http.route('/webhook/push', type='json', auth='public', methods=['POST'])
def receive_push(self):
    data = request.jsonrequest
    # ... business processing ...
Enter fullscreen mode Exit fullscreen mode

Production Alert:
When handling push webhooks from message brokers like Google Cloud Pub/Sub, declaring Odoo controller routes with type='json' is an architectural failure. When an unhandled exception occurs inside a type='json' route, Odoo's dispatcher catches the error and returns a status 200 OK containing a JSON-RPC error payload. Pub/Sub interprets 200 OK as a successful message acknowledgment (ack), permanently dropping failed events and discarding mission-critical financial webhooks.

The Architectural Trap

Under Odoo's HTTP dispatch engine (odoo.http.JsonRequest), any Python exception raised during the execution of a type='json' route is caught by the internal RPC wrapper. Odoo formats the traceback into a JSON-RPC error structure:

{"jsonrpc": "2.0", "id": null, "error": {"code": 200, "message": "Odoo Server Error", "data": {...}}}
Enter fullscreen mode Exit fullscreen mode

Even when an unhandled exception occurs, Odoo sets the HTTP response status code to 200 OK.

Google Cloud Pub/Sub operates on standard HTTP status codes:

  • Status codes HTTP 200, 201, or 204 acknowledge the message (ack), instructing Pub/Sub to remove it from the subscription queue.
  • Status codes HTTP 500, 503, or 429 signal a failed delivery (nack), instructing Pub/Sub to retain the message and retry delivery according to its configured exponential backoff policy (e.g., retrying up to 7 days).

Because Odoo returns HTTP 200 OK even when a database deadlock, serialization failure, or unexpected null pointer occurs, Pub/Sub considers the message successfully delivered and permanently purges it from the queue. Critical financial webhooks, payment confirmations, and customer orders are silently lost forever.

The Production Solution

Webhook ingestion endpoints must strictly use @http.route(..., type='http'). This allows the developer to exert granular, manual control over the HTTP status response:

# -*- coding: utf-8 -*-
from odoo import http, fields
from odoo.http import request, Response
import logging
import uuid
import hmac
import hashlib

_logger = logging.getLogger(__name__)

class PubSubController(http.Controller):

    # MUST use type='http'. type='json' traps exceptions in 200 OK, breaking backoff retries.
    @http.route('/dlab/webhook/pubsub_push/<string:token>', 
                type='http', auth='public', methods=['GET', 'POST'], csrf=False)
    def receive_pubsub_push(self, token, **post):
        try:
            # 1. Bearer Token Verification
            expected_token = request.env['ir.config_parameter'].sudo().get_param(
                'dlab.pubsub_token', default='invalid_default'
            )
            if token != expected_token:
                _logger.warning("Unauthorized webhook access attempt with invalid token.")
                return Response("Forbidden", status=403)

            # 2. Extract JSON Payload & Headers
            json_data = request.get_json_data()
            if not json_data:
                return Response("Empty Payload", status=400)

            raw_body = request.httprequest.get_data()
            meta_sig = request.httprequest.headers.get('X-Hub-Signature-256')
            trace_id = f"msg_{uuid.uuid4().hex[:8]}"

            # 3. Cryptographic Signature Gate (Meta / WhatsApp Webhooks)
            if meta_sig:
                app_secret = request.env['ir.config_parameter'].sudo().get_param('dlab.meta.app_secret', default='')
                expected_hash = hmac.new(app_secret.encode('utf-8'), raw_body, hashlib.sha256).hexdigest()
                expected_sig = f"sha256={expected_hash}"

                if not hmac.compare_digest(expected_sig, meta_sig):
                    _logger.critical("HMAC Signature verification failed!")
                    return Response("Invalid Signature", status=403)

                channel_type = "whatsapp"
                message_id = json_data['entry'][0]['changes'][0]['value']['messages'][0]['id']

            # 4. Standard GCP Pub/Sub Ingestion
            elif 'message' in json_data and 'messageId' in json_data['message']:
                channel_type = "gcp_pubsub"
                message_id = json_data['message']['messageId']
            else:
                return Response("Unprocessable Entity", status=422)

            # 5. Atomic Idempotency Verification
            IdempotencyLog = request.env['dlab.idempotency.log'].sudo()
            if IdempotencyLog.is_processed(message_id, channel_type):
                _logger.info("Duplicate message %s safely dropped.", message_id)
                return Response("Duplicate Ack", status=200)

            # 6. Dispatch Payload to Business Layer
            success = request.env['dlab.pubsub.normalizer'].sudo().process_payload(
                channel_type, json_data, trace_id
            )
            if not success:
                # Trigger Pub/Sub retry via HTTP 500
                _logger.error("Downstream processing failed for message %s", message_id)
                return Response("Internal Processing Failure", status=500)

            return Response("OK", status=200)

        except Exception as e:
            _logger.exception("Fatal unhandled exception in webhook handler: %s", str(e))
            # Critical: Return 500 so Pub/Sub initiates exponential backoff
            return Response("Internal Server Error", status=500)
Enter fullscreen mode Exit fullscreen mode

Preventing Single-Page Application (SPA) Memory Leaks in the OWL Framework

When integrating enterprise advertising engines (such as Google Ad Manager via gpt.js) into an Odoo modern website, architects frequently encounter severe memory leaks and virtual DOM reconciliation crashes.

Client-Side SPA Transitions vs External Script Mutators

In standard Odoo Website themes, page navigation utilizes an asynchronous client-side routing engine (@web/legacy/js/public/public_widget or native OWL components). When a user clicks a blog post link, the browser does not perform a full page reload; instead, the SPA engine fetches the inner HTML of #wrap and swaps the DOM elements dynamically.

Third-party scripts like Google Publisher Tag (googletag) maintain their own internal global registries of active advertising slots:

window.googletag.defineSlot('/1234567890/ad_unit', [300, 250], 'div-gpt-ad-1');
Enter fullscreen mode Exit fullscreen mode

When an Odoo user navigates from Article A to Article B:

  1. The DOM elements containing div-gpt-ad-1 are removed by Odoo's SPA engine.
  2. The new page HTML is injected, declaring a new div-gpt-ad-1.
  3. If the developer's client-side widget simply resets its local variable window.dlab_defined_slots = {}, the slots remain permanently registered inside googletag's internal memory.
  4. When googletag.display('div-gpt-ad-1') is called on the new page, the Google Publisher Tag engine panics with: Error: Slot 'div-gpt-ad-1' was already registered on this page.
  5. Stale closure references retain full DOM node subtrees in memory, triggering aggressive browser memory growth (leaking up to 50 MB per client-side navigation).

📊 Interactive Engineering Benchmark: Explore the live chart, matrix & dataset in the full report on Dlab.md →


📐 Continue Reading the Full Engineering Benchmark on Dlab.md

This architectural excerpt covers the core problem statement and primary failure modes. The complete engineering report on Dlab.md includes:

  • Interactive Chart.js telemetry benchmarks & 36-month TCO comparison matrices;
  • Production PostgreSQL / Odoo 19 implementation patterns and verification checklists;
  • Executive CISO, CFO & Principal Architect technical FAQ.

👉 Read the Complete Engineering Breakdown & Interactive Charts on Dlab.md →

🛸 Open the Interactive 3D Open-Core ERP & 36-Month TCO Simulator on Dlab Shuttle →

💬 Discuss This Architecture 24/7 with Echo AI in Telegram →

Top comments (0)