Designing Idempotent Webhook Receivers for Scrape Events in Agent Pipelines
Durable inboxes, unique keys, and reconciliation make scrape callbacks safe to retry.

An event-driven web scraping API with webhook support sends a completion callback when an asynchronous crawl or extraction job is ready, eliminating the need to poll for completion. Reliable agent pipelines put a durable, idempotent receiver between that callback and the agent’s next action. The sender can retry delivery, but the receiver must prevent duplicates, acknowledge safely, and make replay harmless.
Why async scrape jobs break naive webhook receivers
Async crawl and batch-extraction jobs can spend an arbitrarily long time working before sending a completion event. By then, the receiving endpoint may be slow or unavailable. At-least-once delivery handles that uncertainty through retries after a timeout, a non-2xx response, or a lost acknowledgment. The sender cannot tell whether its request vanished or the receiver processed it and lost the response. Retrying is correct behavior.
Those retries also break any assumption about arrival order. With parallel dispatch, a newer event can arrive before an older event gets another try, so last-arrival-wins logic can overwrite the current state with stale data. A duplicate may arrive days after its first copy. Stripe retries for up to three days, while GitHub requires manual redelivery within three days. A quiet endpoint is not necessarily a finished conversation.
Agent pipelines can also slow things down inside the receiver itself. An LLM call or enrichment request made during the HTTP handler can take longer than the provider’s timeout, which is often only a few seconds. The scrape succeeded, but its callback now triggers retries. Worse, these failures need not throw exceptions. Dashboards can stay green while duplicated enrichment rows, stale CRM records, and repeated RAG upserts accumulate behind the reassuring glow.
The receiver, not the sender, owns the correctness guarantee
The receiver is the consumer half of a distributed queue whose producer shares no transaction with it. “Accept a POST, parse JSON, update a record, return 200” leaves room for crashes, concurrent duplicates, and slow queries between steps that look harmless in isolation. Exactly-once delivery is not achievable at scale, so the production target is at-least-once delivery with receiver-side idempotency. The operating model has to allow for duplicates, disorder, and gaps.
Three gates every scrape-event receiver must pass in sequence

