# How the Circuit Breaker Mechanism in law-chain-hot/websocket-devtools Handles High Traffic

> Learn how law-chain-hot/websocket-devtools circuit breaker handles high traffic by pausing monitoring over 800 messages/sec. Prevent UI freezes and memory issues.

- Repository: [Brian 阿布/websocket-devtools](https://github.com/law-chain-hot/websocket-devtools)
- Tags: internals
- Published: 2026-03-05

---

**The circuit breaker mechanism in law-chain-hot/websocket-devtools automatically pauses WebSocket monitoring when traffic exceeds 800 messages per second to prevent UI freezing and memory overflow.**

The law-chain-hot/websocket-devtools repository provides a browser extension for debugging WebSocket connections. To protect the DevTools panel from becoming unresponsive during traffic spikes, the extension implements a distributed circuit breaker that monitors message rates across content scripts, background scripts, and the React-based panel UI.

## Circuit Breaker Architecture

The circuit breaker mechanism operates across three distinct extension contexts to ensure consistent state management and failure isolation:

- **Content Script ([`src/content/injected.js`](https://github.com/law-chain-hot/websocket-devtools/blob/main/src/content/injected.js))**: Maintains per-connection traffic counters using a sliding window and triggers the breaker when thresholds are exceeded
- **Background Script ([`src/background/background.js`](https://github.com/law-chain-hot/websocket-devtools/blob/main/src/background/background.js))**: Persists the circuit state globally and synchronizes across tabs
- **DevTools Panel ([`src/devtools/panel.jsx`](https://github.com/law-chain-hot/websocket-devtools/blob/main/src/devtools/panel.jsx))**: Displays real-time status and handles user-initiated recovery

### Traffic Detection in the Content Script

In [`src/content/injected.js`](https://github.com/law-chain-hot/websocket-devtools/blob/main/src/content/injected.js), the `checkTrafficAndCircuitBreak` function maintains a sliding-window counter (`connectionTraffic`) for each unique `connectionId`. Every intercepted WebSocket message invokes this checker to update the per-second count. When the count exceeds `TRAFFIC_PAUSE_THRESHOLD` (800 msg/s) within a one-second window, the mechanism immediately sets `proxyState.isMonitoring` to `false` and dispatches a `circuit-breaker-triggered` event via `window.postMessage` (lines 405-411 and 424-436).

### State Propagation Through the Extension

The background script listens for the `circuit-breaker-triggered` message type. Upon receipt at lines 142-147 in [`src/background/background.js`](https://github.com/law-chain-hot/websocket-devtools/blob/main/src/background/background.js), it updates the global `websocketData.isMonitoring` flag to `false` and logs a warning to the console. This ensures that all extension contexts recognize the high-traffic condition simultaneously and stop processing new messages to prevent memory bloat.

### UI Feedback and Recovery

The DevTools panel ([`src/devtools/panel.jsx`](https://github.com/law-chain-hot/websocket-devtools/blob/main/src/devtools/panel.jsx)) listens for the same event and updates the React component state accordingly. It displays a warning banner showing the detected rate (stored in `circuitBreakerRate`) and disables the monitoring toggle to reflect the paused state (lines 88-96). Users can resume monitoring by clicking the **Monitor** button, which invokes `handleStartMonitoring` to reset the flag and clear the banner (lines 52-59).

## Simulating High Traffic to Test the Circuit Breaker

You can verify the circuit breaker mechanism by programmatically generating a message flood in the browser console:

```javascript
// Execute in the DevTools console with an active connection ID
const CONNECTION_ID = 'ws_main_1690000000000_1'; // Replace with your connection ID

for (let i = 0; i < 1000; i++) {
  window.postMessage({
    source: "websocket-proxy-injected",
    type: "websocket-event",
    payload: {
      type: "message",
      id: CONNECTION_ID,
      direction: "incoming",
      timestamp: Date.now(),
      data: `load-test-${i}`
    }
  }, "*");
}

```

When the message rate crosses 800 messages per second, the panel will display a "High Traffic Detected" banner and stop capturing new messages until manually resumed.

## Listening for Circuit Breaker Events

External scripts or debugging tools can monitor the circuit state by listening for the specific event type broadcast by the content script:

```javascript
window.addEventListener("message", (event) => {
  const { source, type, payload } = event.data || {};
  
  if (source === "websocket-proxy-injected" && type === "websocket-event") {
    if (payload?.type === "circuit-breaker-triggered") {
      console.warn(
        `Breaker activated on ${payload.connectionId}: ${payload.messagesPerSecond} msgs/s`
      );
    }
  }
});

```

## Resuming Monitoring Programmatically

To re-enable monitoring without using the UI button, send a runtime message to the background script:

```javascript
chrome.runtime.sendMessage({
  type: "proxy-state-change",
  data: { isMonitoring: true }
});

```

The background script forwards this to the panel, which clears the warning banner and resets `proxyState.isMonitoring` to `true`, allowing message interception to resume immediately.

## Summary

- The **circuit breaker mechanism** uses a sliding-window counter in [`src/content/injected.js`](https://github.com/law-chain-hot/websocket-devtools/blob/main/src/content/injected.js) to detect when WebSocket traffic exceeds **800 messages per second** for any connection
- When triggered, it sets `proxyState.isMonitoring` to `false` and broadcasts a `circuit-breaker-triggered` event across extension contexts via `window.postMessage`
- The **background script** persists this state globally in `websocketData`, while the **DevTools panel** displays a warning banner and disables message capture to protect the UI
- Users can resume monitoring via the **Monitor** button, which invokes `handleStartMonitoring` in the panel component to reset the state
- The system prevents UI freezing and memory overflow while allowing developers to manually re-enable inspection after traffic subsides

## Frequently Asked Questions

### What triggers the circuit breaker in websocket-devtools?

The circuit breaker triggers when the message rate for any single WebSocket connection exceeds 800 messages per second within a one-second sliding window. This threshold is defined as the constant `TRAFFIC_PAUSE_THRESHOLD` in [`src/content/injected.js`](https://github.com/law-chain-hot/websocket-devtools/blob/main/src/content/injected.js).

### Where is the circuit breaker state stored?

The state is distributed across three locations: the content script maintains `proxyState.isMonitoring` as the detection authority, the background script stores it in `websocketData.isMonitoring` for global persistence, and the DevTools panel keeps it in React component state for UI rendering. The background script acts as the synchronization hub between contexts.

### How do I resume monitoring after the circuit breaker activates?

Click the **Monitor** button in the DevTools panel. This calls `handleStartMonitoring` in [`src/devtools/panel.jsx`](https://github.com/law-chain-hot/websocket-devtools/blob/main/src/devtools/panel.jsx), which resets the `isMonitoring` flag and clears the traffic warning banner. You can also resume programmatically by sending a `proxy-state-change` message with `isMonitoring: true` to the background script, which will propagate the change to all extension contexts.

### Can I adjust the 800 messages per second threshold?

The threshold is hardcoded as `TRAFFIC_PAUSE_THRESHOLD` in [`src/content/injected.js`](https://github.com/law-chain-hot/websocket-devtools/blob/main/src/content/injected.js) (referenced around line 405 in the source). To modify it, you must fork the repository, change this constant value, and rebuild the extension. There is no runtime configuration option for the threshold in the current implementation.