Principle:24mlight A Share investment Agent Async API Backend
Appearance
| Knowledge Sources | |
|---|---|
| Domains | Backend_Engineering, API_Design |
| Last Updated | 2026-10-10 14:00 GMT |
Overview
An asynchronous REST API backend pattern using FastAPI with ThreadPoolExecutor for background analysis execution, thread-safe state management, status polling, and result retrieval endpoints.
Description
The async API backend provides a REST interface for triggering and monitoring long-running stock analysis tasks:
- Request Reception: A
POST /api/analysis/startendpoint receives aStockAnalysisRequest(ticker, show_reasoning, num_of_news, initial_capital, initial_position), generates a UUID run_id, and submits the analysis to a ThreadPoolExecutor.
- Asynchronous Execution: The
execute_stock_analysisfunction runs in a background thread, callingrun_hedge_fundwithin aworkflow_runcontext manager that registers and completes the run in global state.
- Status Polling: A
GET /api/analysis/{run_id}/statusendpoint checks the Future's completion state and the RunInfo status (running, completed, error).
- Result Retrieval: A
GET /api/analysis/{run_id}/resultendpoint aggregates agent reasoning data and the final portfolio management decision.
- Server Lifecycle: FastAPI app with CORS middleware, uvicorn server with graceful shutdown via threading.Event polling, and signal handlers for SIGINT/SIGTERM.
Usage
Use this principle when:
- Exposing long-running analysis tasks as async REST API endpoints
- Requiring thread-safe state management for concurrent request handling
- Building monitoring and observability APIs for multi-agent systems
Theoretical Basis
# Abstract pattern (not real implementation)
@app.post("/api/analysis/start")
async def start_analysis(request):
run_id = uuid4()
future = executor.submit(execute_analysis, request, run_id)
api_state.register_task(run_id, future)
return {"run_id": run_id, "status": "running"}
@app.get("/api/analysis/{run_id}/status")
async def get_status(run_id):
task = api_state.get_task(run_id)
run_info = api_state.get_run(run_id)
return {"status": run_info.status, "is_complete": task.done()}
Thread-safe state: Uses threading.RLock for all state mutations in ApiState.
Context manager pattern:
@contextmanager
def workflow_run(run_id):
api_state.register_run(run_id)
try:
yield
api_state.complete_run(run_id, "completed")
except Exception:
api_state.complete_run(run_id, "error")
raise
Related Pages
Implemented By
Page Connections
Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment