The Desi Architect
Notes / Docker Sandboxes / GraphQL Under Pressure: N+1 Database Explosion & Query Depth Attack Defense
Docker Sandboxes · Tier 2: Data & Scale · Lab 70

GraphQL Under Pressure: N+1 Database Explosion & Query Depth Attack Defense

Why does GraphQL make it trivially easy for clients to accidentally bring down your database? Reproduce the classic N+1 query explosion where 1 frontend request triggers 101 SQL queries on PostgreSQL, fix it using DataLoader batching (101 queries down to 3), and defend against malicious recursive query bombs using AST depth limiting.

Time25 minutes
StackGraphQLPorts 18370, 18371
MemoryAbout 120 MB
Before thisLab 04SQL Basics with PostgreSQL
Verified runWindows, Mac, LinuxBash and PowerShell
  1. 1PrepareWhat you will learn
  2. 2PredictGuess before you run
  3. 3RunStep by step
  4. 4ObserveWhat you should see
  5. 5Break itChange one thing
  6. 6Clean upLeave nothing running
On this page
  1. 00 / What You Will Learn
  2. 01 / Why It Matters
  3. 02 / What We Are Building
  4. 03 / Words You Need
  5. 04 / Predict First
  6. 05 / Step by Step
  7. 06 / What You Should See
  8. 07 / Look Inside
  9. 08 / Break It, Fix It
  10. 09 / In Real Projects
  11. 10 / Interview Corner
  12. 11 / Clean Up

00 /What You Will Learn

By the end you will be able to
  • Diagnose how independent field-level resolvers create catastrophic N+1 query storms in relational databases.
  • Measure query amplification programmatically using database query counters and pg_stat_statements.
  • Implement the DataLoader pattern to coalesce individual foreign key lookups into single batched SQL queries.
  • Analyze query Abstract Syntax Trees (AST) to detect and reject deeply nested recursive denial of service queries.
  • Evaluate the architectural tradeoffs between REST fixed endpoints, GraphQL flexibility, and persisted queries.

Before you start

Complete Lab 04 (SQL Basics with PostgreSQL) and Lab 15 (Database Indexing & Slow Queries) first. You should understand primary keys, foreign keys, and SQL query execution. Docker Desktop must be running.