Technical
Odoo Webhooks: Signature Checks, Idempotency and Background Queues
A practical design for receiving webhooks in Odoo: a thin controller, HMAC signature checks, idempotency keys backed by a unique constraint, and a cron-driven queue for the heavy work.
Kalvyai Engineering · · Updated · 7 min read

On this page
Most webhook problems in Odoo are not caused by the sender. They come from a receiving controller that does too much inside the HTTP request. It validates nothing, processes the payload inline, times out, gets retried, and creates a second invoice.
This post walks through a design we use when we build integrations on Odoo. It has four parts:
- A thin controller that only validates and stores the event.
- A signature check on the raw request body.
- An idempotency key enforced by the database.
- A background processor that does the real work, with retries.
The code targets recent Odoo versions. Where an API differs between versions, it is marked so you can check it against your own version.
Why the request should do almost nothing
Webhook senders usually wait a limited time for a response. If they do not get a 2xx answer in time, they retry. The exact timeout and retry schedule depend on the provider, so check their documentation: the response timeout and retry schedule given in your provider's webhook documentation.
If your controller creates sale orders, reconciles payments or calls another API before it answers, three things go wrong:
- Slow requests cause timeouts, and the provider retries an event you are still processing.
- An exception halfway through rolls back the transaction, and you lose the event entirely.
- A burst of events ties up your Odoo HTTP workers, which slows the system for real users.
The fix is to split receiving from processing. The controller checks the signature, writes one row, and returns 200. Everything else happens later.
Step 1: A thin controller
Use type='http' so you get the raw body. Webhooks are plain HTTP POSTs, not Odoo JSON-RPC calls. Disable CSRF, because the sender has no Odoo session.
import hashlib
import hmac
import json
import logging
from odoo import http
from odoo.http import request, Response
_logger = logging.getLogger(__name__)
def _valid_signature(raw_body, sent_signature, secret):
expected = hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, sent_signature or '')
class AcmeWebhookController(http.Controller):
@http.route('/webhooks/acme', type='http', auth='public',
methods=['POST'], csrf=False)
def receive(self, **kwargs):
raw = request.httprequest.get_data()
secret = request.env['ir.config_parameter'].sudo().get_param(
'acme.webhook_secret')
sent = request.httprequest.headers.get('X-Acme-Signature')
if not secret or not _valid_signature(raw, sent, secret):
_logger.warning('Acme webhook rejected: bad signature')
return Response(status=401)
try:
payload = json.loads(raw)
except ValueError:
return Response(status=400)
event_id = payload.get('id')
if not event_id:
return Response(status=400)
request.env['acme.webhook.event'].sudo().register(
event_id, payload.get('type'), raw.decode('utf-8'))
return Response(status=200)A few design notes:
auth='public'gives you an environment running as the public user. Usesudo()only for the narrow writes you need, not for the whole handler.- Multi-database servers. The route needs to resolve to one database. On a server with several databases, configure
dbfilterso the webhook hostname maps to the right one. - Secret storage. The example reads the secret from a system parameter. If you have several provider accounts, store the secret on a configuration record instead. Never hardcode it.
- Header name and format.
X-Acme-Signatureis a placeholder. Each provider has its own header and encoding: the signature header name and encoding your provider documents. - Duplicates still return 200. If the event was already received, the sender should stop retrying. Returning an error for a duplicate just causes more retries.
Step 2: Verify the signature on the raw body
Most providers sign the request with HMAC-SHA256 using a shared secret. The details that trip people up:
- Sign the raw bytes, not parsed JSON. If you parse and re-serialise the payload, key order and whitespace change, and the signature never matches. That is why the controller calls
get_data()before anything else. - Use
hmac.compare_digest. A normal==comparison can leak timing information. - Match the provider's encoding. Some send hex, some base64, some prefix the value (for example
sha256=...). Compare in the same format.
Timestamps and replay protection
Some providers include a timestamp and sign timestamp + '.' + body. If yours does, reject requests whose timestamp is too old. This stops someone from replaying a captured request later.
import time
MAX_SKEW_SECONDS = 300 # pick a tolerance that matches the provider's guidance
def _valid_timestamped_signature(raw_body, timestamp, sent_signature, secret):
try:
ts = int(timestamp)
except (TypeError, ValueError):
return False
if abs(time.time() - ts) > MAX_SKEW_SECONDS:
return False
signed = f'{ts}.'.encode() + raw_body
expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, sent_signature or '')The exact string that gets signed varies by provider: the signed-payload format your provider documents. Get this from their documentation, not from guesswork.
If the provider does not sign requests
Some senders offer no signature. Options in rough order of preference:
- Treat the webhook as a notification only. Take the object ID from the payload and fetch the real data from the provider's API with your own credentials.
- Use a long random token in the URL path and rotate it when staff change.
- Restrict by source IP at the reverse proxy, if the provider publishes stable ranges.
Option 1 is worth using even when signatures exist, for anything involving money.
Step 3: Idempotency keys enforced by the database
Providers deliver at least once. You will receive duplicates, and sometimes two copies arrive at the same moment on different workers. A Python check like if not search([...]): create(...) does not protect you, because both workers can pass the check before either commits.
Let PostgreSQL enforce it with a unique constraint on the provider's event ID.
from datetime import timedelta
from psycopg2 import IntegrityError
from odoo import api, fields, models
class AcmeWebhookEvent(models.Model):
_name = 'acme.webhook.event'
_description = 'Acme webhook event'
_order = 'id'
event_id = fields.Char(required=True, index=True)
event_type = fields.Char()
payload = fields.Text(required=True)
state = fields.Selection(
[('pending', 'Pending'), ('done', 'Done'), ('failed', 'Failed')],
default='pending', required=True, index=True)
attempts = fields.Integer(default=0)
next_attempt_at = fields.Datetime(default=fields.Datetime.now, index=True)
last_error = fields.Text()
_sql_constraints = [
('event_id_uniq', 'unique(event_id)', 'Webhook event already received.'),
]
@api.model
def register(self, event_id, event_type, payload):
try:
with self.env.cr.savepoint():
self.create({
'event_id': event_id,
'event_type': event_type,
'payload': payload,
})
except IntegrityError:
return False # duplicate delivery, already stored
self.env.ref('acme_webhooks.cron_process_webhooks').sudo()._trigger()
return TrueNotes:
- The savepoint matters. Without it, the failed insert aborts the whole transaction and the controller cannot return cleanly.
- Version check: newer Odoo versions replace
_sql_constraintswithmodels.Constraintdeclarations. Use the constraint syntax that your Odoo version's ORM documentation shows. Also confirmir.cron._trigger()is available in your version; if not, the cron simply picks up the row on its next scheduled run. - If one Odoo database receives webhooks from several accounts of the same provider, make the key
unique(account_id, event_id). Event IDs are only unique within one account. - If the provider sends no event ID, build a key from fields that identify the change, such as object ID plus an updated timestamp, or a hash of the body. A body hash is weaker, because a retried delivery can differ slightly.
Idempotency inside the handler too
The constraint stops the same event being stored twice. It does not stop two different events from describing the same change, for example a payment.captured event and a later payment.updated event that both say "paid". The handler should check state before acting: if the invoice is already paid, do nothing. Treat "already done" as success.
Step 4: Process events in the background
Now the heavy work moves out of the request. A scheduled action processes pending rows. Here is the cron definition:
<odoo>
<record id="cron_process_webhooks" model="ir.cron">
<field name="name">Process Acme webhooks</field>
<field name="model_id" ref="model_acme_webhook_event"/>
<field name="state">code</field>
<field name="code">model._process_pending()</field>
<field name="interval_number">5</field>
<field name="interval_type">minutes</field>
</record>
</odoo>The _trigger() call in register asks Odoo to run it soon. The regular interval is a safety net for anything the trigger missed and for scheduled retries.
And the processor:
MAX_ATTEMPTS = 5
@api.model
def _process_pending(self, limit=50):
for _ in range(limit):
self.env.cr.execute("""
SELECT id FROM acme_webhook_event
WHERE state = 'pending'
AND next_attempt_at <= (now() AT TIME ZONE 'UTC')
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED
""")
row = self.env.cr.fetchone()
if not row:
break
event = self.browse(row[0])
try:
with self.env.cr.savepoint():
event._handle()
event.write({'state': 'done', 'last_error': False})
except Exception as exc:
attempts = event.attempts + 1
event.write({
'attempts': attempts,
'last_error': str(exc),
'state': 'failed' if attempts >= self.MAX_ATTEMPTS else 'pending',
'next_attempt_at': fields.Datetime.now()
+ timedelta(minutes=2 ** attempts),
})
self.env.cr.commit()
def _handle(self):
self.ensure_one()
# Parse self.payload and update Odoo records here.
# Check current state first so repeated runs are harmless.
raise NotImplementedErrorWhy it is built this way:
- One row at a time with
FOR UPDATE SKIP LOCKED. If two cron workers run at once, they pick different rows. Selecting one row per loop also means each commit releases only the lock on the row just processed. - A savepoint per event. A failure in one event rolls back only that event's changes, and the error is still recorded.
- A commit per event. Progress is kept even if the cron is killed halfway through a batch. Explicit commits are normal in cron code, but never do this inside the controller.
- Exponential backoff. Temporary failures, like a locked record or a downstream API outage, get retried after 2, 4, 8 minutes and so on. After the limit, the row is marked
failedfor a person to review. - Odoo stores datetimes in UTC without a time zone, so the SQL compares against
now() AT TIME ZONE 'UTC'.
Using a job queue module instead
If your database already uses the community queue_job module from the OCA, you can call with_delay() on the processing method instead of running a cron. You get its job views and retry handling. Keep the event table and unique constraint anyway: the job queue handles execution, while the event table is your idempotency record and audit trail.
Ordering and stale data
Webhooks can arrive out of order. An order.updated event can land before order.created, or two updates can swap places. Ways to handle this:
- Compare an
updated_ator version field in the payload against what you stored last, and skip older updates. - If a referenced record does not exist yet, raise an error so the event is retried later, instead of creating a half-empty record.
- For important objects, fetch the current state from the provider's API inside
_handle(), rather than trusting the payload snapshot.
Operations: make failures visible
A queue nobody looks at is just a slower way to lose data. Add:
- A list view of webhook events filtered by
state = failed, with the error text. - A "Retry" button that resets
statetopending,attemptsto 0 andnext_attempt_atto now. - A cleanup cron that deletes
doneevents after a retention period your business agrees on, since payloads can contain customer data. - An alert, by email or activity, when failed events pile up.
If you would rather not build the monitoring layer for your store integrations yourself, our ConnectIQ app gives you unified multi-store sync telemetry, queue tracking and AI error diagnostics in Odoo.
Checklist
- Controller uses
type='http',csrf=False, POST only. - Signature verified on the raw body with
hmac.compare_digest. - Timestamp checked when the provider signs one.
- Event stored with a database-level unique constraint on the idempotency key.
- Duplicates return 200.
- Heavy work runs in a cron or job queue, never in the request.
- Each event processed in its own savepoint, with retries and backoff.
- Handler checks current state so re-running it is harmless.
- Failed events are visible and retryable.
How Kalvyai can help
We build and maintain Odoo integrations with payment gateways, marketplaces, accounting tools and messaging platforms, including the webhook receivers, queues and monitoring described here. You can see our Odoo work at kalvyai.com/odoo and our ready-made apps at store.kalvyai.com.
If you have an integration that drops or duplicates events, or you are planning a new one, contact us and we will review your setup.
Last updated 20 Nov 2026
- Odoo
- Webhooks
- Integrations
- Python
- Idempotency
- Background Jobs
Kalvyai Engineering · Engineering team
The engineers who build, connect and fix business systems at Kalvyai: Odoo, ERPNext, Shopify and AI agents that work inside them with approvals, budgets and an audit trail.



Comments
No comments yet. Questions and corrections are welcome.
Rate this post or leave a comment