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

推荐订阅源

Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
D
Darknet – Hacking Tools, Hacker News & Cyber Security
N
News and Events Feed by Topic
N
News | PayPal Newsroom
SecWiki News
SecWiki News
P
Privacy International News Feed
T
Troy Hunt's Blog
Attack and Defense Labs
Attack and Defense Labs
N
News and Events Feed by Topic
L
LINUX DO - 热门话题
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Security Latest
Security Latest
AWS News Blog
AWS News Blog
S
Secure Thoughts
W
WeLiveSecurity
H
Heimdal Security Blog
T
Threat Research - Cisco Blogs
I
Intezer
Application and Cybersecurity Blog
Application and Cybersecurity Blog
S
Security @ Cisco Blogs
G
GRAHAM CLULEY
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Spread Privacy
Spread Privacy
L
Lohrmann on Cybersecurity
C
CERT Recently Published Vulnerability Notes
S
Security Affairs
Hacker News - Newest:
Hacker News - Newest: "LLM"
Google Online Security Blog
Google Online Security Blog
Cisco Talos Blog
Cisco Talos Blog
雷峰网
雷峰网
Cloudbric
Cloudbric
Y
Y Combinator Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园_首页
Hacker News: Ask HN
Hacker News: Ask HN
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Google DeepMind News
Google DeepMind News
Vercel News
Vercel News
云风的 BLOG
云风的 BLOG
Latest news
Latest news
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
D
Docker
Recent Announcements
Recent Announcements
博客园 - 【当耐特】
H
Help Net Security
博客园 - 司徒正美
TaoSecurity Blog
TaoSecurity Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
C
Check Point 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
Sharding Hot Partitions in DynamoDB: Why Your Single-Partition Log Table Will Break at Scale
Heartlin Machado · 2026-06-25 · via DEV Community

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


I shipped a DynamoDB table with a hot partition and didn't notice for three weeks. At demo scale (700 items, a few writes per minute) everything worked. It would have been fine right up until it wasn't.

The anti-pattern was obvious in hindsight: every AI operation log entry was written to PK: "OPS_LOG". A single partition key for an append-only, high-throughput write stream. This is the exact workload that hits DynamoDB's per-partition throughput ceiling.

Here's what I found, why it matters, and the three patterns I used to fix it, all without a table migration.

The problem: per-partition throughput limits

DynamoDB scales horizontally by splitting data across partitions. Each partition handles:

  • 3,000 RCU (read capacity units) for eventually consistent reads
  • 1,000 WCU (write capacity units)
  • 10 GB of data

When you use PAY_PER_REQUEST (on-demand) billing mode, DynamoDB auto-scales table-level capacity. But it doesn't auto-scale within a partition. If all your writes hit the same partition key, you're bottlenecked at 1,000 WCU on that one partition regardless of your table-level throughput.

A note on adaptive capacity: DynamoDB does have an adaptive capacity feature that can temporarily boost a hot partition's throughput by borrowing from underutilized partitions. But adaptive capacity is a safety net, not a design strategy. It activates reactively, has limits, and doesn't eliminate the per-partition ceiling. Designing around the constraint is always better than relying on the database to compensate for a bad access pattern.

For PK: "OPS_LOG", with every single AI operation landing on one partition key, this means:

  • At 1 write/second: no problem
  • At 100 writes/second: no problem
  • At 1,001 writes/second: throttled. ProvisionedThroughputExceededException.

A real anti-counterfeiting platform processing scans across thousands of brands could easily hit this. And the failure mode is silent at first: DynamoDB retries internally with exponential backoff. You only see it as increased latency, then as dropped writes.

Where I found hot partitions

I audited every PK pattern in my single-table design and found three hot spots. The simplest detection method: count the cardinality of each PK pattern. If a PK has cardinality of 1 (every write goes to the same key), it's a hot partition by definition.

1. OPS_LOG (AI operations telemetry)

// BEFORE: Every AI call writes to the same PK
{
  PK: "OPS_LOG",
  SK: "2026-06-22T01:00:00Z#threat_detector",
  agent: "threat_detector",
  latencyMs: 340,
  aiSeverity: "HIGH",
  ...
}

