惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

W
WeLiveSecurity
博客园 - 【当耐特】
Microsoft Azure Blog
Microsoft Azure Blog
WordPress大学
WordPress大学
Stack Overflow Blog
Stack Overflow Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
IT之家
IT之家
Cloudbric
Cloudbric
The Register - Security
The Register - Security
小众软件
小众软件
PCI Perspectives
PCI Perspectives
G
Google Developers Blog
AI
AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Google DeepMind News
Google DeepMind News
Google DeepMind News
Google DeepMind News
宝玉的分享
宝玉的分享
Recent Commits to openclaw:main
Recent Commits to openclaw:main
量子位
TaoSecurity Blog
TaoSecurity Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
F
Full Disclosure
N
Netflix TechBlog - Medium
博客园_首页
Last Week in AI
Last Week in AI
A
Arctic Wolf
B
Blog RSS Feed
J
Java Code Geeks
C
Cybersecurity and Infrastructure Security Agency CISA
I
InfoQ
aimingoo的专栏
aimingoo的专栏
云风的 BLOG
云风的 BLOG
NISL@THU
NISL@THU
MyScale Blog
MyScale Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Jina AI
Jina AI
有赞技术团队
有赞技术团队
S
Schneier on Security
L
Lohrmann on Cybersecurity
P
Privacy & Cybersecurity Law Blog
T
Threat Research - Cisco Blogs
P
Palo Alto Networks Blog
S
Security @ Cisco Blogs
Security Archives - TechRepublic
Security Archives - TechRepublic
Security Latest
Security Latest
Vercel News
Vercel News
博客园 - 司徒正美
Webroot Blog
Webroot Blog
Hacker News: Ask HN
Hacker News: Ask HN
A
About on SuperTechFans

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
5 Apify webhook patterns that turn one-off scrapers into reliable data pipelines
Alex Spinov · 2026-05-06 · via DEV Community

5 Apify webhook patterns that turn one-off scrapers into reliable data pipelines

This article was drafted with AI assistance and edited by a human author. All metrics and patterns come from actors I personally maintain on Apify.

I maintain 79 Apify actors (32 public on the Store). The Trustpilot review scraper alone has 954 runs across 3 paying users; the Reddit scraper has 84; the email extractor has 109. The runs themselves work — proxies rotate, pagination terminates, output lands in the dataset. The hard part is what happens after the run.

Most actors I see in the wild treat the dataset as the final destination. The user has to remember to log into Apify, click into the run, and download a CSV. That works for one-off jobs. It does not work for a customer who wants the data in their Postgres at 06:00 UTC every morning, or in a Slack channel the moment a competitor's price changes, or piped into a vector store for retrieval-augmented search.

Webhooks are how you bridge "the actor finished" with "the data is now where the customer needs it." But Apify webhooks are easy to get wrong. Below are the 5 patterns I wish every actor I owned had on day one. None of them require a new dependency. All of them survive the move from "free actor with 10 runs/month" to "paying customer with 1000 runs/month."


Pattern 1: Fire one webhook per ACTOR.RUN.SUCCEEDED and one per ACTOR.RUN.FAILED — never share a handler

The instinct when you wire up your first webhook is to make it generic — one endpoint that receives "the run is done" and figures out the rest from the payload. This breaks the day a customer's success-handler has a bug and silently swallows failure events too.

Wrong:

{
  "eventTypes": ["ACTOR.RUN.SUCCEEDED", "ACTOR.RUN.FAILED", "ACTOR.RUN.TIMED_OUT", "ACTOR.RUN.ABORTED"],
  "requestUrl": "https://customer.example.com/apify-hook"
}

Enter fullscreen mode Exit fullscreen mode

Right:

[
  { "eventTypes": ["ACTOR.RUN.SUCCEEDED"], "requestUrl": "https://customer.example.com/hooks/run-success" },
  { "eventTypes": ["ACTOR.RUN.FAILED", "ACTOR.RUN.TIMED_OUT", "ACTOR.RUN.ABORTED"], "requestUrl": "https://customer.example.com/hooks/run-failure" }
]

Enter fullscreen mode Exit fullscreen mode

The split is worth the extra config row because a success handler that processes data and a failure handler that pages on-call are different services. They have different retry policies, different secrets, and different blast radii. When one breaks, you do not want it to take the other down.

Pattern 2: Use payloadTemplate to send only what the receiver actually needs

The default Apify webhook payload includes the full run object — about 4 KB of JSON with fields like meta, stats, usage, containerUrl, buildId. Most receivers care about three fields: runId, defaultDatasetId, and a status enum.

Sending 4 KB when 200 bytes will do means more bandwidth on the receiver's side, more parsing time, and (the real problem) more accidental coupling — your customer's code starts depending on stats.requestsFinished, and the day Apify renames or removes that field, the integration breaks.

Use payloadTemplate to flatten:

{
  "runId": "{{resource.id}}",
  "actorId": "{{resource.actId}}",
  "datasetId": "{{resource.defaultDatasetId}}",
  "status": "{{resource.status}}",
  "startedAt": "{{resource.startedAt}}",
  "finishedAt": "{{resource.finishedAt}}",
  "actorVersion": "{{resource.buildNumber}}"
}

Enter fullscreen mode Exit fullscreen mode

