Skip to content

bug: Blocking Docker calls in async lifecycle functions freeze entire backend #42

Closed

Description

@vybe

Summary

The recreate_container_with_updated_config() function in the agent lifecycle service is marked async but contains synchronous blocking Docker SDK calls that are not wrapped in run_in_executor(). When container recreation is triggered, these blocking calls freeze the FastAPI event loop for 10-30+ seconds, causing all other API requests to time out and the UI to become unresponsive.

Component

Backend / Agent Service / Lifecycle

Priority

P1

Error

No explicit error - manifests as:

  • API requests returning HTTP 499 (client timeout)
  • /api/telemetry/host and other endpoints timing out
  • WebSocket connections dropping
  • UI pages failing to load
  • Docker health check marking backend as "unhealthy"

Example from logs:

INFO:     ('172.28.0.6', 40848) - "WebSocket /ws" [accepted]
INFO:     connection closed
INFO:     ('172.28.0.6', 56940) - "WebSocket /ws" [accepted]
INFO:     connection closed
# Rapid reconnection attempts as clients timeout

Frontend logs showing 499s during incident:

"GET /api/telemetry/host HTTP/1.1" 499 0
"GET /api/setup/status HTTP/1.1" 499 0
"GET /api/agents HTTP/1.1" 499 0

Location

  • File: src/backend/services/agent_service/lifecycle.py
  • Lines: 277-430 (approximately)
  • Function: recreate_container_with_updated_config()

Root Cause

The function is defined as async but contains multiple synchronous Docker SDK calls that block the event loop:

async def recreate_container_with_updated_config(agent_name: str, old_container, owner_username: str):
    # ...
    
    # These are ALL blocking calls - NOT using run_in_executor:
    old_container.stop()                              # ~1-5 seconds blocking
    old_container.remove()                            # ~1 second blocking
    docker_client.volumes.get(shared_volume_name)     # blocking
    docker_client.volumes.create(...)                 # blocking
    docker_client.containers.run('alpine', ...)       # ~2-5 seconds blocking
    docker_client.containers.run(image, ...)          # ~2-5 seconds blocking

Since FastAPI uses a single-threaded async event loop, these blocking calls prevent ANY other requests from being processed. With multiple Docker operations taking 10-30+ seconds combined, the entire backend becomes unresponsive.

Reproduction Steps

  1. Have a Trinity instance with multiple agents running
  2. Trigger a container recreation (e.g., change API key setting, modify shared folder config, or have a task fail that triggers recreation)
  3. Immediately try to load the UI or make API calls
  4. Observe that all requests timeout until the Docker operations complete
  5. Check frontend logs for HTTP 499 status codes

Suggested Fix

Wrap all blocking Docker SDK calls in asyncio.to_thread() (Python 3.9+) or loop.run_in_executor():

import asyncio

async def recreate_container_with_updated_config(agent_name: str, old_container, owner_username: str):
    # ... existing setup code ...
    
    # Stop and remove old container - NOW NON-BLOCKING
    try:
        await asyncio.to_thread(old_container.stop)
    except Exception:
        pass
    await asyncio.to_thread(old_container.remove)
    
    # Volume operations - NOW NON-BLOCKING
    try:
        await asyncio.to_thread(docker_client.volumes.get, shared_volume_name)
    except docker.errors.NotFound:
        await asyncio.to_thread(
            docker_client.volumes.create,
            name=shared_volume_name,
            labels={...}
        )
    
    # Container creation - NOW NON-BLOCKING
    # Note: containers.run() with many args needs a wrapper function
    def create_container():
        return docker_client.containers.run(
            image,
            detach=True,
            name=f"agent-{agent_name}",
            # ... all other args ...
        )
    
    new_container = await asyncio.to_thread(create_container)

Alternative using a shared executor (matches telemetry.py pattern):

from concurrent.futures import ThreadPoolExecutor

_docker_executor = ThreadPoolExecutor(max_workers=4)

async def recreate_container_with_updated_config(...):
    loop = asyncio.get_event_loop()
    
    await loop.run_in_executor(_docker_executor, old_container.stop)
    await loop.run_in_executor(_docker_executor, old_container.remove)
    # ... etc

Note: The routers/telemetry.py file already uses this pattern correctly for Docker stats - the same approach should be applied to lifecycle.py.