Problem: Unbounded write concentration. Every AI classification, regardless of brand, product, or time, lands on one partition key. PK cardinality: 1.

2. THREAT#brandId (threat alerts)

// BEFORE: All threats for one brand in one partition
{
  PK: "THREAT#brand-abc-123",
  SK: "ALERT#2026-06-22T01:00:00Z#geographic_anomaly",
  severity: "HIGH",
  ...
}

Problem: A brand under active counterfeiting attack generates hundreds of alerts per day. All writes concentrate on THREAT#brand-abc-123. The brand being attacked the hardest gets the worst write performance. Exactly backwards from what you want.

3. BRAND_INDEX / PRODUCT_INDEX (collection keys)

// Collection key for "list all brands" without Scan
{
  PK: "BRAND_INDEX",
  SK: "BRAND#2026-06-22T01:00:00Z#abc",
  name: "Luxe Watches",
  ...
}

Problem: If brand registrations spike (product launch, marketing campaign), all writes hit BRAND_INDEX. Same issue as OPS_LOG. PK cardinality: 1.

The fix: three sharding patterns

Pattern 1: Time-bucketed sharding (for OPS_LOG)

Instead of a single OPS_LOG key, bucket writes by date:

// AFTER: Daily-bucketed partition keys
const dateBucket = timestamp.slice(0, 10); // "2026-06-22"
{
  PK: `OPS_LOG#${dateBucket}`,       // OPS_LOG#2026-06-22
  SK: `${timestamp}#${agent}`,
  GSI1PK: "OPS_LOG",                  // For cross-day queries
  GSI1SK: timestamp,
  ...
}

Write path: Each day's ops entries go to a different partition. Today's 1,000 writes go to OPS_LOG#2026-06-22. Tomorrow's go to OPS_LOG#2026-06-23. The per-partition WCU limit applies per day, not per all-time. PK cardinality goes from 1 to 365/year.

Read path: The dashboard needs recent ops entries across days. Two options:

Option A: Scatter-gather

// Query each daily partition in parallel
const days = 7;
const buckets = [];
for (let i = 0; i < days; i++) {
  const d = new Date(Date.now() - i * 86400000);
  buckets.push(d.toISOString().slice(0, 10));
}

const results = await Promise.all(
  buckets.map(date =>
    queryItems(`OPS_LOG#${date}`, undefined, { limit: 50, scanForward: false })
  )
);

// Merge and sort
const logs = results.flat()
  .sort((a, b) => b.timestamp.localeCompare(a.timestamp))
  .slice(0, limit);

7 parallel queries, each hitting a different partition. DynamoDB handles them concurrently. Total latency is the slowest single query, typically under 20ms.

Option B: GSI1 query

// Single query across all days via GSI
const logs = await queryGSI1("OPS_LOG", undefined, { limit: 50, scanForward: false });

The GSI1 projection has GSI1PK: "OPS_LOG" across all daily partitions. This re-concentrates reads on one GSI partition key, but reads are less critical than writes (3,000 RCU vs 1,000 WCU limit), and the dashboard is low-frequency.

I use scatter-gather as the primary path and GSI1 as a fallback.

Pattern 2: Month-bucketed sharding (for THREAT)

Threats are read by brand, so the bucket needs to include the brand ID:

// AFTER: Monthly-bucketed by brand
const monthBucket = timestamp.slice(0, 7); // "2026-06"
{
  PK: `THREAT#${brandId}#${monthBucket}`,   // THREAT#abc#2026-06
  SK: `ALERT#${timestamp}#${type}`,
  GSI1PK: `BRAND#${brandId}`,               // Cross-month queries
  GSI1SK: `THREAT#${timestamp}`,
  ...
}

Why monthly, not daily? Threats are lower volume than ops logs. A busy brand might get 10-50 threats per day. Monthly bucketing is sufficient to prevent hot-spotting while keeping the scatter-gather read path manageable (query last 3 months = 3 parallel queries vs 90 for daily).

