Video in progress

In production, code turned out to be O(n²) and the service slowed down as the data grew. How do you catch such "time bombs" at the organization level?

// Order export: 300 rows in 2023, 400,000 rows in 2026
for (Order o : orders) {
    if (!result.contains(o.customerId())) {   // result is an ArrayList
        result.add(o.customerId());
    }
}

Code review alone is not enough. You need limits on input size, performance tests with real-sized data, request duration recorded in metrics together with input size, and, once a bug is found, an automatic check for that kind of pattern. The main thing is to make it clear who is responsible for which volume.

📖 Answer

On the day this code was written, there was no problem. With 300 rows, 90 thousand comparisons are unnoticeable. With 400 thousand rows it's close to 10¹¹, and the request goes down with a timeout. A LinkedHashSet instead of ArrayList.contains is a one-line fix, but it took an incident to find it.

Cases like this are usually hidden at several layers: nested loops, a DB query inside a loop (N+1), String concatenation in a loop, List.remove(0), another stream() inside stream().filter().

At the organization level, this is what I do.

I make volume visible. For each endpoint, the metrics show not only latency but also input size: an "export, number of rows" histogram. On the graph you see latency growing quadratically, not linearly, with the number of rows, before the incident.

We write limits into the contract: each API's maximum page size, file size and list length. An endpoint without a limit will get a million items from someone for sure. When the limit is exceeded, you want a clear error (413 or a validation error), not a slow response.

We test at real volume. In CI, algorithmic bugs aren't visible with small fixtures. A nightly performance test with synthetic data 2-3 times the size of prod. If a change is more than 20% slower than the previous result, that's a signal.

Static checks help as well. Some patterns can be automated: a repository call in a loop, List.contains in a loop. Error Prone or ArchUnit rules. They won't catch everything, but they catch the most common ones.

We turn postmortems into rules. After every incident, the question "did we look for this kind of mistake in other places?". Often the same pattern is in 5-6 places.

In reviews, I ask people to make "how big will n be?" a habit. If the answer is "I don't know", that's where a limit or a test is needed.