Skip to content

perf: Backend CPU saturation at 45% with ~30 agents due to WebSocket churn and polling storms #73

Closed

Description

@vybe

Summary

Backend CPU usage reaches ~45% (two Python workers at ~28% each) on a 4-vCPU instance running ~30 agents and 2-3 concurrent browser users. The root cause is a combination of excessive WebSocket connection churn from agent sidecars and aggressive frontend polling from multiple browser tabs. The system becomes sluggish under what should be a manageable load.

Component

Backend / WebSocket Handler / Frontend Polling

Priority

P2

Observed Behavior

# docker stats snapshot
trinity-backend    44.92%    236.1MiB / 15.62GiB

# WebSocket churn: ~1,841 open/close events in 2,000 log lines
INFO: ('172.28.0.x', NNNNN) - "WebSocket /ws" [accepted]
INFO: connection open
INFO: connection closed
# (repeating hundreds of times)

# Frontend polling: single user with agent detail page open generates
# multiple requests per second to /activity, /stats, /git/status endpoints

Root Causes

1. Agent Sidecar WebSocket Reconnection Storm

Each of the ~30 agent containers runs a sidecar (agent-server.py) that maintains a WebSocket connection to the backend. These connections appear to disconnect and reconnect frequently, creating a churn of open/close cycles. With 30+ agents, this creates a constant stream of WebSocket handshakes.

2. Frontend Polling Frequency

The frontend polls multiple endpoints at high frequency when agent detail pages are open:

  • /api/agents/{name}/activity - polled every ~2-3 seconds
  • /api/agents/{name}/stats - polled every ~2-3 seconds
  • /api/agents/{name}/git/status - polled every ~2-3 seconds

A single user with one agent detail tab generates ~3 requests/second. Multiple tabs or users multiply this linearly. Observed: one user with multiple tabs generating floods of identical requests.

3. No Request Coalescing or Throttling

Each polling endpoint independently queries Docker or the agent sidecar. There's no caching layer, request deduplication, or rate limiting on these high-frequency endpoints.

Reproduction Steps

  1. Deploy a Trinity instance with 25-30 agents running
  2. Have 2-3 users open the dashboard and agent detail pages in browsers
  3. One user opens multiple browser tabs on different agent detail pages
  4. Monitor backend CPU: docker stats trinity-backend
  5. Observe CPU climbing to 40-50% on a 4-vCPU machine

Suggested Improvements

Short-term

  • Cache agent stats/activity responses for 5-10 seconds — these endpoints query Docker which is expensive
  • Increase frontend polling intervals from ~2-3s to 10-15s for non-critical endpoints (git status, activity)
  • Use SSE or persistent WebSocket for agent updates instead of polling — the backend already has WebSocket infrastructure

Medium-term

  • Investigate sidecar WebSocket stability — why are connections churning? Add reconnection backoff and keepalive
  • Add server-side rate limiting on polling endpoints per user session
  • Batch agent stats collection — collect all agent stats in one Docker API call instead of per-agent

Long-term

  • Replace polling with push model — backend pushes agent state changes over WebSocket to subscribed frontends
  • Consider uvicorn worker tuning — currently 2 workers may not be optimal for this I/O-bound workload
  • Add request coalescing — if 3 tabs request the same agent stats within 1 second, serve from a single Docker query

Environment

  • Trinity version: f50ee3e
  • Docker version: 29.2.1
  • OS: Ubuntu 22.04.5 LTS
  • Instance: 4 vCPU, 16 GB RAM
  • Agents running: ~30
  • Concurrent browser users: 2-3

Related

  • src/backend/main.py — WebSocket handler
  • src/backend/routers/agents.py — agent stats/activity endpoints
  • src/agent-base/agent-server.py — sidecar WebSocket client
  • src/frontend/ — polling intervals in agent detail components

Activity

  1. vybe commented on Apr 16, 2026

    @vybe
    ContributorAuthor

    Additional Finding: N+1 Permissions Fetch

    Investigation of 15-second dashboard load times with 12+ agents revealed an unaddressed N+1 problem in permission edge fetching.

    Current Behavior

    fetchPermissionEdges() in stores/network.js:152-219 makes N parallel API calls - one GET /api/agents/{name}/permissions per agent. Each call:

    • Does Docker container lookup (get_agent_container())
    • Queries DB for permissions (db.get_permitted_agents())
    • Returns all accessible agents (redundant data repeated N times)

    With 12+ agents = 12+ HTTP round trips, even parallelized.

    Proposed Fix

    Add bulk endpoint GET /api/agents/permissions-edges that returns all permission edges in a single query:

    def get_all_permission_edges() -> List[dict]:
        cursor.execute('SELECT source_agent, target_agent FROM agent_permissions')
        return [{'source': r[0], 'target': r[1]} for r in cursor.fetchall()]

    Frontend changes:

    1. Replace N fetch calls with single bulk endpoint
    2. Move permission fetch out of fetchAgents() - call once on mount
    3. Update via WebSocket on permission change (future)

    Impact

    • Reduces 12+ API calls to 1
    • Eliminates redundant Docker lookups and data transfer
    • Expected 50-70% reduction in initial load time
  2. added 3 commits that reference this issue on May 30, 2026
  3. added
    complexity-medium
    theme-infrastructure
    on Jun 3, 2026
  4. vybe commented on Jun 11, 2026

    @vybe
    ContributorAuthor

    Root mechanism identified — delta from the 2026-06-11 repo audit:

    The CPU saturation this issue observes has a concrete primary mechanism: list_all_agents_fast() calls containers.list() without sparse=True (src/backend/services/docker_service.py), which docker-py implements as 1+N synchronous inspects — ~5ms per container, executed directly on the asyncio event loop. At 200 agents that's ~1s of event-loop blockage per call, and it's invoked from the operator-queue 5s tick, the heartbeat tick, monitoring, GET /api/agents, and even the stats cache-HIT path. Verifiers found 8 additional sync Docker call sites in routers/ops.py.

    Two fixes, both cheap relative to the payoff:

    1. sparse=True + asyncio.to_thread offload in list_all_agents_fast and the other sync Docker sites.
    2. Per-worker poller duplication: every lifespan background loop starts once per uvicorn worker, so prod's --workers 2 doubles every sweep (this already caused one documented SQLite-contention incident). Needs leader election (Redis SET NX) or moving fleet sweeps to a single-runner process.
  5. added
    status-ready
    and removed on Jun 14, 2026
  6. added
    status-in-progress
    and removed
    status-ready
    on Jun 22, 2026
  7. AndriiPasternak31 commented on Jun 22, 2026

    @AndriiPasternak31
    Contributor

    /claim

  8. github-actions commented on Jun 22, 2026

    @github-actions

    @AndriiPasternak31 This issue is already assigned to AndriiPasternak31. Use /unclaim first if you want to take over.

  9. added
    status-in-dev
    and removed
    status-in-progress
    on Jun 24, 2026
  10. removed
    status-in-dev
    on Aug 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

complexity-mediumpriority-p2theme-infrastructuretype-bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions