Chrome "Aw, Snap! Out of Memory" after hours of WebRTC calls: leaked RTCPeerConnections
Support agents on our video desk saw Chrome crash with Out of Memory after a long shift of calls. Every hang-up left a peer connection, camera tracks and video elements alive. Here is how we proved the leak and the teardown that fixed it.
Our support team runs a browser-based video desk: an agent picks up a call from a queue, talks to the customer for a few minutes, hangs up, and takes the next one. The app is a single-page React app that stays open for a whole eight-hour shift. Around six hours in, agents started seeing the Chrome crash page instead of the queue:
Aw, Snap!
Something went wrong while displaying this webpage.
Error code: Out of Memory
It happened only to the busiest agents, those taking 60 or more calls per shift. Agents with a quiet day never saw it. Reloading the tab fixed it until the next long session.
Reproducing it
We wrote a script that joined a test room, waited ten seconds, hung up and repeated. With Chrome's fake capture flags it ran unattended overnight on a spare desktop:
google-chrome \
--use-fake-device-for-media-stream \
--use-fake-ui-for-media-stream \
--user-data-dir=/tmp/webrtc-soak \
https://desk.example.com/soak?calls=300
Chrome's own Task Manager (Shift+Esc on Windows and Linux, Window menu on macOS) showed the tab's memory footprint climbing by roughly 25 MB per call and never coming back down. After about 150 calls the renderer died with the same Out of Memory page.
What we ruled out
A browser bug in a specific Chrome version. The soak test reproduced on two Chrome releases and on Edge, which shares the Chromium engine. A real engine leak would be unlikely to be that consistent across builds, so we looked at our own code first.
The chat transcript or call history list. We disabled both components in the soak build. The growth per call did not change.
Large getStats payloads. We sample stats every two seconds for a quality indicator. Turning sampling off reduced growth slightly but did not stop it, which turned out to be a clue rather than a dead end.
Root cause
chrome://webrtc-internals listed one RTCPeerConnection entry per call the tab had ever made, not just the active one. A heap snapshot confirmed it: after 40 calls there were 40 RTCPeerConnection objects, 40 local MediaStream objects and 80 detached HTMLVideoElement nodes still reachable. Our hang-up handler sent a "leave" message to the signalling server and unmounted the call view, but it never called pc.close(), never stopped the local camera and microphone tracks, and the stats interval closure kept a reference to the old connection alive.
What is happening under the hood
An RTCPeerConnection is not a plain JavaScript object. Behind it Chrome keeps network sockets, ICE agents, jitter buffers, decoders and encoders. The JavaScript wrapper is small in a heap snapshot, but the native resources it owns are not. The WebRTC specification says those resources are released when close() is called, and a connection that is never closed has no reason to give them back while something still references it.
Three separate things kept the old calls alive in our app:
No
close(). Unmounting a React component does not close a peer connection. The connection kept its transports until ICE consent checks failed on the remote side, and even then the object stayed in thefailedstate, reachable from our call store.Live tracks.
pc.close()does not stop the localMediaStreamTrackobjects you captured withgetUserMedia(). Each call grabbed a fresh camera stream, so each call left a capture pipeline running. The camera light stayed on because the newest track was always live, so nobody noticed the old ones.Element and closure references. Detached
<video>elements still hadsrcObjectset to the remote stream, and asetIntervalcallback that calledpc.getStats()held the connection in its closure because we only cleared the interval when the component re-rendered, not on unmount.
Chromium also caps how many peer connections one page may hold. When that cap is reached, new RTCPeerConnection() throws an error instead of crashing. Our agents ran out of memory long before reaching it because each connection carried video decoders.
Environment
Component | Version / value |
|---|---|
OS | Windows 11 23H2 and Ubuntu 24.04 LTS (agent desktops) |
Browser | Chrome 141 stable, Edge 141 |
App | React 19, custom signalling over WebSocket, SFU-based rooms |
Media | 720p camera, Opus audio, one remote participant per call |
Session length | 8 hours, 40-80 calls |
Minimal reproduction
The original hang-up path, reduced to its essentials:
// call.js — broken teardown (excerpt)
export async function startCall(roomId, videoEl) {
const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
const pc = new RTCPeerConnection({ iceServers: ICE_SERVERS });
stream.getTracks().forEach((t) => pc.addTrack(t, stream));
pc.ontrack = (e) => { videoEl.srcObject = e.streams[0]; };
const statsTimer = setInterval(async () => {
callStore.quality = summarize(await pc.getStats());
}, 2000);
callStore.calls.push({ roomId, pc, stream, statsTimer });
await negotiate(pc, roomId);
}
export function hangUp(roomId) {
signalling.send({ type: 'leave', roomId });
// UI unmounts; pc, stream and timer are never released
}
Who is affected
Any long-lived single-page app that creates a new peer connection per call or per participant: contact-centre tools, telehealth dashboards, classroom apps, and SFU clients that rebuild connections on reconnect. Short sessions hide the problem because a page reload frees everything. The leak is in application code, so it shows up in every Chromium-based browser and, with different numbers, in Firefox and Safari too.
The fix
We gave each call a single owner object with one dispose() method, and made hang-up, network failure and component unmount all go through it. Event listeners are registered with an AbortController signal so one abort() removes all of them.
// call.js — fixed (excerpt)
export async function startCall(roomId, videoEl) {
const abort = new AbortController();
const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
const pc = new RTCPeerConnection({ iceServers: ICE_SERVERS });
stream.getTracks().forEach((t) => pc.addTrack(t, stream));
pc.addEventListener('track', (e) => { videoEl.srcObject = e.streams[0]; }, { signal: abort.signal });
pc.addEventListener('connectionstatechange', () => {
if (pc.connectionState === 'failed') call.dispose();
}, { signal: abort.signal });
const statsTimer = setInterval(async () => {
if (pc.signalingState === 'closed') return;
callStore.quality = summarize(await pc.getStats());
}, 2000);
const call = {
roomId,
disposed: false,
dispose() {
if (this.disposed) return;
this.disposed = true;
clearInterval(statsTimer);
abort.abort();
stream.getTracks().forEach((t) => t.stop());
pc.getReceivers().forEach((r) => r.track && r.track.stop());
pc.close();
videoEl.srcObject = null;
callStore.calls = callStore.calls.filter((c) => c !== call);
},
};
callStore.calls.push(call);
await negotiate(pc, roomId);
return call;
}
export function hangUp(call) {
signalling.send({ type: 'leave', roomId: call.roomId });
call.dispose();
}
In the React view, the effect cleanup calls the same method, so navigating away from the call screen can never skip teardown:
useEffect(() => {
let call;
startCall(roomId, videoRef.current).then((c) => { call = c; });
return () => call && call.dispose();
}, [roomId]);
We also stopped capturing a new camera stream for every call. The agent's local stream is now acquired once per shift and shared, with track.enabled toggled when the agent mutes. That removed one capture pipeline per call even before the leak fix.
Alternatives and trade-offs
Reuse one peer connection for the whole shift. With an SFU you can keep a single connection and swap transceivers per call. It is the most efficient option but makes renegotiation logic harder. We kept one connection per call for simpler failure handling.
Force a reload every N calls. It works as a stopgap and we shipped it for two days, but it hides the bug and drops any state the agent had open.
FinalizationRegistryas a safety net. Tempting, but finalizers only run after the object is already unreachable, which was exactly what was not happening. Explicit teardown is the only reliable fix.
How to test the fix
We added an end-to-end test that runs 50 calls with fake media and checks that nothing is left behind. It counts connections through a small debug hook the app exposes in test builds:
// soak.spec.js (Playwright, Chromium)
test('50 calls leave no peer connections behind', async ({ page }) => {
await page.goto('/soak?debug=1');
for (let i = 0; i < 50; i++) {
await page.click('#start-call');
await page.waitForFunction(() => window.__debug.activeCalls() === 1);
await page.click('#hang-up');
}
const open = await page.evaluate(() => window.__debug.activeCalls());
expect(open).toBe(0);
});
The overnight soak run on a real desktop was the second check: 300 calls, memory footprint flat within about 40 MB of the starting point, and chrome://webrtc-internals listing a single entry at any time during a call.
Confirming in production
We record a per-tab memory sample when the browser exposes one and send it with our client telemetry, along with the count of open peer connections. After the rollout, the 95th percentile of peer connections per tab dropped from 37 at end of shift to 1. Crash reports with the Out of Memory code from the video desk went from roughly a dozen per week to zero over the following month.
For spot checks on an agent's machine, open chrome://webrtc-internals during a shift. You should see one connection while a call is active and none between calls. A growing list means a code path skips dispose().
Regression guard
The 50-call Playwright test runs in CI on every merge that touches the call module.
A lint rule in our project bans
new RTCPeerConnectionoutsidecall.js, so every connection goes through the owner object.In development builds,
dispose()logs a warning if it finds a live local track after cleanup.
Security implications
The leak had a privacy side: because old capture tracks were never stopped, the camera stayed active between calls even when the UI showed no call. The browser's capture indicator stayed on, but agents learned to ignore it. Stopping tracks in dispose() means the indicator now reflects reality, which matters for user trust and for any policy that says capture ends when the call ends. The fix adds no new attack surface.
Prevention checklist
Give every peer connection one owner with an idempotent
dispose()that closes it, stops tracks and clears timers.Call
dispose()from hang-up, failure and unmount paths, not from just one of them.Remove listeners with an
AbortControllersignal instead of keeping references to handlers.Set
srcObject = nullon video elements you are about to remove.Run a soak test with fake media before shipping any change to call setup or teardown.
References
W3C WebRTC 1.0,
RTCPeerConnection.close(): https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-closeMDN,
MediaStreamTrack.stop(): https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack/stopChrome DevTools, record heap snapshots: https://developer.chrome.com/docs/devtools/memory-problems/heap-snapshots
Chrome DevTools, fix memory problems: https://developer.chrome.com/docs/devtools/memory-problems
MDN,
AbortSignalwithaddEventListener: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
Add a label
Embed this post
<iframe src="https://hibug.me/webrtc-chrome-desktop-out-of-memory-peerconnection-leak" width="700" height="420" frameborder="0" loading="lazy"></iframe>
I have spent most of my career on the side of software that pages people at night: payment integrations, web platforms with real traffic, CI/CD pipelines, Kubernetes clusters and the databases underneath them. Somewhere along the way I started keeping a notebook of every bug that cost more than an hour — the exact error, what we ruled out, the real root cause and how we proved the fix. Hibug is where those notes live. Every post follows the same path: Investigate, Explain, Fix, Verify — with the environment spelled out, the fix tested, and the security angle checked.
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.