Skip to main content

I introduce performance anti-patterns without realizing it: the code is correct, but it doesn't scale

PhaseDetailed DesignRolesEngineerSeverityMediumApplies toAll coding agentsEvidenceResearch

In one sentence: I may deliver functionally passing code while missing query round trips, complexity, and memory budgets; measure representative workloads to assess actual performance requirements.

Symptomโ€‹

Here is the kind of code I tend to hand you:

  • You ask me to "fetch each order's customer name," and I write a loop that fires SELECT * FROM customers WHERE id = ? one row at a time โ€” 100 orders become 101 queries (the classic N+1).
  • You ask me to "check this batch of users for duplicate emails," and I write a nested loop comparing every pair, O(nยฒ). Fine at a thousand; at a hundred thousand that's tens of billions of comparisons.
  • You ask me to "validate the format of each log line," and I put re.compile(pattern) inside the per-line loop, Python caches recent patterns, so this does not establish recompilation on every line. Many distinct dynamic patterns or engines without that cache may incur repeated compilation; profile first.
  • You ask me to "merge these two configs," and I make an unnecessary deep copy of a multi-megabyte object just to change one field.
  • You ask me to "pull all the report data," and I load the whole table into memory with a single findAll() โ€” no pagination, no streaming โ€” and memory blows up as the data grows.
  • You ask me to "call three external APIs in turn," and I dutifully await them serially, even though the three requests have no dependency on each other and could run concurrently.

Every one of these passes the tests you gave me and reads cleanly. The problem isn't whether it's correct; it's whether it holds up.

Why this happensโ€‹

I may verify output values without obtaining load, data distribution, query plans, or resource budgets. Passing functional tests does not measure latency, throughput, or peak memory. Both frequent operations and one enormous batch can exceed budgets.

The EASE 2024 Leetcode study found competitive efficiency within its tested models and algorithmic tasks, not real-system database or IO performance. RobuNFR studies non-functional requirements, prompt variation, and correctness trade-offs; it does not establish that the sole problem is failing to ask for optimization. Explicit performance requirements still need correctness regression.

I should judge using query counts, profiles, representative benchmarks, and resource limits rather than training-frequency speculation or code appearance.

Consequencesโ€‹

  • The small sample fools everyone. Function correct, tests green, code review reads fine โ€” until the data volume rises and the problem erupts at the most expensive stage (production, the customer site).
  • Separate complexity from actual overhead. N+1 query count grows linearly with N, but round trips and connection contention can be expensive; pairwise scanning is O(nยฒ). Do not call both superlinear or predict production latency from big O alone.
  • The cost of optimizing is deferred and amplified. Once the plain form is woven into the business logic and spread across its callers, retrofitting a batch query or a cache later touches far more surface than getting it right once would have.
  • The resource bill creeps up quietly. Redundant queries, needless deep copies, serial remote calls translate into higher database load, more memory, longer response times โ€” all real money, and hard to trace back to any single line of code.

What to do insteadโ€‹

The core: make scale and performance expectations explicit inputs, and hold me accountable for complexity with measurements. I have no intuition for data volume, so don't make me guess.

  • State the magnitude and SLA before I write. "This table is about 5 million rows, this endpoint needs p99 < 200ms, a single request scans at most ten thousand records" โ€” one line pulls me back from assuming "small and gentle" to reality.
  • Name the anti-patterns to avoid, explicitly. "Don't query inside the loop โ€” solve it with one batch query / JOIN," "this runs over a large collection, don't use O(nยฒ)," "precompile the regex outside the loop," "these independent IO calls should run concurrently." I know these forms; I just don't reach for them by default.
  • Ask for a complexity analysis, down to big-O. "Give the time and space complexity of this code, and roughly how many operations at n=10โต." Force the scale onto the table and the slowness can't hide.
  • Demand before/after measurements, not "I optimized it." "After the change, post a comparison of query count / benchmark time, before vs after." An "optimized" with no numbers is no optimization.
  • Make the verification loop actually test performance. Give a near-real-scale dataset or a benchmark assertion (e.g. "100k rows must finish within 1 second") so the green light means "fast enough," not just "functionally correct."
  • Default to pagination / streaming for large data. "This result set could be very large โ€” use pagination or streaming, don't load it all into memory at once."

Exampleโ€‹

Before:

You: Give me a function that takes a list of orders and returns each order with its customer name.
Me: (loops and queries by customer_id one at a time โ€” N+1)
for o in orders:
o.customer_name = db.query("SELECT name FROM customers WHERE id=?", o.customer_id)
You: (tested with 3 orders, instant pass, merged and shipped)
Production: a page with 2000 orders fires 2000+ queries and takes a dozen seconds to load

After:

You: Input is a list of orders (a single page in production may be thousands).
Return each order with its customer name. Requirements: don't query inside
the loop; give the time complexity; post the before/after query count.
Me: Fetch all customers in one batch query, then map in memory โ€” queries drop from N+1 to 2.
ids = {o.customer_id for o in orders}
names = db.query("SELECT id, name FROM customers WHERE id IN (...)", ids) # 1 query
(in-memory join)
The in-memory mapping is O(n) time and O(n) space; database cost depends on indexes and plans.
Assuming one prior order query and all IDs fitting one parameter list: 1+N queries become 2.
Beyond driver/database parameter or memory limits, batch the work; queries grow with batch count.

Same requirement; add three things โ€” scale, a ban on the anti-pattern, and a demand for measurements โ€” and I go from "I can write it but it won't scale" to "I'll do the math on this cost for you."

When the exception appliesโ€‹

Writing for scale is the default, but in a few cases the plain form is the right one, and forcing an optimization is the "premature optimization" Knuth warned about:

  • Low-frequency paths with bounded per-run cost: simple code can win, but a daily batch can still time out or exhaust memory. Low frequency alone does not waive resource budgets.
  • A hard, small upper bound on size: input drawn from a fixed enum, 7 days in a week, 52 cards in a deck โ€” n is forever constant-scale, and a plain nested loop is shorter and more readable than a batch query or index; the added complexity is pure liability.
  • Readability outweighs the few microseconds here: on a path that isn't hot, a straightforward loop beats code contorted to save time โ€” no one feels the slowness, but everyone pays the unreadability on every maintenance pass.

The test: first decide whether this is a hot path (executed at high frequency, or n that grows unbounded with real data). Optimize only if it's hot; if it's cold or n has a small upper bound, put simplicity and readability first โ€” but base that call on "I know it's cold," not on "I never thought about whether it's hot."

Version notesโ€‹

Applicable versions

Rechecked both performance papers and Python re documentation on 2026-10-29. Corrected N+1 query counts to linear growth; Python caches recent patterns, so repeated calls do not imply recompilation every time. O(n) in the example covers the in-memory mapping only; database indexes, parameter limits, batching, and total memory are separate.

Further reading and sourcesโ€‹