The receiver needs three gates in order, which are authenticity verification, durable acceptance and acknowledgment, then conditional effects. When acceptance includes downstream processing, acknowledgment has to wait for work the receiver cannot control. Acknowledging before persistence creates a different problem. The sender thinks the event was delivered even though a crash can still erase it.
At the first gate, compute the HMAC over the raw request body before parsing changes it. Re-serialized JSON can differ in whitespace or key order and break an otherwise valid signature. Compare signatures in constant time, and enforce a tolerance window where the provider signs a timestamp. During rotation, key selection must also allow both the old and the new keys.
An invalid signature earns a hard 401. A malformed but correctly signed payload belongs in durable storage for inspection and should receive 200 after that write. Treating malformed data as an authentication failure muddies security monitoring, while discarding it removes the evidence needed to understand why the payload is malformed. Neither helps the operator handling the incident.
At the second gate, write to a durable inbox before returning 200, then process from that inbox. The acknowledgment means “stored,” not “finished enriching.” An illustrative table definition can use CREATE TABLE processed_webhooks (..., PRIMARY KEY (tenant_id, provider, event_id)) to anchor deduplication. The composite key keeps events from different tenants and providers from colliding. An INSERT ... ON CONFLICT DO NOTHING checks and claims atomically rather than leaving a race between a lookup and an insert.
The dedup record, raw payload, and scheduling state must commit in one transaction. Otherwise, an event can be recorded without being scheduled for processing. A short-lived cache cannot do the job of the database’s unique constraint across restarts and horizontal instances. If the durable write fails, return a non-2xx so the sender can retry legitimately. Here, a 500 is the honest answer.
At the third gate, deduplication must give way to state validation. An event ID catches exact repeats. The sketch UPDATE ... WHERE status='expected' allows a transition only from its valid prior state, while source timestamps or version fields tell newer results apart from late arrivals. Receipt time is the wrong clock for this job. A CRM enrichment or RAG update must not overwrite a version that a later source event has already established.
Why the dedup window must span the sender's full retry horizon
When a dedup record expires, an old delivery looks like a new event. Retention therefore has to cover the slowest realistic sender’s retry or redelivery horizon, with margin. Average delivery speed is irrelevant to that boundary. Stripe’s retry window spans days, Svix uses a fixed schedule and eventually disables persistently failing endpoints, and GitHub depends on manual redelivery. These contracts differ too much for one casual cache default.
Redis can provide a fast pre-check for duplicate traffic, but the database must remain the authority when that check misses. This separates speed from correctness. A short TTL may be convenient while still expiring well before the sender stops trying, allowing a delayed duplicate through. The database unique constraint closes that gap without making Redis responsible for a guarantee it cannot supply alone.
Durable retention also needs an end. Without cleanup, dedup tables keep growing after their records have served their purpose. The recommended policy is to span the retry horizon with margin, then TTL-clean records beyond that window. Scheduled retention maintenance belongs to the design as much as the unique key does.
The gap-closer: periodic reconciliation for events that never arrived
Deduplication stops extra deliveries but cannot bring back the ones that never arrived. An outage that outlasts the sender’s retry window leaves a gap even in a perfectly idempotent receiver. A scheduled sweeper closes it by comparing local state with provider APIs. It looks for scrape jobs that have finished but have no inbox records, enrichment rows that have been pending longer than they should, or monitoring alerts that should have fired.
The sweeper backfills through list or GET endpoints and uses the same idempotent handlers as live delivery. A fix then helps both live events and reconciliation, while the sweeper keeps putting the dedup logic to work. Hourly reconciliation is typical for most scrape-event workflows. A tighter cadence is justified when a missing enrichment result directly affects an agent decision, balanced against provider API quotas.
Replay needs narrower controls than “send everything again.” Scope it by entity and time range, rate-limit it against downstream effects, and log the operator’s identity. Those replayed events must use the same handlers too. Otherwise, recovery can bypass the safeguards that production delivery has to follow.
How do webpage changes trigger scrapes and webhook-driven agent updates?
The reference path is a monitor producing a change event, followed by webhook intake, a durable queue, and background agent work. For an asynchronous scrape, the scraping API sends a completion callback, the receiver stores it, and a worker fetches the structured result before routing it onward. The agent then updates a RAG store, enriches a CRM row, or triggers a follow-on crawl. Monitoring and completion notifications have different jobs. Buying completion callbacks alone does not establish how page changes will be detected.
In a web-monitoring workflow, an agent subscribes to tracked-page changes whose structured payload includes a diff, an AI summary, and screenshots. Those results can feed a vector store such as ChromaDB through an idempotent upsert. The source timestamp guards the stored version. Only newer content should replace it, because inserting the same chunks again can lead to duplicate passages and noise in retrieval.
When a primary source finds nothing, a live scrape can deliver its result back to the enrichment row. That result may arrive after a manual correction. For significant CRM events, fetching the entity from the provider API before applying the webhook’s claim is worth the extra GET because it guards against state the provider has already superseded. Event deduplication alone cannot settle that conflict.
Trigger.dev converts webhook events into durable jobs independent of the HTTP request lifecycle. Hookdeck offers automatic retries, rate limiting, and durable queueing with backpressure as a dedicated event gateway. These services can offload queue management, but the scraping service still needs stable job IDs and a well-documented event contract. Those are concrete buying criteria. A managed scraping API is a stronger base than brittle scripts, but it still needs a contract that can be used.
Orchestrating the receiver with n8n, LangChain, and MCP
The orchestration framework changes the wiring while leaving the correctness requirements intact. n8n is a preferred fit for scraping workflows because it supports self-hosting and custom code execution without per-task fees. Extraction stays with a dedicated scraper while orchestration stays in the workflow tool. In that setup, a transaction in a database node should store the inbox before the response returns. Workflow execution is not atomic with the HTTP acknowledgment, so in-memory dedup inside a workflow is insufficient.
n8n can consume MCP servers as agent tools and expose workflows as MCP servers for external agents. Its native instance-level MCP server launched in April 2026, so AI clients that work with it can build and publish workflows inside an instance. LangChain’s langchain-mcp-adapters converts MCP tools into LangChain- and LangGraph-compatible tools without custom integration code per provider. That simplifies access to the scraper. It does not simplify away agent state, because a result arriving during an active LangGraph run must be ordered against the agent’s current context as well as the database row.
Zapier introduces a different constraint through its single-trigger-per-Zap model and paywalled webhook access. Those limits complicate fan-out to several agents or stores. The practical mitigation is a thin intermediary receiver, such as a lightweight serverless function backed by the durable inbox, that triggers Zapier after acceptance.
The Model Context Protocol exposes scraping tools to agents. That changes how an agent calls the tool. In an MCP-native asynchronous pipeline, however, the completion webhook still arrives over HTTP and needs the same verification, persistence, and conditional effects. A new protocol does not cancel an old retry.
Operational decisions that determine whether the design holds in production
The strongest objection to a durable inbox is its operating cost. Basic webhook wiring can fit into an afternoon, while this pattern adds storage, retention, a sweeper, replay tooling, and dashboards. That is a legitimate trade-off. Inline processing suits low-volume, fast, inherently idempotent effects such as analytics pings or logging. When missed or doubled events corrupt agent state, CRM records, or RAG retrieval, the inbox costs less than diagnosing silent corruption weeks later.
The Redis-versus-database disagreement is therefore a question of roles. The latency objection is valid without displacing the durable correctness boundary. Privacy also needs safeguards that tuning for speed cannot provide. Raw payloads, event IDs, and tenant IDs can be sensitive, and replay copies of scrape results retain the sensitivity of the crawled content. Before launch, there must be decisions on retention limits, encryption at rest, and log redaction.
The release checklist is binary. Signatures must be verified over raw bytes, and 200 must follow a durable write. Deduplication must use a database unique constraint, and conditional writes must check that the state and source ordering are valid. Background workers must run independently of HTTP requests. The sweeper must be scheduled, and replay must be scoped and rate-limited.


