Backend EngineerMidpythonpostgresqlsql

Fix an N+1 Query

A real backend problem you debug end to end in a live cloud workspace, then show on your portfolio. No tutorial, no toy app - a broken system that behaves like production.

Level
Mid
Time
~30 min
Cost
Free

The scenario

The /api/orders endpoint is extremely slow. It fetches 100 orders, then makes a separate database query for each order's items - a classic N+1 query problem resulting in 101 total queries.

The broken code you start with

main.py (1 + N queries)
cur.execute("SELECT id, user_id, product FROM orders")
orders = cur.fetchall()
for order in orders:
    # one extra query per order - the N+1 problem
    cur.execute("SELECT name, email FROM users WHERE id = %s", (order[1],))
    user = cur.fetchone()

What this teaches you

What you did: The handler looped over orders and did SELECT * FROM users WHERE id = $1 per row - 100 orders = 100 user queries + 1 orders query = 101 round trips. Replaced with a single JOIN users ON orders.user_id = users.id (or WHERE user_id IN (...) batch) - 2 queries total.

Why it matters: N+1 is the most common SQL performance bug in ORM-heavy or "iterate then query" code. Each query is fine in isolation; the loop multiplies them into a latency disaster. The network round-trip dominates.

In the real world: ORMs offer eager-loading (select_related, with, populate). EXPLAIN ANALYZE on the response handler is the diagnostic - if you see 100 small queries instead of 1 large one, you have an N+1.

What you'll practice

Why this impresses a hiring manager

On your portfolio, this becomes

Replaced the per-order user lookup with a single JOIN (or batched WHERE IN), reducing 101 queries to 2 and response time from 5s to 200ms

Keep going

Add JWT Authentication to an APIBackend projectBackend roadmapStep by step to hiredBackend interview questionsSTAR answersAll Backend projectsProjects hub

Build this project free

You're in a real cloud workspace in 30 seconds. Fix it, and it lands on your portfolio.

Start this project →