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

推荐订阅源

Google DeepMind News
Google DeepMind News
MongoDB | Blog
MongoDB | Blog
有赞技术团队
有赞技术团队
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
人人都是产品经理
人人都是产品经理
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog RSS Feed
T
Tor Project blog
T
Threat Research - Cisco Blogs
Microsoft Azure Blog
Microsoft Azure Blog
M
MIT News - Artificial intelligence
V
Vulnerabilities – Threatpost
Project Zero
Project Zero
C
CXSECURITY Database RSS Feed - CXSecurity.com
The Register - Security
The Register - Security
Latest news
Latest news
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
The Hacker News
The Hacker News
Google DeepMind News
Google DeepMind News
L
LINUX DO - 最新话题
U
Unit 42
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 司徒正美
T
Tenable Blog
H
Hacker News: Front Page
B
Blog
宝玉的分享
宝玉的分享
C
Check Point Blog
美团技术团队
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
C
CERT Recently Published Vulnerability Notes
P
Proofpoint News Feed
The GitHub Blog
The GitHub Blog
G
GRAHAM CLULEY
Google Online Security Blog
Google Online Security Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
P
Proofpoint News Feed
GbyAI
GbyAI
酷 壳 – CoolShell
酷 壳 – CoolShell
Hugging Face - Blog
Hugging Face - Blog
Y
Y Combinator Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Hacker News - Newest:
Hacker News - Newest: "LLM"
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Scott Helme
Scott Helme
L
Lohrmann on Cybersecurity
量子位
A
About on SuperTechFans
V2EX - 技术
V2EX - 技术
T
The Exploit Database - CXSecurity.com

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
Build a video webhook handler that survives duplicates (Express + Postgres)
Mason K · 2026-06-15 · via DEV Community

Mason K

📦 Code: github.com/USER/video-webhook-receiver (replace before publishing)

TL;DR

We build a production-grade webhook receiver for async video events (asset.ready and friends): verify HMAC-SHA256 on the raw body, dedupe on the event id with a Postgres unique index, persist + ack with 200 fast, then process from a queue. Webhooks are at-least-once, so duplicates are guaranteed; we design for them.

Managed video APIs encode asynchronously. You upload, you get status: preparing, and minutes later a webhook fires asset.ready. If that handler is wrong, you hit the worst bug shape there is: upload succeeded, encode succeeded, and the video never shows up. No error anywhere. Let's build the handler so that never happens.

Four steps:

  1. The raw-body trap (this breaks signature checks for almost everyone).
  2. Verify the HMAC signature in constant time.
  3. Dedupe with a unique index so duplicates are no-ops.
  4. Ack fast, process from a queue.

1. The raw-body trap 🪤

Providers sign the exact bytes of the request body. If you reparse JSON and re-serialize before checking, the bytes differ and the signature never matches. The classic cause is a global express.json():

// app.js: THE BUG
const express = require('express');
const app = express();
app.use(express.json());          // ❌ consumes + reparses the body globally

app.post('/webhooks/video', (req, res) => {
  // req.body is parsed; the raw bytes are gone; signature check will always fail
});

The fix: mount a raw body parser on the webhook route only, and keep JSON parsing for the rest of your app.

// app.js: THE FIX
const express = require('express');
const app = express();

// raw buffer ONLY for the webhook route, registered before any json() middleware
app.post('/webhooks/video',
  express.raw({ type: 'application/json' }),
  handleVideoWebhook
);

app.use(express.json()); // normal parsing for everything else

Now req.body inside handleVideoWebhook is a Buffer of the exact bytes the provider signed.

2. Verify the signature (constant time)

Most providers send HMAC-SHA256, often with a timestamp to block replays (Stripe-style t=...,v1=...; Mux uses a similar scheme). Recompute and compare with crypto.timingSafeEqual so you don't leak the secret through timing.

// verify.js
const crypto = require('crypto');

