DEV Community

Cover image for Autopsy #13: The useEffect Dependency Loop That DDoSed Our Own API
frontend.rocks
frontend.rocks

Posted on Edited on Originally published at frontend.rocks

Autopsy #13: The useEffect Dependency Loop That DDoSed Our Own API

Incident Report

A filter bar refactor wrapped searchParams.get('status') inside an object literal (const filter = { status }) to match a shared hook signature. In local dev, the page rendered and updated the URL bar without visible errors.

  • T+00:00: Deployed the filter bar refactor to production.
  • T+03:00: API gateway telemetry recorded a 48x spike in GET /api/items traffic and a 64% rate of 429 Too Many Requests responses.
  • T+05:00: Client error tracking logged Maximum update depth exceeded across 19% of active dashboard sessions.
  • T+06:30: Network waterfalls showed a single filter click spawning 47 uncancelled GET /api/items?status=open requests within 420 ms while main-thread CPU hit 99%.

The Red Herring

In #inc-frontend, the team added a 300 ms debounce around the fetch() call inside useEffect. In local dev, the network tab appeared calmer for the first quarter-second.

In production, debouncing only delayed the first burst by 300 ms. The component continued re-rendering in a tight loop because the underlying dependency reference changed on every execution frame, starving the main thread and still tripping the 30 req/s gateway rate limiter.

Causal Chain

Five runtime layers amplify a single URL filter change into an API self-DDoS. Per-render heap allocation, bidirectional closure drift, Object.is() reference inequality, absent cache key deduplication, and uncancelled fetch() streams compound into rate-limit exhaustion.

Failure Simulator

Interactive Failure Simulator — Click to step through the live model

Layer Dissection

01 → 02: Fresh Heap Allocations Break Closure Stability

During each render, the component constructs const filter = { status: searchParams.get('status') ?? 'open' } directly in the function body. Under Execution Context, Call Stack & Closures, every invocation creates a new execution context and allocates a distinct object address on the V8 heap.

const filter = { status: params.get('status') ?? 'open' }; // new heap address per call
useEffect(() => {
  setMirrorFilter(filter); // schedules re-render #2 with stale searchParams closure
}, [filter, setSearchParams]);
Enter fullscreen mode Exit fullscreen mode

Simultaneously, a second useEffect copies mirrorFilter back into URLSearchParams. Because hooks read values from their own render snapshot under Stale Closures & Hook Traps, two concurrent updates bounce outdated filter values between local state and the URL bar.

02 → 03: Reference Inequality Reschedules the Effect Loop

Before committing an effect, React compares each entry in the dependency array against the previous render's array using Object.is(). Under Virtual DOM & Reconciliation, two object literals with identical properties fail reference equality:

  • Primitive string 'open': Object.is('open', 'open') returns true and skips effect execution.
  • Object literal { status: 'open' }: Object.is(@0x7f1a04, @0x7f1b88) returns false and schedules another commit.

Because the effect calls setMirrorFilter(filter) inside its body, every failed Object.is() check triggers a synchronous state update, allocating @0x7f1b88 on the next render until React hits its 50-update depth guard.

03 → 04: Absent Cache Key Deduplication Multiplies Network Traffic

Every iteration of the render loop invokes fetch('/api/items?status=' + filter.status) directly inside useEffect. Without Server-State Cache Machines, the client maintains no finite state machine or primitive cache key (['items', 'open']) to coalesce identical concurrent reads.

  • Cache miss per render: 47 renders generate 47 independent HTTP requests for the exact same payload.
  • Thundering client: No staleTime or in-flight deduplication map blocks duplicate reads from leaving the browser.

04 → 05: Uncancelled Sockets Saturate the Gateway Into 429

None of the 47 fetch() calls pass an AbortSignal or return a cleanup function. Under AbortController & Cooperative Cancellation, the browser keeps every initiated HTTP/2 stream open until the server responds or times out, stacking stale responses and tripping the 30 req/s per-IP token bucket into 429 Too Many Requests.

Architectural Fix & Invariants

function ItemsView() {
  const [params] = useSearchParams();
  const status = params.get('status') ?? 'open';
  const [items, setItems] = useState<Item[]>([]);

  useEffect(() => {
    const controller = new AbortController();
    fetch(`/api/items?status=${encodeURIComponent(status)}`, { signal: controller.signal })
      .then((res) => (res.ok ? res.json() : Promise.reject(res.status)))
      .then((data) => setItems(data))
      .catch((err) => { if (err.name !== 'AbortError') throw err; });
    return () => controller.abort();
  }, [status]);
}
Enter fullscreen mode Exit fullscreen mode

Architectural Invariants

  • Single source of truth: URL query parameters own filter state; mirror useState copies of URL values are prohibited.
  • Primitive dependency keys: useEffect and server-state cache keys accept only primitive strings, numbers, or booleans, never inline object literals.
  • Mandatory cooperative cancellation: Every effect-driven fetch() passes an AbortController.signal and aborts in its cleanup function.
  • Gateway rate-limit budget: Integration tests fail if a single filter change dispatches more than 1 network request or leaves uncancelled requests on unmount.

Golden Rule: Never pass freshly allocated objects into useEffect dependencies or mirror URL state in useState; depend on primitives, deduplicate reads by key, and abort every in-flight fetch on cleanup.

Top comments (0)