The Complete Production SOP: How to Deploy and Run Uvicorn ASGI Server Tuning & Gunicorn Worker Management in Autonomous AI Agents
Production SOP to install and execute Uvicorn ASGI Server Tuning & Gunicorn Worker Management in Codex, Claude Code, Cursor, and Windsurf.
Technical Overview & Architectural Context
Autonomous coding agents frequently generate brittle or naive deployment scripts when configuring ASGI runtimes like FastAPI and Starlette. Left unconstrained, models commonly invoke single-process development servers (`uvicorn main:app --reload`) directly in production, fail to account for multi-core hardware allocation, or misconfigure Gunicorn process wrappers by omitting the required worker class (`uvicorn.workers.UvicornWorker`). Furthermore, agents frequently overlook event loop optimizations like uvloop and httptools, leaving high-concurrency microservices bottlenecked on default Python asyncio event loops. The `uvicorn-asgi-server-worker-tuning` skill enforces strict deterministic operational boundaries across autonomous agent runtimes. By injecting proven procedural parameters—including CPU-bound worker math, graceful connection draining timeouts, socket reuse policies, and uvloop verification protocols—the agent deterministically crafts production-grade deployment manifests, Dockerfiles, and orchestration configurations without manual developer remediation.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Create the local skill manifest directory and inject verified procedural rules into agent runtime contexts.
Agent runtimes such as Claude Code, Cursor, and Codex automatically scan directory trees like `.agents/skills` or `.claude/skills` for YAML frontmatter matching runtime triggers. Installing the skill ensures the autonomous LLM recognizes the execution boundaries whenever production deployment or server tuning queries are processed.
mkdir -p .agents/skills/uvicorn-asgi-server-worker-tuning && cat <<'EOF' > .agents/skills/uvicorn-asgi-server-worker-tuning/SKILL.md
---
name: "uvicorn-asgi-server-worker-tuning"
description: "Deploy high-concurrency FastAPI/Starlette applications with Uvicorn and Gunicorn processes."
metadata:
author: "Encode"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "tune uvicorn workers"
- "gunicorn uvicornworker production"
- "uvloop performance uvicorn"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---
# Uvicorn ASGI Server Tuning & Gunicorn Worker Management
Configures Uvicorn production deployments: tuning worker counts (gunicorn -k uvicorn.workers.UvicornWorker), loop backends (uvloop), HTTP parser (httptools), SSL termination, and graceful shutdown timeouts.
## When to Invoke
Invoke this skill whenever you need to:
- tune uvicorn workers
- gunicorn uvicornworker production
- uvloop performance uvicorn
## Execution SOP & Rules
1. Install performance extras: pip install uvicorn[standard] uvloop httptools.
2. Run with Gunicorn: gunicorn -w 4 -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000 app.main:app.
3. Set graceful shutdown: --graceful-timeout 30 --timeout 60.
4. Verify uvloop event loop is active in startup logs: 'Using asyncio event loop: uvloop'.
## Verification Checklist
- Run local linting, syntax validation, and type-checks before reporting completion.
- Ensure all created or modified files adhere to workspace boundaries and avoid uncommitted secrets.
- Verify tests or build commands exit cleanly with return code 0.
EOF---
name: "uvicorn-asgi-server-worker-tuning"
description: "Deploy high-concurrency FastAPI/Starlette applications with Uvicorn and Gunicorn processes."
metadata:
author: "Encode"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "tune uvicorn workers"
- "gunicorn uvicornworker production"
- "uvloop performance uvicorn"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---Mounting the skill locally in `.agents/skills` keeps rule enforcement deterministic while avoiding excessive token bloat in global system prompts.
Ensure `shell_exec: false` remains respected by agents during configuration file generation so arbitrary server commands aren't executed uninspected.
Production Dependency Ingestion & Gunicorn Configuration
Direct the agent to generate a deterministic gunicorn_conf.py rather than passing raw shell flags.
High-throughput production setups require an external configuration module defining dynamic worker calculation based on CPU core availability (e.g., `(2 x $NUM_CORES) + 1`), graceful termination windows, and worker recycling thresholds to prevent memory leakage.
cat <<'EOF' > gunicorn_conf.py
import multiprocessing
import os
# Dynamic core allocation
default_workers = (multiprocessing.cpu_count() * 2) + 1
workers = int(os.getenv("WEB_CONCURRENCY", default_workers))
worker_class = "uvicorn.workers.UvicornWorker"
bind = os.getenv("BIND", "0.0.0.0:8000")
keepalive = int(os.getenv("KEEP_ALIVE", "5"))
timeout = int(os.getenv("TIMEOUT", "60"))
graceful_timeout = int(os.getenv("GRACEFUL_TIMEOUT", "30"))
# Worker lifecycle management to avoid memory fragmentation
max_requests = int(os.getenv("MAX_REQUESTS", "1000"))
max_requests_jitter = int(os.getenv("MAX_REQUESTS_JITTER", "100"))
accesslog = "-"
errorlog = "-"
loglevel = os.getenv("LOG_LEVEL", "info")
EOFimport multiprocessing
import os
workers = int(os.getenv("WEB_CONCURRENCY", (multiprocessing.cpu_count() * 2) + 1))
worker_class = "uvicorn.workers.UvicornWorker"
bind = "0.0.0.0:8000"
graceful_timeout = 30
timeout = 60
max_requests = 1000
max_requests_jitter = 100Setting `max_requests` and `max_requests_jitter` prevents simultaneous worker restarts while continuously recycling long-lived Python memory heaps.
In containerized environments (Kubernetes, AWS ECS), `multiprocessing.cpu_count()` may report host hardware instead of container quotas; enforce `WEB_CONCURRENCY` manually via environment variables.
Triggering Agent Execution via Targeted Context Prompts
Trigger deterministic worker tuning using standardized domain keywords.
Provide the AI agent with a prompt matching registered triggers such as 'gunicorn uvicornworker production' or 'tune uvicorn workers'. The agent's rule engine matches the query to the skill manifest, loading production constraints into active reasoning context.
python -m pip install "uvicorn[standard]>=0.30.0" "gunicorn>=22.0.0" "uvloop>=0.19.0" "httptools>=0.6.0"Use verbatim triggers in agent instructions to bypass fallback heuristic reasoning and trigger SKILL.md SOP paths directly.
Avoid vague commands like 'run fastapi server'; explicitly instruct 'tune uvicorn workers with gunicorn for production' to prevent development `--reload` flags from slipping in.
Verification, Linting & Output Quality Gate
Execute automated self-healing checks to verify uvloop binding and zero-failure process initialization.
The agent must verify that Gunicorn initiates Uvicorn workers using the high-performance `uvloop` asyncio loop implementation and that clean process signal handling (SIGTERM) drains in-flight requests within the graceful timeout window.
python -c "import uvloop, httptools, gunicorn; import uvicorn.workers.UvicornWorker; print('Verification Succeeded: ASGI Stack Ready')"#!/usr/bin/env bash
set -euo pipefail
# Test server execution dry run
gunicorn -c gunicorn_conf.py --check-config app.main:app
echo "Gunicorn configuration syntax validated."Running `gunicorn --check-config` within CI/CD pipelines ensures ASGI module paths and gunicorn syntax resolve cleanly without actually spinning up listeners.
If using Uvicorn with Alpine Linux Docker images, compile tools (`gcc`, `musl-dev`) are mandatory to build C-extensions for uvloop and httptools.
Real-World Scenario: Scale High-Throughput FastAPI Service with Gunicorn & uvloop for Production Container
“We are preparing our FastAPI application in app.main:app for a production Kubernetes deployment. Tune uvicorn workers with gunicorn uvicornworker production configuration, ensuring uvloop performance uvicorn standards, 30s graceful timeout, and memory leak protection.”
Runtime Troubleshooting & Failure Modes
Root Cause: Gunicorn was installed without Uvicorn or the standard extras in the active virtual environment, preventing Gunicorn from resolving the UvicornWorker class path.
pip install "uvicorn[standard]" gunicornRoot Cause: uvloop is either missing from the Python path or conflicting custom event loop policies were declared inside app/main.py prior to Uvicorn worker startup.
pip install uvloop httptools && grep -rn "set_event_loop_policy" app/ || trueFrequently Asked Questions (Uvicorn ASGI Server Tuning & Gunicorn Worker Management SOP)
Q:Can I use Uvicorn ASGI Server Tuning & Gunicorn Worker Management across Codex, Claude Code, and Cursor simultaneously?
Yes. This skill is specified in standard SKILL.md format and mounts seamlessly into Codex, Claude Code, Cursor, and Windsurf workspaces without cross-platform friction.
Q:How does Uvicorn ASGI Server Tuning & Gunicorn Worker Management prevent context window overflow during long agent sessions?
By providing deterministic execution rules, exact configuration files, and validation commands up front, preventing the LLM from entering repetitive trial-and-error debugging cycles.
Q:Does this skill require escalated root or container permissions?
No. The skill is audited with a security score of 98/100, requires only workspace filesystem read/write access, and does not require root execution privileges or unrestrained host access.
Ready to equip your autonomous agent with Uvicorn ASGI Server Tuning & Gunicorn Worker Management?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.