Read path: GSI1 query on BRAND#brandId with SK prefix THREAT# returns threats across all monthly buckets, sorted by timestamp, no scatter-gather needed:

const threats = await queryGSI1(`BRAND#${brandId}`, "THREAT#", {
  limit: 50,
  scanForward: false,
});

This is the ideal pattern: shard writes on the base table, unify reads on a GSI.

Pattern 3: Accept the trade-off (for collection keys)

BRAND_INDEX and PRODUCT_INDEX are also single-partition keys. But brand and product registration is low-throughput: maybe 50 per day during a hackathon, maybe 500 per day in production. The 1,000 WCU per-partition limit won't be hit.

The decision: Don't shard collection keys. The engineering cost of scatter-gather reads on "list all brands" isn't justified when registration throughput will never approach the partition limit.

If it did (say, an enterprise customer bulk-importing 10,000 products via the batch endpoint), I'd switch to PRODUCT_INDEX#<shard> with N-way random sharding:

const shard = Math.floor(Math.random() * 10);
{
  PK: `PRODUCT_INDEX#${shard}`,  // Random distribution across 10 partitions
  SK: `PRODUCT#${timestamp}#${id}`,
  ...
}

Read path: scatter-gather across shards 0-9, merge, sort. But I don't need this today. YAGNI applies to partition sharding too.

How to detect hot partitions

1. Count your PK cardinality

The simplest check, no monitoring required. Read every PutItem and UpdateCommand in your codebase. For each one, ask:

  • Is this PK cardinality bounded or unbounded? PRODUCT#uuid = unbounded (good). OPS_LOG = bounded to 1 (bad).
  • Does this PK receive burst traffic? A PK that gets 1 write/hour is fine even if it's singleton. A PK that gets 1,000 writes/second needs sharding.
  • What's the growth rate? A PK with 100 items forever is different from a PK that grows by 1,000 items/day.

2. CloudWatch Contributor Insights

Enable Contributor Insights on the table. It shows the top-N partition keys by consumed capacity. If one PK is 80% of your write traffic, you have a hot partition even if you're not throttled yet. ThrottledRequests per table only fires after you're already impacted. Contributor Insights catches the problem before it hurts.

3. Write a risk matrix

Document every write operation with its PK. If you see the same PK in multiple write paths, that's a convergence signal:

Write Operation PK Risk
Register brand BRAND#uuid Low: unique per brand
Register product PRODUCT#uuid Low: unique per product
Record scan PRODUCT#uuid Medium: popular products get many scans
Write threat THREAT#brand#month Low: monthly bucketing distributes
Write ops log OPS_LOG#date Low: daily bucketing distributes
Brand index BRAND_INDEX Low: registration is low-throughput

If the Risk column says "High" for anything, shard it.

Summary: the three decisions

Hot Partition Pattern Bucket Size Read Strategy
OPS_LOG Time-bucketed Daily Scatter-gather (7 parallel queries)
THREAT#brand Time-bucketed Monthly GSI1 query (single partition)
BRAND_INDEX Accepted N/A Single partition query

The fix for OPS_LOG was 8 lines in the Lambda writer and 15 lines in the API reader. No table migration. No GSI rebuild. No downtime. The monthly THREAT bucketing was similarly surgical: change the PK format in the Lambda and switch the reader to GSI1.

That's the beauty of DynamoDB's schemaless design: you can change your partition key format mid-stream without touching existing data. New writes go to the new pattern; old data stays readable through legacy fallback queries. You don't need a migration. You need a new PutItem and a Query that checks both patterns.

The code

All changes are in a single commit: refactor: shard hot partitions, eliminate Scans, document access patterns.

Key files:

  • lambda/threat-detector.mjs: OPS_LOG daily bucketing and THREAT monthly bucketing
  • src/app/api/ops-log/route.ts: scatter-gather read across daily buckets
  • src/app/api/threats/route.ts: GSI1 read across monthly buckets
  • src/lib/dynamodb.ts: updated schema documentation

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