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

推荐订阅源

月光博客
月光博客
Cyberwarzone
Cyberwarzone
L
LINUX DO - 最新话题
N
News and Events Feed by Topic
T
Troy Hunt's Blog
Help Net Security
Help Net Security
S
Security @ Cisco Blogs
Google DeepMind News
Google DeepMind News
Security Archives - TechRepublic
Security Archives - TechRepublic
M
MIT News - Artificial intelligence
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V2EX - 技术
V2EX - 技术
Y
Y Combinator Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
大猫的无限游戏
大猫的无限游戏
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Microsoft Security Blog
Microsoft Security Blog
Cisco Talos Blog
Cisco Talos Blog
T
Threatpost
Recent Commits to openclaw:main
Recent Commits to openclaw:main
S
SegmentFault 最新的问题
I
InfoQ
H
Hacker News: Front Page
D
Docker
Scott Helme
Scott Helme
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Blog — PlanetScale
Blog — PlanetScale
人人都是产品经理
人人都是产品经理
博客园 - 叶小钗
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
N
Netflix TechBlog - Medium
AWS News Blog
AWS News Blog
Know Your Adversary
Know Your Adversary
博客园 - 【当耐特】
T
Tor Project blog
U
Unit 42
H
Heimdal Security Blog
Microsoft Azure Blog
Microsoft Azure Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
P
Privacy & Cybersecurity Law Blog
PCI Perspectives
PCI Perspectives
美团技术团队
O
OpenAI News
T
Tailwind CSS Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
B
Blog
GbyAI
GbyAI
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
MyScale Blog
MyScale Blog

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
DynamoDB Streams and Lambda for Real-Time Threat Detection: The Event Pipeline DynamoDB Was Built For
Heartlin Machado · 2026-06-25 · via DEV Community

This post was created for the H0: Hack the Zero Stack hackathon. #H0Hackathon


A consumer scans a product's QR code. Five seconds later, a threat alert appears on the brand's dashboard, no page refresh, no polling. The entire pipeline is DynamoDB Streams firing a Lambda, writing a threat alert back to DynamoDB, and pushing it to the browser via Server-Sent Events.

This post walks through the complete pipeline I built for GenuProof, an anti-counterfeiting platform running on DynamoDB and Vercel. Every component is serverless. Cost at zero traffic: $0.

The architecture

