Skip to main content

๐Ÿž Production Bug: 100% CPU Spike from Empty Catch Block — Fixed with Spring Retry! ๐Ÿ˜ฎ๐Ÿ”ฅ

  ๐ŸŒช️ The Chaos Begins

It was a normal day in production... until suddenly, one server started heating up ๐Ÿ”ฅ. And I don’t mean metaphorically — its CPU usage shot up to 100% and stayed there, like it had chugged 10 cups of espresso ☕๐Ÿ’ฅ.

No OutOfMemoryError.
No Exceptions.
No logs screaming for help.
Just... silence and a fan spinning like a helicopter ๐ŸŒ€.

๐Ÿงฉ The Initial Clues

We SSH'd into the server and ran:


top -H -p <java_process_id>

We noticed one thread hogging the CPU — continuously.

Then we used VisualVM to peek inside.
Stack trace of that CPU-hogging thread looked like this:


at com.example.MyProcessor.process(MyProcessor.java:42) at com.example.MyProcessor.run(MyProcessor.java:30) ...

Hmm… That class wasn’t doing anything fancy. Just a retry mechanism inside a loop.


๐Ÿ” The Suspect Code

Here’s what the code looked like:


while (true) { try { doSomeCriticalOperation(); break; // Exit on success } catch (Exception e) { // ๐Ÿ™ˆ Empty catch — suppresses all errors silently } }

Looks innocent, right? But this was the silent killer. ๐Ÿ˜ฌ


๐Ÿง  What's Actually Happening?

Let’s break it down:

  • doSomeCriticalOperation() was failing due to a misconfiguration in a service dependency.

  • The exception was caught and silently ignored.

  • The loop kept retrying immediately — without delay, logging, or even sleeping.

  • This meant the thread entered a tight loop, running full-speed without yielding the CPU.

๐Ÿ’ก Result: One thread spins at 100%, wasting CPU cycles, doing absolutely nothing productive.

Now imagine this inside a microservice deployed across 10 pods. If every pod had even one such spinning thread… ๐Ÿ’ฅ chaos.


๐Ÿงฏ How We Fixed It (Spring Retry to the Rescue!)

Instead of writing manual retry loops (which can go wrong as we saw), we went with a production-grade solution: Spring Retry — and it was a game changer.


✅ Spring Retry — Simple Yet Powerful!

Step 1: Add dependencies (Maven):


<dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> </dependency>

Step 2: Enable Retry in Spring Boot App


@EnableRetry @SpringBootApplication public class MyApp { }

Step 3: Annotate the method you want to retry


@Service public class MyService { @Retryable( value = { RemoteServiceException.class }, maxAttempts = 3, backoff = @Backoff(delay = 2000, multiplier = 2)) public void doSomeCriticalOperation() { // Your code that may fail temporarily System.out.println("Trying critical operation..."); throw new RemoteServiceException("Oops! Remote system failed"); } @Recover public void recover(RemoteServiceException e) { // This is called if all retries fail System.out.println("Recovering gracefully after retries failed"); } }

๐Ÿค” What’s Happening Here? — Let Me Explain

๐Ÿ” @Retryable — Automatic Retry Logic

When you annotate a method with @Retryable, Spring will automatically retry that method if it throws the specified exception.

Here's what this means in plain English:


@Retryable( value = { RemoteServiceException.class }, maxAttempts = 3, backoff = @Backoff(delay = 2000, multiplier = 2) )

๐Ÿ’ก Breakdown:

  • value: What exception(s) to retry on. Here, RemoteServiceException.

  • maxAttempts = 3: Try a total of 3 times (initial + 2 retries).

  • backoff: Adds a delay between attempts.

    • delay = 2000: Start with 2 seconds delay.

    • multiplier = 2: Delay grows exponentially (2s → 4s → 8s...).

So, if the method fails:

  • First retry after 2 seconds,

  • Second retry after 4 seconds,

  • Third retry after 8 seconds,

  • ... then give up.

๐Ÿ›‘ @Recover — Graceful Fallback After All Retries Fail

If even after all retries the method still keeps failing, the method annotated with @Recover will be called.

This is like your “Plan B” — for logging, alerts, or triggering a failover.

⚠️ Very Important:
The method signature of @Recover must match the original method + the exception type as the first parameter.


❓ Common Doubt: Will @Recover Be Called If Retry Succeeds?

Great question — and it’s one that confuses many people!

๐Ÿง  Question:

If my @Retryable method fails once, but then succeeds on the second retry, will @Recover still be called?

๐ŸŸข Answer:

No. @Recover is only called if all retry attempts fail.

Here’s what happens:

  • ✅ If the method succeeds in any retry → Spring considers it successful → @Recover is not called.

  • ❌ If it fails in all attempts → @Recover will be triggered with the last thrown exception.

๐Ÿ“Š Quick Example:

With this config:


@Retryable( value = RemoteServiceException.class, maxAttempts = 3, backoff = @Backoff(delay = 1000) )
  • 1st attempt fails

  • 2nd attempt succeeds ✅
    → @Recover will NOT be called

But if:

  • 1st attempt fails

  • 2nd attempt fails

  • 3rd attempt fails
    → Now Spring gives up and calls the method annotated with @Recover ๐Ÿ›‘


✅ Always remember:

Spring Retry calls @Recover only as a final fallback — not during intermediate retries.

๐Ÿ’ก Why It’s Better Than Manual Retry

✅ No tight loops
✅ No wasted CPU
✅ Controlled retry with backoff
✅ Easy configuration
✅ Better observability
✅ Cleaner code = fewer bugs


๐ŸŽ Final Thought

Replacing our naive while(true) with Spring Retry instantly improved the system’s resilience and clarity. And the best part? Even junior developers could now read and understand what’s going on — thanks to annotations and structured retries.


๐Ÿ”š Wrapping Up

This bug taught me one thing:
Even something as small as an empty catch block can trigger chaos. And with tools like Spring Retry, we don’t just patch things — we make our systems smarter and safer. ๐Ÿ’ช

So next time something fails — don’t spin in circles ๐Ÿ”„.
Retry smart, sleep well. ๐Ÿ˜ด

Have you used Spring Retry before? Or hit similar retry nightmares? Drop your stories in the comments — I’d love to hear them!

๐Ÿช„ Written by: Anand @ JavaBeanBag

Comments

Popular posts from this blog

๐Ÿฑ Tomcat vs ⚡ Netty – Which One Should You Use?

๐Ÿฑ Tomcat vs ⚡ Netty – Which One Should You Use? So recently I got curious about this too ๐Ÿค”. Everywhere in Spring Boot tutorials we see Tomcat . Then suddenly while exploring Spring WebFlux , the name Netty pops up. And I was like – “Wait, who’s this Netty guy trying to replace Tomcat?” ๐Ÿ˜… Let’s break it down with real-time examples , icons , and fun comparisons . ๐Ÿฑ Tomcat – The Traditional Web Server Type: Servlet Container (blocking I/O) World: Used with Spring MVC Style: Thread-per-request model ๐Ÿ‘ฉ‍๐Ÿ’ป Pros: Stable, widely used, battle-tested Cons: Struggles with huge concurrent connections ๐Ÿ‘‰ Example in real life: Tomcat is like a restaurant with fixed waiters ๐Ÿด. - Each customer = one thread/waiter - If too many customers come in at once → waiters run out → customers wait outside ๐Ÿšช ⚡ Netty – The Reactive Rockstar Type: Asynchronous Event-Driven Network Framework World: Default for Spring WebFlux Style: Event-lo...

๐ŸŽญ Spring’s Secret: Why @Transactional & Friends Betray You Silently

๐Ÿ’ก Lesson Learned — Not a Prod Bug, But a Real Pain No, this wasn’t a production outage. Nobody screamed at me. But I sat for 3 hours wondering: “Why the heck is my @Transactional not rolling back!?” ๐Ÿ˜ต‍๐Ÿ’ซ “Why is Redis cache not working?” ๐Ÿคฏ Turned out, the issue was one silent villain: ๐Ÿงฑ Self-invocation ๐Ÿคท What Is @Transactional ? If you're new: @Transactional = Tells Spring to start a DB transaction when a method is called. It’ll commit if everything’s okay. It’ll rollback if something fails. ๐Ÿง  Think of it like wrapping your code in: try { beginTransaction(); // your logic commit(); } catch(Exception e) { rollback(); } ๐Ÿ•ต️ Real-Life Analogy — The Gateway Community ๐Ÿ˜️ Let me tell you about my society — it has a strict watchman at the gate. Here’s how it works: ๐Ÿ›‚ Watchman = Spring Proxy ๐Ÿ  Your apartment = Your service class ๐Ÿšช Your room = A method inside that class ๐Ÿƒ Scenario 1: Outsider Visits Your friend from outside...

๐Ÿงต Virtual Threads in Java — The Ultimate Guide with Diagrams, Code & Interview Qs!

๐Ÿš€ “How are Virtual Threads different from Thread Pools?” ๐Ÿ˜ต “Are they OS threads or JVM threads?” ๐Ÿ™ƒ “Should I still use CompletableFuture?” ๐Ÿคฏ “How do I even use them in real-time microservices?” ๐Ÿง  What are Virtual Threads? Virtual Threads (introduced in Java 21 as stable ๐ŸŽ‰) are lightweight threads managed by the JVM instead of the OS kernel. ๐Ÿ‘‰ They look like normal threads, but don’t hog OS resources like traditional threads. ๐Ÿง  What is the OS Kernel? ๐Ÿ›️ OS Kernel = The Brain of the Operating System It’s the core part of your OS (Windows, Linux, Mac) that: Manages memory ๐Ÿง  Schedules threads ๐Ÿ•’ Talks to hardware ๐Ÿ’ป Handles I/O operations ๐Ÿ“จ When you create a traditional thread in Java, the JVM asks the OS Kernel to create a real OS-level thread. ๐Ÿ–ผ️ Imagine This... ┌───────────────────────────┐ │ Your Java Application │ └────────────┬──────────────┘ │ ...