DEV Community

Cover image for Odoo Development Services: Idempotent Webhook Receivers in Odoo 18
Sanya Mittal
Sanya Mittal

Posted on

Odoo Development Services: Idempotent Webhook Receivers in Odoo 18

A payment gateway retries a failed webhook for days, and your Odoo endpoint treats every retry as a new payment. The result is duplicate postings, double stock reservations, and finance teams reconciling by hand. This happens whenever an external system calls an Odoo controller and the response is slow or lost. Odoo development services for integrations must assume that every inbound call can arrive more than once. This article shows the pattern we use in Odoo 18 with Python and PostgreSQL, drawn from how Odoo development services handle integrations in production.

Context and Setup

The scenario is a gateway posting JSON events to /webhook/payments, an Odoo 18 database on PostgreSQL, and a sale order that must become paid exactly once. Delivery guarantees are the root issue. Stripe retries live-mode webhook deliveries for up to three days with exponential backoff, and it does not guarantee event order (Stripe documentation, 2026).

You need a custom addon, the gateway's signing secret stored in ir.config_parameter, and an event payload that carries a stable unique ID.

How Odoo Development Services Make Webhook Handlers Idempotent

Idempotent means the same event produces the same result however many times it arrives. In Odoo, the reliable way to get that is a unique database constraint, not a Python existence check.

Step 1: Store Every Event Behind a Unique Constraint

A check-then-insert pattern races. Two retries arriving together can both run search(), find nothing, and both process the event. A unique index closes that gap, because the second insert waits for the first transaction and then fails.

python
from odoo import fields, models

class WebhookEvent(models.Model):
_name = "webhook.event"
_description = "Inbound webhook event"

provider = fields.Char(required=True)
event_id = fields.Char(required=True)

# Why: PostgreSQL, not Python, decides which concurrent delivery wins
_sql_constraints = [
    ("event_uniq", "unique(provider, event_id)", "Event already received"),
]
Enter fullscreen mode Exit fullscreen mode

Step 2: Verify, Deduplicate, and Process in One Transaction

The controller does four things in order:

Verify the HMAC signature against the raw request body.
Insert the event row inside a savepoint.
On a unique violation, return 200 so the sender stops retrying.
Otherwise apply the business change in the same transaction.
python
import hashlib, hmac, json
import psycopg2.errors
from odoo import http
from odoo.http import request
from odoo.tools import mute_logger

class PaymentWebhook(http.Controller):

@http.route("/webhook/payments", type="http", auth="public",
            methods=["POST"], csrf=False)
def receive(self):
    raw = request.httprequest.get_data()  # Why: signature covers raw bytes, not parsed JSON
    env = request.env(su=True)
    secret = env["ir.config_parameter"].get_param("payments.webhook_secret", "")
    expected = hmac.new(secret.encode(), raw, hashlib.sha256).hexdigest()
    sent = request.httprequest.headers.get("X-Signature", "")
    if not hmac.compare_digest(expected, sent):  # Why: constant-time compare blocks timing attacks
        return request.make_response("invalid signature", status=401)

    event = json.loads(raw)
    try:
        # Why: the savepoint keeps a failed insert from aborting the outer transaction
        with mute_logger("odoo.sql_db"), env.cr.savepoint():
            env["webhook.event"].create(
                {"provider": "payments", "event_id": event["id"]})
    except psycopg2.errors.UniqueViolation:
        return request.make_response("duplicate", status=200)  # Why: 2xx stops sender retries

    # Why: an exception here rolls back the event row too, so the next retry runs clean
    env["sale.order"]._apply_payment_event(event)
    return request.make_response("ok", status=200)
Enter fullscreen mode Exit fullscreen mode

Step 3: Weigh Trade-offs in Odoo Development Services

Inline processing keeps the event row and the business change atomic, but the sender's timeout limits how much work fits in the request. For heavier work, store the event and hand it to a queue such as OCA queue_job. The cost is that deduplication and state changes become separate steps.

Because delivery order is not guaranteed, write _apply_payment_event to compare state transitions, not arrival times. Also schedule a cron job that purges old event rows so the table stays small.

Real-World Application

In one of our Odoo development projects at Oodles, a client saw duplicate payment postings after gateway retries. We added the event table, the signature check, and the single-transaction handler described above.

Key Takeaways
Put idempotency in a PostgreSQL unique constraint, because a Python existence check races under concurrent retries.
Verify HMAC signatures on the raw request bytes before parsing JSON.
Wrap the event insert in a savepoint so a duplicate does not abort the outer transaction.
Return 2xx for duplicates and non-2xx for real failures, so rollback and retry stay consistent.
Design handlers around state transitions, not event timestamps, because delivery order is not guaranteed.

Have you hit duplicate webhook postings in Odoo? Share your retry setup in the comments, or talk to us about Odoo development services.

What are Odoo development services?
Odoo development services cover custom modules, third-party integrations, data migration, reporting, and version upgrades. For integrations, the work includes controllers, API clients, and handlers that stay correct when external systems retry or reorder calls.

Why do webhook providers send duplicate events?
In Odoo Development Services Providers retry whenever they receive a non-2xx response, a timeout, or no response. A lost reply therefore looks like a failure, and the same event is delivered again. Receivers must tolerate repeats.

Should Odoo webhook handlers use queue_job?
Use it when processing exceeds the sender's timeout. Store the event first, enqueue the work, and return 200. Keep the unique constraint on the event table, so duplicate deliveries never create duplicate jobs.

How do I secure an Odoo webhook controller?
Verify an HMAC signature computed over the raw body, compare it with hmac.compare_digest, and keep the secret in ir.config_parameter. Use separate secrets for test and live endpoints, and reject unexpected event types.

Is csrf=False safe on a webhook route?
CSRF protects browser sessions, and webhook callers have none. With auth="public", the HMAC signature check replaces CSRF protection. Without that check, csrf=False leaves the endpoint open to forged requests.

Top comments (0)