Consumer scans QR > Vercel API Route > DynamoDB PutItem (SCAN# record)
                                              |
                                              v
                                    DynamoDB Stream (NEW_IMAGE)
                                              |
                                              v
                                    Lambda: authentik-threat-detector
                                      |-- Geographic anomaly check
                                      |-- Burst scan detection
                                      |-- Claim violation check
                                      |-- Hash tampering check
                                              |
                                         (if anomaly)
                                              |
                                              v
                                    DynamoDB PutItem (THREAT# alert)
                                              |
                                              v
                                    SSE endpoint polls THREAT#
                                              |
                                              v
                                    Brand dashboard updates (no refresh)

Step 1: The scan write triggers the Stream

When a consumer verifies a product, the Vercel API route writes a scan record:

const scanRecord = {
  PK: `PRODUCT#${productId}`,
  SK: `SCAN#${new Date().toISOString()}`,
  productId,
  timestamp: now,
  ip,
  country: geo.country,
  city: geo.city,
  userAgent: req.headers.get("user-agent"),
  result: hashMatch && signatureValid ? "authentic" : "suspicious",
};
await putItem(scanRecord);

This write hits DynamoDB. Because Streams is enabled with NEW_IMAGE view type, DynamoDB emits a stream record containing the complete new item. The stream record goes to a shard, and our Lambda function is subscribed to that shard.

Step 2: Lambda receives the stream event

The Lambda function is configured as a DynamoDB Stream trigger:

  • Batch size: 10 (process up to 10 records per invocation)
  • Batching window: 5 seconds (wait up to 5s to fill the batch)
  • Starting position: LATEST
export async function handler(event) {
  for (const record of event.Records) {
    if (record.eventName !== "INSERT") continue;

    const newImage = record.dynamodb.NewImage;
    const sk = newImage.SK.S;

    // Only process scan records and provenance events
    if (sk.startsWith("SCAN#")) {
      await processScan(newImage);
    } else if (sk.startsWith("EVENT#")) {
      await processEvent(newImage);
    }
  }
}

Key detail: the Lambda filters by SK prefix. Because this is a single-table design, the Stream contains writes for all entity types: brand profiles, product registrations, webhook configs. The Lambda ignores everything except SCAN# and EVENT# records. This filtering happens in application code, not at the Stream level, which means we pay for Lambda invocations on non-scan writes. At our scale, this is negligible. At very high write volume, you'd use DynamoDB Stream event filtering to filter at the infrastructure level.

Step 3: Anomaly detection (four checks)

For each scan record, the Lambda runs four sequential anomaly checks:

Geographic anomaly

// Query recent scans for this product (last 24 hours)
const recentScans = await ddb.send(new QueryCommand({
  TableName: TABLE,
  KeyConditionExpression: "PK = :pk AND SK BETWEEN :start AND :end",
  ExpressionAttributeValues: {
    ":pk": `PRODUCT#${productId}`,
    ":start": `SCAN#${twentyFourHoursAgo}`,
    ":end": `SCAN#${now}`,
  },
}));

const countries = new Set(recentScans.Items.map(s => s.country.S));
if (countries.size >= 3) {
  // Same product scanned from 3 or more countries in 24h
  anomalyType = "geographic_anomaly";
}

This is the pattern DynamoDB was built for: range query within a partition, sorted by timestamp. The SK SCAN#2026-06-22T01:00:00Z sorts lexicographically as a timestamp. The BETWEEN query returns only scans in the 24-hour window, no filter expression needed, no wasted read capacity.

An important subtlety: DynamoDB Streams delivers records in order within a shard. This ordering guarantee is what makes burst detection correct. If scans arrived out of order, we couldn't reliably count "10 scans in the last hour" because the window would be inconsistent. Streams' per-shard ordering means the Lambda always sees scans in the sequence they were written.

Burst scan detection

const oneHourAgo = new Date(Date.now() - 3600000).toISOString();
const recentHourScans = recentScans.Items.filter(
  s => s.timestamp.S > oneHourAgo
);
if (recentHourScans.length >= 10) {
  anomalyType = "burst_scan";
}

Ten or more scans of the same product in one hour suggests someone is testing a cloned QR code, trying different devices and locations to see if the system catches them.

Claim violation

const claim = await ddb.send(new GetCommand({
  TableName: TABLE,
  Key: { PK: `PRODUCT#${productId}`, SK: "CLAIM" },
}));
if (claim.Item) {
  // Product already claimed by a consumer, new scan from different device
  anomalyType = "claimed_product_scan";
}

This is a GetItem: one partition read, one RCU. The CLAIM record was written when the original consumer claimed the product. Any subsequent scan from a different device fingerprint is suspicious.

Hash tampering

if (verificationResult !== "authentic") {
  anomalyType = "hash_tampering";
}

If the scan record itself shows the product failed hash verification, something is fundamentally wrong: either the database was tampered with or the product record was modified. CRITICAL severity.

Step 4: Write the threat alert

If any check fires, the Lambda writes a threat alert back to DynamoDB:

const monthBucket = timestamp.slice(0, 7); // "2026-06"
const alert = {
  PK: `THREAT#${brandId}#${monthBucket}`,
  SK: `ALERT#${timestamp}#${type}`,
  GSI1PK: `BRAND#${brandId}`,
  GSI1SK: `THREAT#${timestamp}`,
  brandId, type, severity, productId, details, timestamp,
  resolved: false,
  source: "lambda-stream",
};
await ddb.send(new PutCommand({ TableName: TABLE, Item: alert }));

Note the monthly-bucketed PK: THREAT#brandId#2026-06. If we used THREAT#brandId as a flat PK, a brand that generates thousands of threat alerts would create a write-hot partition, all writes concentrating on one partition key. Monthly bucketing distributes writes across time-based partitions. (I wrote a separate post on sharding hot partitions if you want the full breakdown.)

The GSI1PK: "BRAND#brandId" projection means we can query all threats for a brand across monthly buckets with a single GSI1 query, no scatter-gather needed on the read path.

Step 5: SSE pushes to the dashboard

The final piece: getting the alert to the brand's browser without polling from the client side.

The Vercel API has an SSE (Server-Sent Events) endpoint that the dashboard connects to:

// Client (React component)
const source = new EventSource(`/api/stream?brandId=${brandId}`);
source.addEventListener("threat", (e) => {
  const threat = JSON.parse(e.data);
  setThreats(prev => [threat, ...prev]);
});

The server-side SSE endpoint queries DynamoDB every 3 seconds for new threats newer than the last timestamp:

const threats = await queryGSI1(`BRAND#${brandId}`, `THREAT#${lastTimestamp}`, {
  limit: 10,
  scanForward: true,
});
for (const threat of threats) {
  controller.enqueue(encoder.encode(`event: threat\ndata: ${JSON.stringify(threat)}\n\n`));
  lastTimestamp = threat.timestamp;
}

The total latency from scan-to-dashboard:

  1. PutItem scan record: ~5ms
  2. Stream delivery to Lambda: ~100-500ms
  3. Lambda anomaly checks: ~50-200ms (includes DynamoDB queries)
  4. PutItem threat alert: ~5ms
  5. SSE poll interval: up to 3s

Total: under 5 seconds from QR scan to dashboard alert.

Error handling and retry guarantees

What happens when the Lambda fails mid-execution? DynamoDB Streams has built-in retry:

  • At-least-once delivery: if the Lambda throws, DynamoDB retries the same batch. The function must be idempotent (writing a threat alert with the same PK/SK is a no-op PutItem, naturally idempotent).
  • Ordering preserved on retry: retries deliver the same records in the same order within the shard. Your anomaly detection logic sees a consistent sequence regardless of how many retries occurred.
  • Bisect on error: if a batch consistently fails, DynamoDB splits it in half and retries each half separately, isolating the poisoned record.

The Lambda doesn't need a dead-letter queue at our scale. If a record genuinely can't be processed after retries, it ages out of the 24-hour Stream retention window. No scan goes unprocessed silently: the scan record itself is already in DynamoDB, and the anomaly detection runs again on the next scan for the same product.

Why DynamoDB Streams (not SQS, not EventBridge)

The alternative architecture would be: write to DynamoDB, then separately publish to SQS or EventBridge, then subscribe a Lambda, then write the alert back. That's three services instead of one.

DynamoDB Streams collapses the first two into a built-in feature. The advantages over a separate message bus:

  • Zero infrastructure: no queue to create, no dead-letter queue to configure, no IAM policies for cross-service access
  • Guaranteed delivery: every successful DynamoDB write generates a stream record. No "forgot to publish" bugs.
  • Ordered processing: records arrive in write order within a shard. SQS standard queues don't guarantee ordering. SQS FIFO queues do, but require explicit deduplication IDs.
  • Same-table writes: the Lambda reads from DynamoDB and writes back to the same table. One set of credentials, one IAM policy, one table.
  • Cost: $0 at rest. No base cost when nobody is scanning. Lambda charges only for invocations.

The Lambda function

The full Lambda is 412 lines. Here's what each section does:

Lines Function Purpose
1-20 Setup DynamoDB client, env vars, table name
21-40 handler() Stream record iteration, SK filtering
41-106 anomalyChecks() Four detection checks
108-250 processScan() Orchestrates checks and writes
252-355 AI integration Classification (downstream consumer of the pipeline)
356-397 writeAlert() Threat alert with monthly bucketing
400-412 writeOpsLog() Telemetry with daily bucketing

The complete source is in lambda/threat-detector.mjs at github.com/4KInc/genuproof.

Stream configuration

Setting Value Why
View type NEW_IMAGE Need the full item to run anomaly checks
Batch size 10 Process multiple scans per invocation to reduce Lambda cold starts
Batching window 5 seconds Allows batching during burst periods
Starting position LATEST Only process new writes, not historical data
Retry 2 Retry failed batches (Streams guarantees ordering within retry)

What I learned

  1. Single-table design with Streams is the canonical DynamoDB architecture. One table gives you one Stream. One Stream gives you one event pipeline. The simplicity is the point.

  2. Filter in application code, not infrastructure (at small scale). At large scale, use Lambda event source filtering to avoid paying for irrelevant invocations.

  3. Monthly-bucketed threat partitions were a late addition after I realized the flat THREAT#brandId PK would hot-spot. The fix took 30 minutes and required zero table migration: change the PK format in the Lambda writer and switch the reader to GSI1.

  4. SSE is underrated for real-time features. It's simpler than WebSockets, works through CDNs, and the 3-second poll against DynamoDB costs essentially nothing at demo scale.

  5. Streams ordering enables correctness, not just convenience. Burst detection, geographic anomaly windows, and claim violation checks all depend on seeing scans in the order they were written. Without Streams' per-shard ordering guarantee, you'd need application-level sequencing.


Built for the H0: Hack the Zero Stack hackathon using DynamoDB and Vercel. #H0Hackathon