Order API Spikes from 80ms to 4s: Three Thread Pool and Timeout Traps That Looked Normal
At 3:07 that afternoon, monitoring started alerting.
The average response time of the order interface jumped from 80ms to 4 seconds, and the error rate curve shot almost vertically upward. I opened the dashboard and saw a perfectly "normal" picture: CPU usage 40%, memory stable, no GC anomalies, database connections only a few dozen. All the basic metrics looked like nothing was wrong, but on the user side, orders kept spinning and then timing out.
That incident was eventually traced to a thread pool configuration line. But during the process of fixing it, we stumbled into three pitfalls, each more hidden than the last, and every time we fixed one, it led to the next. Looking back afterwards, these three pitfalls were actually different symptoms of the same root cause. I want to write down this experience completely, because it's worth remembering for anyone writing Java backends.
Pitfall 1: All remote calls share one thread pool
Let me first describe the system background. This is a typical order service that calls three downstream services in sequence: coupon, inventory, and risk control. At the time, the team, for "simplicity," used a single common thread pool to handle all these remote calls, and that thread pool was created with Executors.newFixedThreadPool.
The problem lay in these two decisions.
How the incident happened
That day, one of the coupon service's interfaces, due to a downstream database hiccup, saw response time rise from 20ms to 8 seconds. It just became slower, not dead.
But that "slowness" dragged our order service down.
Because all remote calls shared one thread pool, the slow coupon requests began to occupy threads heavily. Each request waited 8 seconds before releasing a thread, and the pool quickly filled up. Subsequent requests, including those that didn't depend on coupons at all and just wanted to check order status, all got stuck in the queue.
Worse, newFixedThreadPool uses an unbounded queue (the default capacity of LinkedBlockingQueue is Integer.MAX_VALUE). Requests kept coming in, threads stayed occupied, and the queue piled up without limit. Memory started to rise and eventually crashed the entire JVM.
The essence of this first pitfall: different business calls share one thread pool, and one slow call can "drown" all other calls. This has a specific name in academia, and the Bulkhead pattern is exactly what addresses it. Just like a ship's hull is divided into sealed compartments, so that flooding in one compartment doesn't sink the whole ship, thread pools should be isolated by dependency too.
What we thought was the "fix" turned out to be the start of the next pitfall
After locating the problem, we made a decision that seemed right at the time: give each downstream its own thread pool. One for coupons, one for inventory, one for risk control, each isolated, so whoever is slow carries the burden alone.
At the moment of deployment, the coupon problem was indeed isolated; it was slow, but order queries were no longer affected. We breathed a sigh of relief.
Then the load test results came back and we were stunned: the overall throughput of the order interface dropped instead of rising, 15% slower than before.
Pitfall 2: Mismatch between thread pool and database connection pool
The second pitfall is the most counterintuitive and the one most worth writing about.
Symptom: more threads made things slower
After isolating the thread pools, to "improve performance," we increased the core thread count of each business thread pool from 20 to 50. The logic was simple: more threads, higher concurrency, naturally higher throughput.
The result was throughput dropped, while the CPU context-switching metric spiked.
At first we suspected the overhead of the newly introduced thread pools, but after investigating we found the problem was in the database connection pool: our HikariCP pool had always been configured with 20 connections, and we hadn't touched it.
So 50 business threads were competing for 20 database connections, and 30 threads were blocking waiting for connections. When threads went from 20 to 50, the truly useful ones were still 20; the other 30 only added lock contention and context switching. When the thread count exceeds the database connection count, the extra threads are pure burden.
Root cause: connection pool is not bigger-is-better, nor smaller-is-better
I want to correct a more common misconception: many people's first reaction is "then adjust the connection pool to 50 too." That's wrong.
The official HikariCP pool sizing document is counterintuitive: the database connection pool should be small, and let application threads queue for connections. The famous formula from the document is:
connections = ((core_count * 2) + effective_spindle_count)
For a 4-core machine with a single disk, it computes to 9, and the document recommends 10. It even mentions Oracle's performance team running an experiment: reducing the connection pool from 2048 to 96 dropped application response time from about 100ms to about 2ms, 50x faster.
Why? Because database connections essentially use CPU, disk, and network serially. Once you exceed the database's true parallel processing capability, adding more connections only brings context-switching overhead, and throughput drops instead of rising. The sentence from that document stuck with me:
You want a small pool, saturated with threads waiting for connections.
So the real solution is not "make both sides equal," but form a reasonable ratio between thread count and connection count, and let the wait happen at the right place.
Specifically, here's what we did:
- Split the connection pool by business type: long-transaction batch tasks use one pool, online real-time queries use another. The HikariCP document also mentions that systems mixing long and short transactions are the hardest to tune, and splitting into two pools often works well.
- Bring thread pool sizes back to a restrained value: anchor on the database connection count, and don't let business threads vastly exceed the number of connections that can run in parallel.
- Use a semaphore for concurrency caps: what really needs to be limited is the "concurrent load hitting the database," not a blanket thread count.
After fixing the second pitfall, throughput recovered. We thought it was finally over.
Then during a peak-season mock drill, the third pitfall surfaced, and this one was the nastiest.
Pitfall 3: Timeouts don't propagate, and retries killed the downstream
Symptom: downstream was only a bit slow, but we broke it
During the peak-season drill, the coupon service's P99 latency rose to 3 seconds due to heavy load. Our order service's timeout for calling it was set to 5 seconds, which looked sufficient.
But the problem was: the order service's upstream, the API gateway, had a 2-second timeout for the order interface.
So a chain reaction occurred:
- The gateway timed out at 2 seconds; the order service hadn't yet gotten the coupon's 5-second result, so the gateway gave up.
- Once the gateway timed out, it retried the order interface.
- The order service received the retry and initiated another coupon call.
- The coupon service was already struggling with 3-second slow requests, now its request volume doubled.
- The coupon service got slower, more orders timed out, the gateway retried more...
A positive feedback loop formed. Within seconds, the coupon service's request volume multiplied several times, going from "a bit slow" to completely down.
This is a retry storm. Google's SRE book, Chapter 21, "Handling Overload" calls this phenomenon combinatorial retry explosion. When every layer of a deep call stack retries, the retry count multiplies rather than adds. That chapter has a harsh line: a failed request should only be retried by the layer directly above the one that rejected it; multiple layers retrying simultaneously is combinatorial explosion.
Root cause 1: Timeouts have no "budget" concept
The first mistake we made was treating timeouts as isolated numbers. Gateway 2 seconds, order 5 seconds, coupon 8 seconds, each looks "reasonable" on its own, but their relationship was wrong.
Downstream timeouts must be less than upstream timeouts, with headroom left over. Otherwise, by the time the upstream has given up and returned the request to the user, the downstream is still running obliviously. These "orphan requests" continue consuming resources and press the system at its most vulnerable moment.
The correct approach is decreasing timeout budgets: starting from the gateway, each layer's time budget is smaller than the one above. If the gateway gives 2 seconds, the order service should only give, say, 1.5 seconds or less to downstream calls, keeping 0.5 seconds for its own processing and return.
Root cause 2: Retries have no cost awareness
The second mistake was a too-naive retry policy: retry on timeout, up to three times, with no backoff and no budget.
AWS's retry with backoff documentation is clear: retries must be spaced with exponential backoff, otherwise many clients will retry at the same moment, forming spikes. It also stresses idempotency; if the retried operation isn't idempotent, retries cause data duplication.
Google SRE's solution is more systematic, and I think it's the real answer to this problem:
- Per-request retry budget: each request retries at most 3 times; after that, let the error bubble up.
- Per-client retry budget: each client tracks the "retry request ratio," and only allows retries when it's below 10%. The data in the document is telling: with only per-request limits, request volume can still rise to nearly 3x; with the 10% per-client budget, it typically gets suppressed to 1.1x.
- "Overloaded; don't retry" error code: when the server detects it's overloaded, it returns an error that explicitly tells the caller "don't retry," cutting off the positive feedback at the source.
There's also an action that should have been taken earlier: circuit breaking. When the coupon service is clearly unhealthy, the order service should short-circuit and take degraded logic (like "coupon temporarily unavailable, order at original price") instead of repeatedly hitting the wall. This is also the fail-fast mentioned in AWS documentation: for non-transient faults, failing fast is far more efficient than retrying repeatedly.
Three pitfalls, one root cause
Putting the three pitfalls side by side, you'll find they look different on the surface: thread pool contamination, connection count mismatch, retry storm. But the root cause is the same:
Resources have no boundaries, and failures propagate uncontrollably.
- Pitfall 1: The thread pool has no boundaries, and one slow dependency's failure spreads to all calls.
- Pitfall 2: Concurrency has no boundaries, threads grow unboundedly beyond what the system can truly handle.
- Pitfall 3: Retries have no boundaries, upstream failures get amplified layer by layer, backfiring on an already fragile downstream.
Once you see this, the solutions become unified. I later summarized three design principles for the team, and now I go through them every time I do system design:
First, any shared resource must have isolation and caps. Thread pools are isolated by dependency using the bulkhead pattern; queues must be bounded with explicit rejection policies; concurrency must have explicit numbers, not rely on defaults. Java's ThreadPoolExecutor allows precise control of corePoolSize, maximumPoolSize, queue capacity, and rejection policy, which is why it's safer than the Executors factory methods.
Second, timeout is a budget that decreases layer by layer from entry to exit. Don't configure timeouts in isolation; treat them as shares of a chain. Downstream timeouts are always less than upstream, with headroom left for processing.
Third, failure propagation must have circuit breakers. Retries need budgets and backoff; overload must fail fast; dependencies must be able to be circuit-broken and degraded. A system's robustness doesn't come from "never failing" but from "not spreading when it fails."
Closing thoughts
After that incident, it took us about two weeks to do a systematic overhaul: thread pool isolation, connection pool splitting, timeout budget propagation, and integrating circuit breaking and retry budgets. Later, we went through peak seasons again; the coupon service still wobbled a few times, but the order interface never snowballed again.
My biggest takeaway wasn't learning a specific configuration parameter, but changing my judgment of what "system is normal" means. Previously I looked at CPU, memory, GC, and thought if those were green, the system was fine. Now I know that real danger often hides behind those green metrics: a gradually growing queue, a retry with no cap, an unrelated interface silently slowed down by a shared thread pool. They don't alert until one day they all break out together.
The value of an architect often lies in seeing these "invisible boundaries." These three principles aren't hard to understand, but the hard part is thinking about them before you start writing code, not, like me, paying for them with a production incident.
References
- HikariCP. About Pool Sizing (official wiki). https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing
- Resilience4j. Bulkhead (official documentation). https://resilience4j.readme.io/docs/bulkhead
- Forero Cuervo A. Site Reliability Engineering, Chapter 21: Handling Overload. Google, 2016. https://sre.google/sre-book/handling-overload/
- AWS. Retry with backoff pattern, AWS Prescriptive Guidance. https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/retry-backoff.html
- Oracle. ThreadPoolExecutor (Java™ Platform Standard Ed. 8 API Documentation). https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html