Gemini Webhooks: Signature Verification, Idempotent Callbacks, and Async Job Recovery
Verify Gemini API Standard Webhooks signatures, rotate signing secrets with grace periods, deduplicate callback deliveries, and pace output downloads.

Polling long-running AI operations—such as Gemini Batch API jobs, asynchronous Interactions, or video generation—wastes worker threads and adds unnecessary request volume when jobs take minutes or hours to finish. Google's Gemini Webhooks API pushes thin event notifications (batch.succeeded, batch.failed, interaction.completed, video.generated) to your HTTPS callback URI using the Standard Webhooks signing specification. However, an unguarded webhook listener can easily fail under duplicate deliveries, lost signing secrets, or downstream HTTP 429 storms when hundreds of completed batch jobs trigger follow-up API calls at once.
This guide covers end-to-end webhook engineering for Gemini and asynchronous AI pipelines: verifying Standard Webhooks HMAC signatures, rotating signing secrets with a 24-hour grace period, deduplicating thin event payloads via an idempotency ledger, and queuing follow-up artifact downloads safely.
Understand the Gemini Webhooks contract and thin event payloads
In Google's official Gemini Webhooks guide and Webhooks API reference, registering a webhook via client.webhooks.create() returns a new_signing_secret only once. Incoming POST deliveries use Standard Webhooks headers (webhook-id, webhook-timestamp, webhook-signature) and deliver a thin notification payload containing the event type and resource metadata (such as data.id and data.output_file_uri), not the multi-megabyte batch output itself.
| Event type or mechanism | What the callback delivers | Common implementation mistake | Production listener requirement |
|---|---|---|---|
Signature verification (webhook-id, webhook-timestamp, webhook-signature) |
HMAC-SHA256 signature over "{webhook_id}.{timestamp}.{raw_body}" |
Parsing JSON before verifying raw bytes or ignoring timestamp replay window | Verify raw request body and 5-minute timestamp tolerance before any state change |
Secret rotation (webhooks.rotate_secret) |
Issues a new signing secret with optional immediate revocation or 24-hour grace period | Overwriting the old secret in env vars before in-flight callbacks drain | Accept signatures matching either current_secret or previous_secret during the 24h rotation window |
batch.succeeded / video.generated |
Resource ID and output_file_uri |
Downloading and parsing 500MB output files synchronously inside the HTTP callback thread | Persist event to durable queue, return 200 OK in < 200ms, and fetch output_file_uri asynchronously |
batch.failed |
Resource ID and failure notification | Immediately re-submitting the entire failed batch inline | Route to dead letter queue triage and inspect item-level errors |
interaction.completed |
Completed interaction/agent ID | Triggering unpaced follow-up LLM calls for every callback simultaneously | Enqueue follow-up calls through queue admission control |
When integrating webhook-driven automations in n8n or backend services alongside Claude Code and Cursor, review the API429 documentation, model catalog, pricing page, and Google provider guide.
Four reliability rules for webhook listeners
- Verify signatures against raw body bytes and support dual-secret rotation: Because network proxies or JSON re-serializers alter whitespace, always compute or verify the Standard Webhooks signature against the exact raw UTF-8 request body. Store both your active signing secret and the expiring secret during Google's 24-hour grace period so zero callbacks are dropped during rotation.
- Deduplicate by
webhook-idand resource state transition: Webhook senders use at-least-once delivery; if your listener takes too long or a network ACK drops, the exact samebatch.succeededevent will arrive again. Record(webhook_id, event_type, resource_id)in your idempotency store and return an idempotent200 OKif already processed. - Never confuse HTTP 200 callback delivery with job success: A
batch.failedevent is delivered as a valid signedPOSTrequest that your listener must acknowledge with200 OKso the sender stops retrying the notification—while your application marks the batch job failed in its own state machine. - Keep fallback polling for reconciliation: Webhooks reduce polling overhead by 95%+, but firewall misconfigurations or endpoint downtime can still miss an event. Run a low-frequency reconciliation sweep for jobs stuck in
runningpast their expected SLA.
Pacing downstream artifact downloads and follow-up model calls
A subtle failure mode occurs after your webhook listener properly verifies and enqueues a `batch.succeeded` or `interaction.completed` event: if 300 batch jobs finish during the same minute or a single batch output file contains 10,000 completed rows that each trigger a downstream embedding or classification request, your post-processing workers can self-inflict an internal queue collapse or upstream `HTTP 429` wave.
Design the post-webhook worker pipeline with three explicit controls:
- Stream-parse large output files: When downloading `output_file_uri` from a completed batch job, stream and parse the JSONL file line by line with bounded memory rather than loading hundreds of megabytes into a single worker process.
- Enforce item-level schema validation before DB commit: Batch outputs can still contain individual rows that hit `MAX_TOKENS`, safety stops, or malformed JSON. Validate every row through your structured-output pipeline rules and route only failed rows to the dead letter queue.
- Pace follow-up API dispatches: If webhook completion triggers a second-stage model call (such as translating or summarizing the result), feed those second-stage jobs into your adaptive throttle controller rather than executing them at the burst speed of incoming webhooks.
Runnable offline Python Standard Webhooks verifier and deduplicator
The following self-contained Python 3.10+ module implements RFC/Standard-Webhooks HMAC-SHA256 verification (with timestamp replay bounds and dual-secret rotation support) plus idempotent thin-payload routing using only the Python standard library:
from __future__ import annotations
import base64
from dataclasses import dataclass
import hashlib
import hmac
import json
from typing import Mapping
@dataclass(frozen=True)
class WebhookProcessResult:
http_status: int
action: str # "enqueued_output_fetch", "routed_to_dlq", "duplicate_ignored", "rejected_signature"
resource_id: str | None
output_uri: str | None
reason: str
def sign_standard_webhook(secret_b64: str, msg_id: str, timestamp: str, raw_body: str) -> str:
raw_secret = base64.b64decode(secret_b64.removeprefix("whsec_"))
to_sign = f"{msg_id}.{timestamp}.{raw_body}".encode("utf-8")
digest = hmac.new(raw_secret, to_sign, hashlib.sha256).digest()
return "v1," + base64.b64encode(digest).decode("ascii")
def verify_standard_webhook(
*,
raw_body: str,
headers: Mapping[str, str],
active_secrets_b64: tuple[str, ...],
now_epoch: int,
tolerance_s: int = 300,
) -> bool:
msg_id = headers.get("webhook-id", "")
ts_str = headers.get("webhook-timestamp", "")
sig_header = headers.get("webhook-signature", "")
if not msg_id or not ts_str.isdigit() or not sig_header:
return False
ts = int(ts_str)
if abs(now_epoch - ts) > tolerance_s:
return False
offered_sigs = [part.strip() for part in sig_header.split(" ") if part.strip().startswith("v1,")]
for secret in active_secrets_b64:
expected = sign_standard_webhook(secret, msg_id, ts_str, raw_body)
if any(hmac.compare_digest(expected, candidate) for candidate in offered_sigs):
return True
return False
def handle_gemini_webhook(
*,
raw_body: str,
headers: Mapping[str, str],
active_secrets_b64: tuple[str, ...],
seen_webhook_ids: set[str],
now_epoch: int,
) -> WebhookProcessResult:
if not verify_standard_webhook(
raw_body=raw_body, headers=headers, active_secrets_b64=active_secrets_b64, now_epoch=now_epoch
):
return WebhookProcessResult(400, "rejected_signature", None, None, "invalid_signature_or_stale_timestamp")
msg_id = headers["webhook-id"]
if msg_id in seen_webhook_ids:
return WebhookProcessResult(200, "duplicate_ignored", None, None, "webhook_id_already_recorded")
event = json.loads(raw_body)
seen_webhook_ids.add(msg_id)
event_type = event.get("type", "")
data = event.get("data") or {}
res_id = data.get("id")
uri = data.get("output_file_uri")
if event_type in ("batch.succeeded", "video.generated", "interaction.completed"):
return WebhookProcessResult(200, "enqueued_output_fetch", res_id, uri, f"queued_async_fetch_for_{event_type}")
if event_type == "batch.failed":
return WebhookProcessResult(200, "routed_to_dlq", res_id, None, "batch_failed_routed_to_dlq_triage")
return WebhookProcessResult(200, "duplicate_ignored", res_id, uri, "unhandled_event_acknowledged")
if __name__ == "__main__":
secret_current = "whsec_" + base64.b64encode(b"0123456789abcdef0123456789abcdef").decode("ascii")
body = json.dumps({"type": "batch.succeeded", "data": {"id": "batches/job-42", "output_file_uri": "files/out-42"}})
hdrs = {
"webhook-id": "msg_991",
"webhook-timestamp": "1760000000",
"webhook-signature": sign_standard_webhook(secret_current, "msg_991", "1760000000", body),
}
ledger: set[str] = set()
first = handle_gemini_webhook(
raw_body=body, headers=hdrs, active_secrets_b64=(secret_current,), seen_webhook_ids=ledger, now_epoch=1760000050
)
second = handle_gemini_webhook(
raw_body=body, headers=hdrs, active_secrets_b64=(secret_current,), seen_webhook_ids=ledger, now_epoch=1760000055
)
print("First delivery:", first)
print("Duplicate delivery:", second)
Check /en/faq and retry budget rules when configuring worker queues that download completed batch files.
FAQ
Why does client.webhooks.create return the signing secret only once?
For security, Google's Webhooks API only returns new_signing_secret at creation or rotation time and never exposes it in subsequent get or list calls. Store the secret immediately in your secret manager; if lost, call the secret rotation endpoint.
How do we rotate a Gemini webhook signing secret without dropping in-flight callbacks?
Use the 24-hour grace period option when rotating the secret, and configure your webhook verifier to accept signatures matching either the newly issued secret or the previous secret until the grace window expires.
Should our webhook endpoint download the batch output file before returning HTTP 200?
No. Webhook payloads are intentionally thin (id and output_file_uri) so your listener can verify the signature, persist the event ID to a local queue, and return 200 OK within milliseconds. Downloading large output files or firing follow-up model calls inside the request handler causes webhook timeouts and duplicate callback retries.
What HTTP status should our webhook listener return when it receives batch.failed?
Return 200 OK after verifying the signature and recording the failure state in your database or dead letter queue. Returning 500 or 400 on a valid batch.failed notification only tells the webhook sender that delivery failed, triggering unnecessary callback retries.
Sources & further reading
Put the next step into practice.
Check model IDs, current pricing and request formats before integrating. Availability can depend on the model and provider route.