Environment

  • Trinity version: b2b8f06
  • Docker version: 28.3.3
  • OS: Ubuntu (Debian-based container)

Related

  • src/backend/routers/telemetry.py - Example of correct async Docker handling with run_in_executor
  • src/backend/services/agent_service/lifecycle.py - Primary file needing fixes
  • Similar blocking calls may exist in other lifecycle functions (start_agent, stop_agent, etc.) - recommend auditing entire file

Impact

When triggered, this bug causes:

  • Complete UI unresponsiveness for 10-30+ seconds
  • All scheduled tasks to queue up
  • WebSocket disconnections
  • Potential cascade effects if multiple recreations are triggered

Activity

  1. vybe commented on Feb 24, 2026

    @vybe
    ContributorAuthor

    Update: Blocking Docker Calls Are Widespread

    Further investigation shows blocking Docker SDK calls exist across multiple files, not just lifecycle.py:

    Affected Files and Blocking Calls

    File Functions Blocking Calls
    services/agent_service/lifecycle.py recreate_container_with_updated_config() stop(), remove(), volumes.get/create(), containers.run()
    services/agent_service/crud.py create_agent() volumes.get/create(), containers.run() (2x - alpine + agent)
    services/agent_service/terminal.py handle_terminal_ws() exec_create(), exec_start(), exec_resize()
    services/agent_service/helpers.py Various volumes.get()
    services/monitoring_service.py Various containers.get()
    services/system_agent_service.py Various containers.run()

    Impact

    Every one of these operations blocks the FastAPI event loop:

    • Creating an agent: Blocks for 5-15+ seconds during volume creation and container start
    • Opening a terminal: Blocks during exec_create and exec_start
    • Resizing terminal: Blocks on exec_resize
    • Container recreation: Blocks for 10-30+ seconds (already documented)
    • Health checks/monitoring: Blocks on containers.get

    Recommended Fix

    Create a shared Docker operations module that wraps all Docker SDK calls:

    # services/docker_ops.py
    import asyncio
    from concurrent.futures import ThreadPoolExecutor
    from functools import partial
    
    # Shared executor for all Docker operations
    _docker_executor = ThreadPoolExecutor(max_workers=8, thread_name_prefix="docker-ops")
    
    async def run_docker_op(func, *args, **kwargs):
        """Run a blocking Docker SDK call without blocking the event loop."""
        loop = asyncio.get_event_loop()
        return await loop.run_in_executor(
            _docker_executor,
            partial(func, *args, **kwargs)
        )
    
    # Usage:
    # await run_docker_op(docker_client.containers.run, image, detach=True, ...)
    # await run_docker_op(container.stop)
    # await run_docker_op(docker_client.api.exec_create, container_id, cmd, ...)

    Then systematically replace all direct docker_client.* calls with await run_docker_op(docker_client.*, ...).

  2. vybe commented on Mar 2, 2026

    @vybe
    ContributorAuthor

    Resolved ✅

    Fixed in DOCKER-001 (2026-02-24).

    All blocking Docker SDK calls are now wrapped in asyncio.run_in_executor() via the centralized docker_utils.py module. 13 async wrapper functions cover all container, volume, and exec operations.

    Files Updated

    • services/docker_utils.py - NEW core utility module (287 lines)
    • services/agent_service/lifecycle.py - All Docker calls now async
    • services/agent_service/crud.py - All Docker calls now async
    • services/agent_service/terminal.py - Uses api_exec_create, api_exec_start
    • services/agent_service/helpers.py - check_shared_folder_mounts_match() now async
    • routers/agents.py - Delete/stop/reload calls wrapped
    • routers/ops.py - Fleet restart/stop calls wrapped
    • services/system_agent_service.py - Container ops wrapped
    • services/ssh_service.py - All credential methods now async
    • services/docker_service.py - execute_command_in_container() now async
    • services/git_service.py - Awaits async container commands

    Impact

    Scenario Before After
    Container recreation 10-25s event loop block 0s block
    Agent start 2-5s block 0s block
    Agent stop/delete 1-8s block 0s block
    Concurrent HTTP requests Queued/timeout Processed normally
    WebSocket connections Dropped during ops Stable

    Documentation

    • Feature flow: docs/memory/feature-flows/async-docker-operations.md
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority-p1type-bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions