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

推荐订阅源

V2EX - 技术
V2EX - 技术
P
Privacy International News Feed
Security Latest
Security Latest
H
Hacker News: Front Page
T
Tenable Blog
The Hacker News
The Hacker News
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
S
Security @ Cisco Blogs
Project Zero
Project Zero
O
OpenAI News
AI
AI
Spread Privacy
Spread Privacy
C
CERT Recently Published Vulnerability Notes
The Last Watchdog
The Last Watchdog
G
GRAHAM CLULEY
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Scott Helme
Scott Helme
Application and Cybersecurity Blog
Application and Cybersecurity Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
C
CXSECURITY Database RSS Feed - CXSecurity.com
NISL@THU
NISL@THU
A
Arctic Wolf
T
Threat Research - Cisco Blogs
PCI Perspectives
PCI Perspectives
N
News and Events Feed by Topic
C
Cyber Attacks, Cyber Crime and Cyber Security
C
Cybersecurity and Infrastructure Security Agency CISA
Simon Willison's Weblog
Simon Willison's Weblog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Know Your Adversary
Know Your Adversary
Google Online Security Blog
Google Online Security Blog
罗磊的独立博客
L
LINUX DO - 最新话题
U
Unit 42
S
Security Affairs
有赞技术团队
有赞技术团队
WordPress大学
WordPress大学
博客园 - 【当耐特】
T
The Exploit Database - CXSecurity.com
S
Schneier on Security
月光博客
月光博客
Engineering at Meta
Engineering at Meta
腾讯CDC
F
Full Disclosure
Cyberwarzone
Cyberwarzone
S
SegmentFault 最新的问题
Recorded Future
Recorded Future
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
博客园 - 司徒正美
The Cloudflare 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
Building a Database Performance Testing Tool With AI: The Honest Breakdown
Alicia Maria · 2026-05-21 · via DEV Community

It still feels a little strange to have AI writing practically all the code — but I decided to give it a real shot on this new project. A bit of context: I was running low on project ideas to share here, so I asked the AI for a list and picked one called Database Performance Testing. The goal was to run performance tests against a relational database. I built it in roughly two days, and in this article I want to share my honest impressions — both technical and about the AI-assisted workflow itself.


Why run performance tests on a database?

I think this is the first question we need to ask before starting any project. As it happens, I'm currently on a project where data performance is a critical system concern — which got me thinking: what would it look like to run performance tests directly against a relational database?

From a QA perspective, performance isn't just about how the API connects to the database. It's also about how queries are written and how the chosen database handles query concurrency, especially in synchronous systems. A slow endpoint isn't always a slow endpoint — sometimes it's a slow query hiding behind it. That's what drove me to start here.


What are we testing?

For this project, we have four distinct test scenarios:

  • N+1 Query Detection
  • Deadlock Simulation
  • Query Regression Tracking Across Schema Changes
  • Slow Queries

N+1 Query Detection

N+1 is a classic performance problem in applications that access databases — especially systems using ORMs like Entity Framework, SQLAlchemy, or Sequelize. The name describes exactly what happens: instead of one optimized query, the application ends up running 1 initial query + N additional queries.

Consider an e-commerce system that lists 20 orders and shows the email of each order's user. A naive approach would be:

SELECT id, user_id FROM orders LIMIT :n;
SELECT email FROM users WHERE id = :uid;

Enter fullscreen mode Exit fullscreen mode

The first query fetches the orders. The second query then runs 20 times — once per order. That's your N+1. The consequences at scale include multiplied latency, cache pollution, and unpredictable response times for users.

This can also appear in concurrent scenarios. Two threads both fetching user data simultaneously, each triggering their own cascade of lookups, can quickly multiply database load in ways that are hard to trace without instrumentation.


Deadlock Simulation

Imagine two transactions happening concurrently:

Transaction A:

UPDATE orders SET status = 'pending' WHERE id = 1;
UPDATE orders SET status = 'paid'    WHERE id = 2;

