Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Principle:24mlight A Share investment Agent Async API Backend

From Leeroopedia
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:

  1. Request Reception: A POST /api/analysis/start endpoint receives a StockAnalysisRequest (ticker, show_reasoning, num_of_news, initial_capital, initial_position), generates a UUID run_id, and submits the analysis to a ThreadPoolExecutor.
  1. Asynchronous Execution: The execute_stock_analysis function runs in a background thread, calling run_hedge_fund within a workflow_run context manager that registers and completes the run in global state.
  1. Status Polling: A GET /api/analysis/{run_id}/status endpoint checks the Future's completion state and the RunInfo status (running, completed, error).
  1. Result Retrieval: A GET /api/analysis/{run_id}/result endpoint aggregates agent reasoning data and the final portfolio management decision.
  1. 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