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

- **Canonical URL:** https://frontend.rocks/autopsies/useeffect-dependency-loop-ddos/
- **Case:** #13
- **Failure Mode:** Cascading Latency
- **Production Symptom:** Changing a single URL filter triggers an infinite render loop, Maximum update depth exceeded, and a burst of 429 Too Many Requests responses.
- **Last Verified:** 2026-11-17

## Causal Chain
1. [Execution Context, Lexical Environment, and Call Stack](https://frontend.rocks/concepts/execution-context-call-stack.md): Each component invocation allocates a new { filter } object reference on the V8 heap.
2. [Stale Closures in Hooks & Callbacks](https://frontend.rocks/concepts/stale-closures-hooks.md): Bidirectional synchronization between URLSearchParams and local state captures desynchronized values across render cycles.
3. [Virtual DOM & Reconciliation](https://frontend.rocks/concepts/virtual-dom-reconciliation.md): Object.is() comparison on the dependency array evaluates false on every render and reschedules the effect.
4. [Server State Cache Machines (fresh → stale → fetching)](https://frontend.rocks/concepts/server-state-cache-machines.md): Lacking a server-state cache machine with primitive key deduplication triggers a fresh fetch() on every iteration.
5. [AbortController and Cooperative Cancellation](https://frontend.rocks/concepts/abortcontroller-cancellation.md): In-flight HTTP requests never abort, saturating connections and tripping 429 rate limits on the API.

## Primary Sources
- https://react.dev/reference/react/useEffect
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
- https://dom.spec.whatwg.org/#interface-abortcontroller
- https://www.rfc-editor.org/rfc/rfc6585#section-4

---
## 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

Step through the five execution stages below to inspect V8 heap reference allocation, `Object.is()` evaluation, in-flight request stacking, and the stabilized single-source-of-truth state.

## 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](/concepts/execution-context-call-stack), every invocation creates a new execution context and allocates a distinct object address on the V8 heap.

```tsx
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]);
```

Simultaneously, a second `useEffect` copies `mirrorFilter` back into `URLSearchParams`. Because hooks read values from their own render snapshot under [Stale Closures & Hook Traps](/concepts/stale-closures-hooks), 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](/concepts/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](/concepts/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](/concepts/abortcontroller-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

```tsx
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]);
}
```

**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.