function verifySignature(rawBody, header, secret) {
  // header like: "t=1735689600,v1=4f2c...". Adapt to your provider's format.
  const parts = Object.fromEntries(header.split(',').map(kv => kv.split('=')));
  const timestamp = parts.t;
  const sent = parts.v1;
  if (!timestamp || !sent) return false;

  // reject old timestamps (replay protection): 5 min tolerance
  const ageSec = Math.abs(Date.now() / 1000 - Number(timestamp));
  if (ageSec > 300) return false;

  const signedPayload = `${timestamp}.${rawBody.toString('utf8')}`;
  const expected = crypto
    .createHmac('sha256', secret)
    .update(signedPayload)
    .digest('hex');

  const a = Buffer.from(sent, 'hex');
  const b = Buffer.from(expected, 'hex');
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

module.exports = { verifySignature };

// handleVideoWebhook.js (top half)
const { verifySignature } = require('./verify');
const SECRET = process.env.WEBHOOK_SECRET;

async function handleVideoWebhook(req, res) {
  const sigHeader = req.get('webhook-signature') || '';
  if (!verifySignature(req.body, sigHeader, SECRET)) {
    return res.status(401).send('bad signature');   // reject, don't process
  }
  const event = JSON.parse(req.body.toString('utf8'));
  // ... step 3 below
}

3. Dedupe: the load-bearing wall

Webhook delivery is at-least-once. You WILL get the same event twice (the provider retries when unsure). Use the event id as an idempotency key and a unique index to make a duplicate a no-op.

-- schema.sql
CREATE TABLE webhook_events (
  event_id    text PRIMARY KEY,        -- provider's unique event id
  type        text NOT NULL,
  raw         jsonb NOT NULL,          -- persist the payload for replay/debug
  received_at timestamptz NOT NULL DEFAULT now(),
  processed   boolean NOT NULL DEFAULT false
);

// handleVideoWebhook.js (continued)
const { pool } = require('./db');
const { enqueue } = require('./queue');

  // inside handleVideoWebhook, after JSON.parse:
  const eventId = event.id;
  const client = await pool.connect();
  try {
    await client.query('BEGIN');

    // INSERT ... ON CONFLICT DO NOTHING returns 0 rows if we've seen it
    const ins = await client.query(
      `INSERT INTO webhook_events (event_id, type, raw)
       VALUES ($1, $2, $3) ON CONFLICT (event_id) DO NOTHING`,
      [eventId, event.type, event]
    );

    if (ins.rowCount === 0) {
      await client.query('COMMIT');
      return res.status(200).send('duplicate ignored');   // idempotent no-op
    }

    await client.query('COMMIT');
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release();
  }

💡 If you do real DB work inline instead of queuing, put the dedupe insert and that work in the same transaction. Otherwise a crash between them leaves you fulfilled-but-not-recorded, and the retry double-fulfills.

4. Ack fast, process async ⏱️

The most dangerous failure isn't an error, it's being slow. If your handler finishes the work after the provider's timeout (often 5-15s), the provider assumes failure and retries, running your logic twice. So do the minimum in the request: verify, dedupe, persist, enqueue, return 200. A worker does the real work.

// handleVideoWebhook.js (end)
  await enqueue({ eventId, type: event.type });   // durable queue (SQS/BullMQ/etc.)
  return res.status(202).send('accepted');
}

// worker.js
const { dequeue } = require('./queue');
const { pool } = require('./db');

async function processEvent({ eventId }) {
  const { rows } = await pool.query(
    'SELECT raw, processed FROM webhook_events WHERE event_id = $1', [eventId]
  );
  if (!rows.length || rows[0].processed) return;     // gone or already done

  const event = rows[0].raw;
  switch (event.type) {
    case 'video.asset.ready':
      await markVideoReady(event.data.asset_id, event.data.playback_id);
      break;
    case 'video.asset.errored':
      await markVideoFailed(event.data.asset_id, event.data.error);
      break;
    // ordering is NOT guaranteed: reconcile by asset_id, don't assume sequence
  }

  await pool.query(
    'UPDATE webhook_events SET processed = true WHERE event_id = $1', [eventId]
  );
}

dequeue(processEvent);

Two mistakes that survive code review

❌ Returning 500 on a business error
   A 500 tells the provider to RETRY. If the event itself is bad
   (malformed asset, constraint violation), you've made a poison
   message that retries forever and floods your logs.
   ✅ Ack 200 once persisted; handle business failures in the worker
      with your own retries + a dead-letter queue.

❌ Treating webhooks as the only source of truth
   If your endpoint is down for an hour, those events can be lost
   for good. ✅ Run a periodic job that lists assets from the
   provider and reconciles against your DB.

Quick test

# replay a captured event twice; second should be a no-op
curl -X POST localhost:3000/webhooks/video \
  -H 'content-type: application/json' \
  -H "webhook-signature: t=$(date +%s),v1=$(...)" \
  --data-binary @event.json
# → 202 accepted
# run it again → 200 duplicate ignored

What's next

  • Swap the in-house queue for SQS/BullMQ and add a dead-letter queue.
  • Add a /webhooks/replay admin endpoint that re-enqueues a stored event_id.
  • Add the reconciliation cron that lists provider assets and backfills anything missed.

This is the same at-least-once reliability shape you'd build for any messaging system. Video just makes the stakes obvious: get it wrong and the upload succeeds, the encode succeeds, and the video never appears.