This guide shows how to instrument a Python FastAPI service running on GCP Cloud Run with OpenTelemetry (OTEL) and export traces to Google Cloud Trace. It includes the exact folder layout, code, and deploy/delete commands.
Home → “OTEL on GCP Cloud Run (FastAPI)”
Prerequisites → Tooling & IAM
Project Layout → Folder structure
Source Code → Dockerfile, requirements.txt, FastAPI app, OTEL setup
Deploy → Build & deploy commands
Verify → Logs & Trace Explorer
Toggles & Env Vars → Feature flags
Troubleshooting → Common errors & fixes
Page navigation link names (short):
Home
Prereqs
Layout
Code
Deploy
Verify
Env Vars
Troubleshoot
Goal: Capture function-level latency and external HTTP call latency from FastAPI on Cloud Run and view them in Cloud Trace Explorer.
Approach: Use OTEL SDK + auto-instrumentation for fastapi, requests, httpx; export to stdout (for logs) and Cloud Trace.
Why OTEL: Vendor-neutral, easy to add other exporters later (e.g., Datadog via OTLP/Collector).
GCP project with Cloud Run and Cloud Trace enabled
Docker + gcloud CLI authenticated to your project
Artifact Registry repo created (example uses: us-central1-docker.pkg.dev/sugunan/fastapi-repo)
Cloud Run service account with Cloud Trace Agent (default on many projects)