Now your receiver gets a stable, minimal contract. When you need a new field, you add it explicitly — never by accident.

Pattern 3: HMAC-sign every webhook so the receiver can prove it came from Apify

A webhook URL leaked once in a customer's load balancer logs lives forever. Anyone who finds it can POST your payload format and trigger downstream work. The defense is not "rotate the URL" — it is "sign every payload."

Apify's webhook configuration accepts custom headers. Use one to send an HMAC of the payload:

Sender side (your actor's webhook config or a small wrapper):

import crypto from 'node:crypto';

const secret = process.env.WEBHOOK_HMAC_SECRET;
const payload = JSON.stringify({ runId, datasetId, status });
const signature = crypto.createHmac('sha256', secret).update(payload).digest('hex');

await fetch(customerUrl, {
  method: 'POST',
  headers: {
    'content-type': 'application/json',
    'x-apify-signature': `sha256=${signature}`,
  },
  body: payload,
});

Enter fullscreen mode Exit fullscreen mode

Receiver side:

const expected = crypto
  .createHmac('sha256', process.env.WEBHOOK_HMAC_SECRET)
  .update(req.rawBody)
  .digest('hex');

const provided = (req.headers['x-apify-signature'] || '').replace(/^sha256=/, '');

if (!crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(provided))) {
  return res.status(401).end();
}

Enter fullscreen mode Exit fullscreen mode

Two notes that catch people: (1) compute the HMAC on the raw request body, before any JSON parsing — middleware that mutates the body silently breaks signatures. (2) Use timingSafeEqual, not ===. String comparison is timing-sensitive and lets attackers brute-force one byte at a time.

Pattern 4: Make the receiver idempotent — Apify retries failed webhooks

Apify retries a webhook up to 11 times with exponential backoff if your endpoint returns a non-2xx. That's a feature: it means transient receiver-side failures don't lose data. It's also a footgun: it means your receiver can be called multiple times for the same run.

If your handler does anything stateful — inserts into Postgres, posts to Slack, sends an email — you must dedupe by runId.

The minimum viable dedupe table:

CREATE TABLE apify_webhook_seen (
  run_id TEXT PRIMARY KEY,
  received_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

Enter fullscreen mode Exit fullscreen mode

Handler:

const { runId, datasetId, status } = req.body;

const { rowCount } = await pg.query(
  'INSERT INTO apify_webhook_seen (run_id) VALUES ($1) ON CONFLICT DO NOTHING',
  [runId]
);

if (rowCount === 0) {
  return res.status(200).json({ ok: true, already_processed: true });
}

await processRun(runId, datasetId, status);
res.status(200).end();

Enter fullscreen mode Exit fullscreen mode

The INSERT ... ON CONFLICT DO NOTHING is the heart of the pattern. The second call for the same run inserts zero rows, the handler exits early, and nothing downstream sees a duplicate. This is the same pattern Stripe documents for their own webhooks — it's the de-facto standard for at-least-once delivery.

Pattern 5: Don't process the dataset inside the webhook — enqueue and return 200 fast

Apify expects a webhook response in 30 seconds. If your handler downloads a 200 MB dataset, parses it, runs deduplication, and writes to Postgres before returning, you will hit timeouts on every large run. Apify will then retry — and your half-finished writes will compound.

The correct shape: webhook = enqueue, worker = process.

// Webhook handler
app.post('/hooks/run-success', async (req, res) => {
  // verify HMAC (Pattern 3) + dedupe (Pattern 4) first
  await jobQueue.add('process-apify-run', {
    runId: req.body.runId,
    datasetId: req.body.datasetId,
  });
  res.status(200).json({ ok: true, queued: true });
});

// Worker (separate process)
jobQueue.process('process-apify-run', async (job) => {
  const { runId, datasetId } = job.data;
  for await (const item of streamDataset(datasetId)) {
    await upsertItem(item);
  }
});

Enter fullscreen mode Exit fullscreen mode

Your queue can be BullMQ on Redis, AWS SQS, Postgres LISTEN/NOTIFY, or a single row in a jobs table polled by a cron. The technology doesn't matter. What matters is that the webhook handler does only: verify, dedupe, enqueue, return. Heavy work happens in the worker, where you have hours, not seconds, and where retries are your own controlled retries — not Apify's blind 11.


Why these 5 and not 15

Webhooks have dozens of edge cases. SSL termination, IP allowlists, header size limits, timezone-naive timestamps, payload-too-large errors, dead-letter queues, exponential-backoff jitter. I picked these 5 because they are the ones that will bite a paying customer in their first month, and the ones that take 30 minutes each to wire in if you do them on day one — versus 3 days each to retrofit after the integration is in production.

If you maintain Apify actors that have paying users, audit each of yours against this list. The Trustpilot scraper and the email extractor both run all 5 patterns; the older actors do not, and every customer support thread I have ever had has been one of these 5 failures.



Disclosure: I maintain Apify actors related to this topic; the apify.com link below directs to my Apify Store profile.

I write about Apify production patterns and scraping engineering on blog.spinov.online and on Telegram @scraping_ai. Author profile: apify.com/knotless_cadence (79 actors, 32 public). Questions about a specific actor or webhook pattern — open an issue on the actor page or email spinov001@gmail.com.