Investigate staging latency and slow inference root cause
Summary
Investigate why the staging environment is slow, including cases where GPT-5 inference or agent responses take too long, and identify the root cause.
Problem / Context
Staging is reported to be slow enough that normal testing and validation are affected. One suspected symptom is long GPT-5 inference latency, but the root cause is not yet known.
This blocks release confidence because slow staging can hide product regressions, make QA unreliable, and prevent the team from distinguishing model latency from backend, networking, queueing, orchestration, or frontend performance issues.
Known environment: staging. Exact app/build/version and timing data should be captured during investigation.
Scope (optional)
In scope:
- Measure staging latency across user-facing chat and agent flows.
- Break down latency by frontend, core RPC, backend API, model inference, tool execution, orchestration, and network time where possible.
- Compare staging against production/local/dev for the same prompts and flows.
- Inspect GPT-5/provider request timings, retries, queueing, rate limits, streaming start time, and timeout behavior.
- Identify whether slowness is caused by model choice, provider routing, backend infrastructure, staging config, telemetry, database, memory sync, tool loading, or frontend rendering.
- Document root cause and recommended fix plan.
Out of scope unless confirmed as root cause:
- Replacing the model/provider permanently.
- Broad infrastructure migration.
Acceptance criteria
- [ ] Baseline captured — Record representative staging response times, including time-to-first-token and total response time where available.
- [ ] Latency breakdown — Attribute time across frontend, core, backend, provider inference, tool calls, and network/queueing.
- [ ] GPT-5 path verified — Confirm whether GPT-5 inference itself is slow or whether latency is introduced before/after the provider call.
- [ ] Environment comparison — Compare staging with production/local/dev for at least one repeatable flow.
- [ ] Root cause identified — Document the primary cause of staging slowness with logs, traces, or measurements.
- [ ] Fix plan proposed — Provide recommended remediation steps and owners for the follow-up implementation.
- [ ] Regression safety — Add monitoring, timing logs, or tests where practical so similar latency regressions are easier to catch.
- [ ] Diff coverage ≥ 80% — Code changes meet the changed-lines coverage gate where applicable.
Related
- Staging performance investigation
- GPT-5 inference latency
- Release testing reliability
Implementation Plan
Triage Assessment
YellowSnnowmann's investigation is thorough and well-evidenced (Finding 0-5). The issue is relevant: staging slowness blocks QA confidence and may hide regressions. The investigation correctly debunked the "GPT-5" framing and identified 5 ranked root-cause hypotheses. The remaining gap is Phase B (live measurement confirmation) which is blocked by Phase A instrumentation.
Proposed Scope
- Retain the existing investigation comment as the authoritative analysis.
- Implement Phase A instrumentation first (backend per-stage timers, client TTFT timer).
- Phase B: capture baseline staging vs prod vs local for one repeatable flow.
- Phase C-D: apply remediation per what Phase B confirms.
Implementation Steps
- Backend timers (
backend/src/controllers/inference/chatCompletions.ts): movelatencyMsstart to route entry before auth middleware. Add per-stage timing: auth, balance, sticky-provider lookup, upstream TTFT, post-stream. Log resolved provider/baseURL. Enable Sentry or lightweight timer log onNODE_ENV === 'staging'. - Client TTFT timer (
openhuman/app/src/pages/Conversations.tsx): add timer from submit to firsttext_delta. Attach tochat_message_sent/chat_donetelemetry events. - Connection reuse (
src/openhuman/inference/provider/compatible_request.rs): switch from per-streamreqwest::Clientto a shared, configured client withpool_max_idle. Same in backend (chatCompletions.ts-- sharedOpenAIclient instance). - Index InferenceLog (
backend/src/models/InferenceLog.ts): add compound index{userId: 1, threadId: 1, createdAt: -1}for the sticky-provider query. - Retry reconciliation (
chatCompletions.ts): set explicittimeout+maxRetries; ensure app-level priority failover does not stack on SDK retries.
Verification
- E2E:
scripts/e2e-core.shafter instrumentation to confirm no regression. - Unit: coverage for timer start/stop helpers (Vitest for client, Jest/Mocha for backend).
- Manual: staging vs prod latency comparison using the new timers.
Risks and Open Questions
- Risk: Phase A timers add overhead on hot path. Mitigate with sampling or log-level guard.
- Open: Owners for Phase C-D (remediation) are TBD.
Acceptance Criteria
- [ ] Backend emits per-stage timing for each
/openai/v1/chat/completionsrequest on staging. - [ ] Client emits TTFT and total-turn timing on
chat_done. - [ ] Staging vs prod baseline captured for at least one repeatable flow.
- [ ] Hypothesis 1 (single-host PM2) or 2/3/4/5 confirmed or excluded with data.
- [ ] Remediation PRs gated by Phase B confirmation.
Staging Latency Investigation — Root Cause Analysis
Tracking issue:
tinyhumansai/openhuman#3491— "Investigate staging latency and slow inference root cause" Status: code-path analysis complete; live measurement pending host access Date: 2026-06-09
TL;DR
- "GPT-5" is a red herring. The backend has no GPT-5 chat route. Requests for
gpt-5are rejected with HTTP 400 before any upstream call. All chat traffic routes to DeepSeek / Fireworks / GMI / DashScope. - Primary root cause is infrastructure asymmetry, not the model. Staging is a single un-autoscaled PM2 process on one shared bare-metal host; prod is an autoscaling EKS deployment. Staging cannot absorb load and cold-restarts on every deploy.
- Secondary causes are slow staging dependencies (shared-tier / possibly cross-region Mongo, off-region memory server), per-request connection churn (no TCP/TLS reuse), and stacked retries.
- The investigation is currently blocked from full proof because staging has zero request tracing and there is no client-side TTFT timer. Measurement instrumentation must land before baseline/TTFT/comparison criteria can be satisfied.
Scope of analysis
Two repos were traced:
backend-alphahuman— Node/TS OpenAI-compatible inference proxy (/openai/v1/chat/completions).openhuman— Tauri (Rust core + React) desktop app that calls the backend via an in-process Rust core.
This is a static code-path analysis. It produces a ranked set of root-cause hypotheses with file:line evidence. It does not yet include live staging measurements (see "Gaps" below).
Finding 0 — "GPT-5 inference latency" is misattributed
There is no routable GPT-5 chat model in the backend.
src/controllers/inference/modelRegistry.ts:188-574—PUBLIC_MODELSdefines onlyreasoning-v1,pro-reasoning-v1,chat-v1,agentic-v1,coding-v1, plus audio/embedding models. No OpenAI / GPT binding.src/controllers/inference/chatCompletions.ts:92-96—validateChatCompletionRequest→isValidModel(model); an unknown id likegpt-5throwsBadRequestError(HTTP 400) before any upstream call.src/config/integrationRegistry.ts:51-57—inference:gpt-5-nanoexists only as a billing/pricing entry (provider: 'openai') used by Discord/gmeet assistants for cost accounting — not by the chat controller.
Implication: perceived "GPT-5 slowness" on staging is one of:
- the client requesting a rejected model and retrying against a fallback, or
- the client mapping
gpt-5→ one of the v1 models, whose real upstream is DeepSeek/Fireworks/GMI/DashScope.
All chat-model defaultProvider values resolve to DeepSeek direct (https://api.deepseek.com/v1); pro-reasoning-v1 defaults to a region-specific DASHSCOPE_BASE_URL.
Finding 1 — Infrastructure asymmetry (PRIMARY, HIGH)
Staging is not a scaled-down prod; it is a different architecture.
| Aspect | Staging | Prod |
|---|---|---|
| Compute | 1 bare-metal SSH host, PM2 instances: 1 |
EKS, HPA minReplicas: 4, maxReplicas: 12 |
| Deploy | in-place git pull + yarn install + yarn build:prod + pm2 restart |
prebuilt ECR image, rolling update |
| Memory cap | max_memory_restart: 1G |
limits cpu 2500m / mem 4Gi |
| Redis | redis://localhost:6379 (same box) |
dedicated pod (cpu 1 / mem 1Gi) |
| Co-tenants | shares CPU with Camoufox/Firefox browser + Redis | isolated pods |
Evidence: .github/workflows/deploy-develop.yml:97-181, .github/workflows/deploy-prod.yml:14-20,71-79, ecosystem.config.js:13-18, k8s/app/core-hpa.yaml:13-14, k8s/app/core-deployment.yaml:67-73, config.json:23.
Why it causes slowness: no horizontal scale-out under load, CPU contention with co-located Redis and the browser automation stack, and a cold rebuild + restart on every deploy. This alone explains "slow enough that normal testing is affected."
Finding 2 — Slow staging dependencies (HIGH / MED)
-
Mongo: staging uses an Atlas shared SRV cluster (
config.json:11,...staging.bffer2q.mongodb.net/?appName=Staging) — likely a low M-tier and possibly not co-located with the app host. The chat hot path performs ~5–6 serial Mongo round-trips before the first upstream byte:- auth:
User.findById+ parallelTeam.findById/TeamMembership.findOne—src/middlewares/authenticateJWT.ts:63-78 - balance:
canAfford→ensureCycleFresh+User.findById(...).select('usage')+getTeamTopup—src/controllers/inference/chatCompletions.ts:480-481 - sticky provider:
InferenceLog.findOne(... sort createdAt -1)whenthread_idpresent —chatCompletions.ts:483
Each serial hop is multiplied by staging Mongo latency, and all of it sits outside the measured
latencyMswindow. The sticky-provider query needs an index on{userId, threadId, createdAt}. - auth:
-
Memory server: staging
MEMORY_SERVER_URL: http://172.236.126.152:8000(config.json:48) — a raw Linode IP over plain HTTP, off-region, not present in any prod ConfigMap.
Finding 3 — Connection churn + retry stacking (HIGH on high-RTT staging)
-
No connection reuse on either side. A fresh HTTP client is built per request:
- core:
reqwest::Clientper stream —openhuman/src/openhuman/inference/provider/compatible_request.rs:88-127, invoked per turn atcompatible_stream_native.rs:37(nopool_max_idle/tcp_keepalivetuning). - backend:
new OpenAI({...})per request —src/controllers/inference/chatCompletions.ts:113-123/:504,664.
Every chat turn pays a fresh TCP + TLS handshake to
staging-api.tinyhumans.ai; higher staging RTT directly inflates time-to-first-token (TTFT) on every turn. - core:
-
Stacked retries. The upstream client sets no
timeoutand nomaxRetries, so the OpenAI Node SDK defaults apply (maxRetries: 2,timeout: 600000ms). App-level priority/failover retries stack on top (chatCompletions.ts:520-584non-stream,:677-729stream). Under 429/5xx pressure a single logical request can fan out to multiple full upstream attempts with exponential backoff.
Finding 4 — Provider routing override risk (HIGH if present, UNVERIFIED)
src/config/nconf.ts:38defaultINFERENCE_AGENTIC_PROVIDER: 'fireworks'(both envs).config.json:51-53pinsGMI_*_MODEL_ID = anthropic/claude-sonnet-4.6— only effective if a provider resolves togmi.src/controllers/inference/modelRegistry.ts:194-198(code comment): DeepSeek-direct is ~7.6× faster than Fireworks and ~15× faster than GMI.nconf.ts:162(argv().env().file()) lets host env vars override the committed config.
Risk: if the live staging host's gitignored .env / config.staging.json sets INFERENCE_*_PROVIDER=gmi (or a non-priority Fireworks tier), inference is materially slower than prod's DeepSeek default. This cannot be confirmed from the repo — the staging override files are not committed.
Finding 5 — Observability gaps that block proof (the real blocker)
src/config/sentry.ts:5-13— Sentry initializes only whenNODE_ENV === 'production', andtracesSampleRate: 0/profilesSampleRate: 0regardless. Staging has zero request tracing / spans / profiling.src/utils/trackInference.ts—latencyMs = Date.now() - startTime, butstartTimeis captured atchatCompletions.ts:486after auth + balance + sticky resolution, so all pre-call DB overhead is invisible.- Upstream timing headers (
x-fireworks-server-processing-ms) are logged only behind the disabledapp:inference:upstreamdebug namespace (chatCompletions.ts:168-197). - Client: no TTFT timer anywhere (submit → first
text_delta), no total-turn timer (submit →chat_done), no split of local-RPC vs backend-stream vs connection-setup. Only server-emitted subagentelapsed_msandchat_donetoken counts exist. (openhuman/app/src/pages/Conversations.tsx:857emits a barechat_message_sentevent with no timing payload.)
Ranked root-cause hypotheses
| # | Hypothesis | Confidence | Needs to confirm |
|---|---|---|---|
| 1 | Single-host, un-autoscaled PM2 staging under CPU contention | High | Host CPU/mem metrics under load |
| 2 | Slow shared-tier / cross-region staging Mongo × 5–6 serial pre-call hops | High | Mongo query timings on staging |
| 3 | No TCP/TLS connection reuse → per-turn handshake RTT | Med–High | TTFT split (connection-setup vs stream) |
| 4 | Provider routing override → GMI/Fireworks instead of DeepSeek | High if present | Live staging .env / config.staging.json |
| 5 | Stacked SDK + app retries under 429/5xx | Med | Per-attempt retry logging |
Recommended fix plan
Phase A — Instrumentation (prerequisite; unblocks all measurement criteria)
- Backend: move the
latencyMsstart to route entry; add per-stage timing (auth, balance, sticky, upstream TTFT, post-stream tracking). Capture the resolved provider/baseURL and retry-attempt count per request. Enable Sentry (or a lightweight timer log) onNODE_ENV === 'staging'. - Client: add a TTFT timer (submit → first
text_delta) and a total-turn timer (submit →chat_done); attach to the existingchat_message_sent/chat_donetelemetry. - Owner: TBD (backend + app).
Phase B — Confirm with measurements
- Capture baseline staging vs prod vs local for one repeatable flow (TTFT + total). Pull the live staging
.env/config.staging.jsonand confirm provider routing. - Owner: YellowSnnowmann (issue assignee).
Phase C — Remediation (apply what the data confirms)
- Connection reuse: shared
reqwest::Client(core) and sharedOpenAIclient (backend) with keep-alive. - Set explicit upstream
timeout+maxRetries; reconcile with app-level failover to avoid retry stacking. - Index
InferenceLogon{userId, threadId, createdAt}; collapse/parallelize pre-call DB hops. - Right-size staging infra (autoscale or larger host; move Redis/Mongo off the shared box / into region).
- Owner: TBD.
Phase D — Regression safety
- Keep the Phase-A timers in place; add a staging TTFT alarm/threshold.
Gaps vs issue acceptance criteria
| Criterion | Status |
|---|---|
| Baseline captured (TTFT + total) | Blocked — no timers exist yet (Phase A) |
| Latency breakdown per layer | Partial — code path mapped; needs per-stage timers |
| GPT-5 path verified | Done — no GPT-5 route exists (Finding 0) |
| Environment comparison | Blocked — needs live measurement (Phase B) |
| Root cause identified | Hypotheses ranked — needs Phase B to convert to proof |
| Fix plan + owners | Drafted — owners TBD |
| Regression safety | Planned (Phase D) |
Triage: needs opinion — “Investigate staging latency and slow inference root cause” needs a maintainer decision on product scope/priority or fresh reproduction evidence before its status can be settled. Please advise whether to pursue, narrow, or close it.
Thanks for opening this. The earlier analysis on this thread points away from the model and towards staging's hosting: a single, non-autoscaled process on a shared host, versus autoscaling in production. That's an infrastructure question rather than a change in this repository.
Could whoever owns staging confirm whether it's still slow today? If it is, the next step is the live measurement that was left pending in June (request timing at the backend vs upstream model latency). If it isn't, we'll close this as resolved.