BerriAI/litellm · error · HTTPException

DB not connected. This endpoint needs a database; set DATABA

Error message

DB not connected. This endpoint needs a database; set DATABASE_URL to a PostgreSQL connection string (postgresql://...) to enable it. See https://docs.litellm.ai/docs/proxy/virtual_keys

What it means

get_daily_activity is the shared paginated spend-analytics core behind the daily-activity endpoints (/global, per-user, per-team, per-tag variants). It queries the daily-spend tables through raw SQL on Prisma, so it first asserts prisma_client is not None and raises HTTP 500 with CommonProxyErrors.db_not_connected_error when the proxy has no database. Spend analytics are entirely DB-backed — there is no in-memory fallback.

Source

Thrown at litellm/proxy/management_endpoints/common_daily_activity.py:1004

    page: int,
    page_size: int,
    exclude_entity_ids: list[str] | None = None,
    metadata_metrics_func: Callable[[Sequence[DailySpendRecord]], SpendMetrics] | None = None,
    timezone_offset_minutes: int | None = None,
    include_current_utc_day: bool = False,
    resolve_entity_metadata: Callable[[Sequence[DailySpendRecord]], Awaitable[dict[str, dict[str, object]]]]
    | None = None,
) -> SpendAnalyticsPaginatedResponse:
    """Common function to get daily activity for any entity type.

    ``resolve_entity_metadata`` lets a caller resolve entity metadata from the
    rows actually on the page (e.g. user_id -> user_email) instead of fetching
    the whole entity table upfront, which matters when the entity set is
    unbounded.
    """

    if prisma_client is None:
        raise HTTPException(
            status_code=500,
            detail={"error": CommonProxyErrors.db_not_connected_error.value},
        )

    if start_date is None or end_date is None:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail={"error": "Please provide start_date and end_date"},
        )

    try:
        where_conditions: Final = _build_where_conditions(
            entity_id_field=entity_id_field,
            entity_id=entity_id,
            start_date=start_date,
            end_date=end_date,
            model=model,
            api_key=api_key,

View on GitHub (pinned to 77b7c6c40c)

Solutions

  1. Set DATABASE_URL="postgresql://..." and restart the proxy
  2. Confirm spend tables exist by letting Prisma run migrations on startup (automatic when the DB is reachable)
  3. Retry the analytics call with both start_date and end_date supplied once a 200 returns from GET /budget/list as a DB sanity check

Example fix

# before
litellm --config config.yaml  # no DATABASE_URL
curl http://localhost:4000/global/spend/report -H "Authorization: Bearer $KEY"  # 500 DB not connected

# after
export DATABASE_URL="postgresql://user:pass@db:5432/litellm" && litellm --config config.yaml
curl "http://localhost:4000/global/spend/report?start_date=2026-08-01&end_date=2026-08-18" -H "Authorization: Bearer $KEY"
Defensive patterns

Strategy: validation

Validate before calling

import os

# All spend-analytics endpoints are DB-backed; check the deployment first
if not os.getenv("DATABASE_URL", "").startswith("postgresql://"):
    raise SystemExit("proxy has no DB; daily-activity endpoints return 500")

Try / catch

import httpx

try:
    r = httpx.get(f"{PROXY_URL}/global/spend/report",
                  params={"start_date": "2026-08-01", "end_date": "2026-08-18"},
                  headers=hdrs)
    r.raise_for_status()
except httpx.HTTPStatusError as e:
    if e.response.status_code == 500 and "DB not connected" in e.response.text:
        raise RuntimeError("configure DATABASE_URL before querying spend analytics") from e
    raise

Prevention

When it happens

Trigger: Calling any daily-activity/spend-report endpoint (e.g. GET /global/spend/report or the per-entity daily activity routes that delegate here) on a proxy without DATABASE_URL configured.

Common situations: Pointing spend dashboards at a config-only proxy; DB env var missing in one of several proxy replicas behind a load balancer; analytics enabled in the UI before Postgres was provisioned.

Related errors


AI-assisted analysis of BerriAI/litellm@77b7c6c40c (2026-08-18). Data as JSON: /api/errors/1228b3bc6e7bdfad. Report an issue: GitHub.