DEV Community

Cover image for title: How I Accidentally DDoS'd My Own API (And the 2-Line React Fix) 🤡
freerave
freerave

Posted on

title: How I Accidentally DDoS'd My Own API (And the 2-Line React Fix) 🤡

We've all been there. You spend days building a "bulletproof" backend. You set up a strict Rate Limiter to protect your database from malicious bots and DDoS attacks. You feel like a Cybersecurity mastermind. 🛡️

Then, you open your own app, type a few words into the search bar, and... your backend blocks YOU.

Yep, I accidentally DDoS'd myself.

If you want to see the exact moment my backend decided to fight back, check out this quick 30-second Short I made about the incident:

(Wait, what actually happened?)

The Crime: Friendly Fire
I was building a search feature for my platform, DotSuite. I wanted the search results to update automatically as the user typed. So, I wrote a standard useEffect in React to fetch the data whenever the search state changed.

The result? For every single keystroke, my React frontend fired a new API request.
Typing "dotsuite" didn't send 1 request. It sent 8 requests in less than a second.

My backend saw this massive spike in traffic, panicked, and did exactly what I programmed it to do: It slammed me with a massive wall of 429 Too Many Requests errors.

The Fix: The Magic of "Debounce"
This is a classic rookie mistake, but the fix is a beautifully simple Senior Dev pattern called Debouncing.

Instead of spamming the server instantly, we tell the frontend: "Hey, wait for the user to stop typing for 500 milliseconds. If they are quiet for half a second, THEN send the request."

I've put together the exact code snippet showing the optimized "Debounce Code" using setTimeout and clearTimeout.

Check out the full solution in this GitHub Gist:

Why this matters:
Saves Money: Database reads aren't free. This simple pattern cuts your database reads by 90%.

Better UX: Your app won't stutter while trying to resolve 15 overlapping API responses.

No more 429 Errors: Your rate limiter can actually focus on real bad actors, not your own frontend!

Over to you!
Have you ever accidentally taken down your own app? Or written a script that backfired spectacularly? Share your "Log of Shame" in the comments below so I don't feel alone! 👇😂

I'm FreeRave, currently building developer tools at DotSuite. Drop a follow if you love seeing the messy, behind-the-scenes reality of full-stack development!

Top comments (0)