Enter fullscreen mode Exit fullscreen mode

Transaction B (running simultaneously, in reverse order):

UPDATE orders SET status = 'paid'    WHERE id = 2;
UPDATE orders SET status = 'pending' WHERE id = 1;

Enter fullscreen mode Exit fullscreen mode

Each transaction holds a lock the other needs. The database detects the cycle and resolves it by rolling back one of the transactions — but that rollback has a cost. At scale, this kind of contention can cause noticeable latency spikes and, in the worst case, lock up parts of your application. The goal of the deadlock test isn't just to confirm that a deadlock can*happen, but to measure *how the database recovers and what the timing impact looks like.


Query Regression Tracking Across Schema Changes

This scenario focuses on measuring the impact of schema changes — index creation, migrations, table alterations — on query execution plans and timings. It captures EXPLAIN ANALYZE output before and after a migration, then diffs the results.

This is especially useful for:

  • Validating that an optimization actually improved things before merging
  • Documenting schema versions and their performance characteristics over time
  • Supporting production investigations when run periodically as a baseline

Slow Queries

The slow query tests act as a latency gate — a set of critical queries that must stay under a defined threshold (configured in config.py as SLOW_QUERY_THRESHOLD_MS). If any of these queries breach the threshold in CI, the pipeline fails.

Think of it as a performance budget for your most important database operations. In this project, five critical queries were monitored. Here are the results from a low-volume benchmark run:

Query Avg (ms) p95 (ms) Max (ms)
user_lookup 0.20 0.29 0.35
order_history 0.31 0.43 0.75
inventory_search 0.24 0.32 0.62

All three passed the threshold comfortably. But the value here isn't just the green light — it's having a historical baseline. The next time someone adds a filter, changes a join, or drops an index, you'll know immediately if these numbers move.


The solution structure

Here's how the project is organized:

.
├── config.py                          # DB_URL and SLOW_QUERY_THRESHOLD_MS
├── conftest.py                        # pytest fixtures: engine, instrumented_engine
├── pyproject.toml                     # pytest config and markers
├── requirements.txt
├── analysis/
│   ├── n_plus_one_detector.py         # N+1 detection and simulation
│   ├── deadlock_simulator.py          # Concurrent deadlock demo
│   └── explain_analyzer.py            # EXPLAIN plan capture and diff
├── benchmarks/
│   ├── queries/                       # Raw .sql files (12 queries)
│   ├── scenarios/
│   │   └── run_benchmark.py           # Volume benchmark runner
│   ├── test_n_plus_one.py             # N+1 detection tests
│   ├── test_deadlock.py               # Deadlock tests
│   ├── test_explain.py                # EXPLAIN ANALYZE plan tests
│   └── test_slow_queries.py           # Latency threshold gate (5 critical queries)
├── data/
│   ├── seed.py
│   └── distributions.json
├── migrations/
│   ├── baseline/
│   │   └── 001_initial_schema.sql
│   └── v2_add_indexes/
│       └── 002_add_indexes.sql        # Sample migration for regression demo
├── reports/
│   ├── query_regression_report.py     # Delta reporter (also exports to Grafana)
│   ├── export_metrics.py              # Writes results to benchmark_results table
│   ├── output/                        # Timestamped benchmark JSON results
│   └── plans/                         # Saved EXPLAIN plans
├── scripts/
│   └── setup_schema.py                # Apply migration + snapshot schema
├── .github/
│   └── workflows/
│       └── performance-tests.yml      # CI: schema → seed → pytest
└── docker/
    ├── docker-compose.yml             # PostgreSQL + Grafana
    ├── init.sql
    └── grafana/
        ├── provisioning/
        └── dashboards/benchmark.json  # Auto-provisioned dashboard

Enter fullscreen mode Exit fullscreen mode

A few things worth highlighting in this structure:

analysis/ is designed to be run independently. Each module — N+1 detection, deadlock simulation, EXPLAIN analysis — can be executed on its own. You don't have to run the full suite every time. This matters in practice: there are moments where you only care about regression tracking after a migration, and running deadlock simulation alongside it is just noise.

explain_analyzer.py captures and diffs EXPLAIN plans. This is what powers the query regression scenario — it saves plan snapshots before and after a schema change and computes the delta. The results are stored under reports/plans/ as timestamped JSON files.

Grafana is provisioned automatically. The benchmark_results table gets populated by export_metrics.py after each run, and the dashboard in grafana/dashboards/benchmark.json is auto-loaded. No manual setup needed.


What the data actually showed

The most interesting results came from the query regression scenario. After adding a composite index (idx_orders_user_created) via migration 002_add_indexes.sql, the EXPLAIN plans for order_history changed dramatically:

Before the index — Sequential Scan:

  • Execution time: 0.532ms
  • The planner scanned the entire orders table (touching 39 blocks) and filtered out 2,497 rows to find 3 matching records
  • Total cost estimate: 101.27

After the index — Bitmap Index Scan:

  • Execution time: 0.090ms
  • The planner used idx_orders_user_created directly, reading only 5 blocks
  • Total cost estimate: 10.92

That's an 83% reduction in execution time and a ~10x drop in planner cost — from a full table scan touching 2,500 rows down to a targeted index lookup. Without the regression tracking in place, this kind of change would have been invisible unless someone happened to run EXPLAIN manually.

This is exactly the kind of validation that's worth having in CI: you add an index, run the suite, and get a clear before/after diff that confirms the optimization actually worked.


On building with AI: the honest take

This is where I want to spend some real time, because the AI-assisted workflow was just as interesting to reflect on as the technical output itself.

What I actually did was prompt the AI for a project idea, refine the scope, and then iteratively ask it to generate the solution — structure first, then individual modules, then the CI pipeline. I didn't write much code from scratch. What I did was spend a significant amount of time reading what it produced, questioning whether the test logic made sense, and validating that the scenarios matched the real-world problems they were meant to simulate.

What felt different about this workflow compared to writing everything myself:

  • I spent more time thinking about whether the tests were correct than about how to implement them. That's actually a good shift for a QA-focused project — but it felt unfamiliar.
  • The AI was excellent at boilerplate and structure (docker-compose setup, pytest fixtures, file organization) and decent at logic, but it needed guidance on edge cases and test validity.
  • I felt genuinely uncertain about "ownership" of the result. The code works, I understand it, and I made real decisions throughout — but I also couldn't have shipped it in two days without the AI. That's a strange feeling to sit with.

Where it genuinely helped: spinning up the Docker + Grafana integration was something I would have spent half a day on manually. The AI had a working docker-compose.yml with auto-provisioned dashboards in minutes. That alone was worth it for a POC.

Where it fell short: the AI tends to produce confident-looking code that needs careful review. A few of the generated SQL files had column names that didn't match the schema. The N+1 detection logic needed an extra pass to handle the concurrent case correctly. None of these were blockers, but they reinforced that the human-in-the-loop isn't optional — it's the job.

I'll keep experimenting with AI-assisted workflows, particularly for testing tooling and POCs. If you've built something similar or have thoughts on the approach, I'd love to hear it in the comments. You can see the full solution here.


Key takeaways

  • Database performance testing is a QA concern, not just a backend one. Slow queries, N+1 patterns, and regression after migrations are all things a QA engineer should be equipped to catch.
  • EXPLAIN plans are underused. Having automated before/after diffs on schema changes is low-effort and high-value. The index migration result above would have been invisible otherwise.
  • Modular test design matters. Being able to run N+1 detection independently from deadlock simulation means you can integrate specific checks into specific workflows without overhead.
  • AI accelerates, but doesn't replace judgment. The two days I spent on this were productive — but the value came from the decisions I made, not from the code the AI generated.

I'll keep experimenting with AI-assisted workflows, particularly for testing tooling and POCs. If you've built something similar or have thoughts on the approach, I'd love to hear it in the comments.You can check the full solution here.