Deployment

Run Python services with the Sophonz SDK in production — programmatic init() or opentelemetry-instrument, environment and secret layout, containers with a non-root user and read-only root filesystem, Kubernetes manifests, and graceful shutdown.

In production the SDK is configured almost entirely through the environment: the service name and endpoint in plain configuration, the API key in a secret. This page follows the setup of the Sophonz sample servers, which run Flask and Django under gunicorn and FastAPI under uvicorn on Kubernetes, with a non-root user and a read-only root filesystem.

Programmatic or zero-code

init() in codeopentelemetry-instrument
Start commandgunicorn app:appopentelemetry-instrument gunicorn app:app
ConfigurationArguments, with environment variables as fallbackEnvironment variables only
Per-instrumentation settingsinstrumentations={...}SOPHONZ_PYTHON_INSTRUMENTATIONS (JSON)
Uncaught exception captureOn (init() default)Off unless SOPHONZ_PYTHON_EXPERIMENTAL_EXCEPTION_CAPTURE=true
Framework helpers (sophonz_flask_middleware, SophonzMiddleware, ...)YesYes
Import orderYour entrypoint must call init() before the framework loadsHandled by the launcher
DjangoCall init() after DJANGO_SETTINGS_MODULE is setSet DJANGO_SETTINGS_MODULE in the environment

Both start the same SDK. Use init() when the configuration belongs with the code, such as commenter options, a sampler object, or additional instrumentors. Use opentelemetry-instrument to add the SDK to an existing image without code changes. Do not combine them in one process.

Under gunicorn, opentelemetry-instrument starts the SDK in the master process, before workers fork, whether or not --preload is set. The batch processors restart their export threads in each worker, and worker_exit is still the place to flush:

# gunicorn.conf.py
def worker_exit(server, worker):
    from sophonz.opentelemetry import shutdown
 
    shutdown()

Environment

The non-secret configuration of the sample servers:

OTEL_SERVICE_NAME=checkout-api
OTEL_EXPORTER_OTLP_ENDPOINT=https://in.sophonz.ai
OTEL_PROPAGATORS=tracecontext,baggage
OTEL_RESOURCE_ATTRIBUTES=service.namespace=shop
OTEL_METRICS_EXPORTER=none
SOPHONZ_STARTUP_LOGS=false
VariableWhy
OTEL_SERVICE_NAMEWithout it, spans arrive as unknown_service:python and the SDK logs a warning.
OTEL_EXPORTER_OTLP_ENDPOINTThe default already; set it explicitly so the value is visible, or point it at your own collector.
OTEL_PROPAGATORSThe default already; set it so nobody narrows it to tracecontext and loses session.id (see Browser to Backend Tracing).
OTEL_RESOURCE_ATTRIBUTESservice.namespace should match the browser app's project. SOPHONZ_SERVICE_NAMESPACE=shop does the same.
OTEL_METRICS_EXPORTER=nonehttps://in.sophonz.ai accepts /v1/traces and /v1/logs; /v1/metrics answers 404. Without this, the metrics exporter logs a failed export every 60 seconds.
SOPHONZ_STARTUP_LOGS=falseSilences the startup summary once a deployment is known to work. Leave it on for the first rollout.

Add SOPHONZ_DEPLOYMENT_ENVIRONMENT=production (deployment.environment.name) and OTEL_SERVICE_VERSION if you tag telemetry by environment and release.

The API key

SOPHONZ_API_KEY is the registered app key (sk_...). It is sent as the authorization header and the service.key resource attribute, and the collector uses service.key to decide which app the telemetry belongs to.

Two failure modes look like a healthy pod:

  • No key. The SDK logs OpenTelemetry SDK initialization skipped once and the application runs without telemetry.
  • A key the collector does not know. Exports succeed, and the collector drops the data.

Keep the key in a secret, make it required so a missing secret stops the pod from starting, and check for the service in Sophonz after the first deployment.

Container image

FROM python:3.13-slim
 
ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PIP_NO_CACHE_DIR=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1
 
RUN groupadd --system --gid 1001 app \
 && useradd --system --uid 1001 --gid app --no-create-home \
      --home-dir /nonexistent --shell /usr/sbin/nologin app
 
COPY requirements.txt /tmp/requirements.txt
RUN python -m venv /opt/venv \
 && /opt/venv/bin/pip install --requirement /tmp/requirements.txt \
 && rm /tmp/requirements.txt
 
WORKDIR /app
COPY gunicorn.conf.py ./
COPY myservice/ ./myservice/
# Byte-compile at build time: the root filesystem is read-only at runtime.
RUN python -m compileall -q /app
 
ENV PATH=/opt/venv/bin:$PATH
USER 1001:1001
EXPOSE 8000
 
CMD ["gunicorn", "--config", "/app/gunicorn.conf.py", "myservice.wsgi:app"]
# requirements.txt
sophonz-opentelemetry[flask,psycopg]==0.1.0
flask
gunicorn
psycopg[binary,pool]

For a read-only root filesystem, the only writable path is /tmp, mounted as an empty volume. gunicorn needs two settings for that:

# gunicorn.conf.py
worker_tmp_dir = "/tmp"          # worker heartbeat files
control_socket_disable = True    # recent gunicorn releases create a control socket under $HOME

For FastAPI, replace the command:

CMD ["uvicorn", "myservice.main:app", "--host", "0.0.0.0", "--port", "8000", \
     "--loop", "asyncio", "--proxy-headers", "--forwarded-allow-ips", "*", \
     "--timeout-graceful-shutdown", "20"]

For Django, set ENV DJANGO_SETTINGS_MODULE=mysite.settings and run gunicorn --config /app/gunicorn.conf.py mysite.wsgi.

Kubernetes

Plain configuration in a ConfigMap, the key in a Secret:

kubectl create secret generic sophonz-service-key \
  --from-literal=SOPHONZ_API_KEY='sk_...'
apiVersion: v1
kind: ConfigMap
metadata:
  name: checkout-api-config
data:
  PORT: "8000"
  WEB_CONCURRENCY: "2"
  OTEL_SERVICE_NAME: checkout-api
  OTEL_EXPORTER_OTLP_ENDPOINT: https://in.sophonz.ai
  OTEL_PROPAGATORS: tracecontext,baggage
  OTEL_RESOURCE_ATTRIBUTES: service.namespace=shop
  OTEL_METRICS_EXPORTER: none
  SOPHONZ_STARTUP_LOGS: "false"
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: checkout-api
spec:
  replicas: 2
  selector:
    matchLabels:
      app: checkout-api
  template:
    metadata:
      labels:
        app: checkout-api
    spec:
      automountServiceAccountToken: false
      # gunicorn graceful_timeout (20s) plus the SDK flush (up to 5s).
      terminationGracePeriodSeconds: 30
      securityContext:
        runAsNonRoot: true
        runAsUser: 1001
        runAsGroup: 1001
        fsGroup: 1001
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: checkout-api
          image: registry.example.com/checkout-api:1.0.0
          ports:
            - name: http
              containerPort: 8000
          envFrom:
            - configMapRef:
                name: checkout-api-config
          env:
            # Required on purpose: without a key the SDK only logs a warning,
            # and the pod would run without telemetry.
            - name: SOPHONZ_API_KEY
              valueFrom:
                secretKeyRef:
                  name: sophonz-service-key
                  key: SOPHONZ_API_KEY
            - name: DATABASE_URL
              valueFrom:
                secretKeyRef:
                  name: postgres-credentials
                  key: DATABASE_URL
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
          readinessProbe:
            httpGet:
              path: /ready
              port: http
          livenessProbe:
            httpGet:
              path: /health
              port: http
          volumeMounts:
            - name: tmp
              mountPath: /tmp
      volumes:
        - name: tmp
          emptyDir: {}
  • The SDK needs no writable path, no extra capability, and no service account token.
  • A readiness probe that checks the database and a liveness probe that does not keep a pod that lost its database out of rotation without restarting it.
  • Probe requests produce server spans like any other request. To leave them out, add OTEL_PYTHON_EXCLUDED_URLS: health,ready to the ConfigMap; the Flask, FastAPI, and Django instrumentations skip URLs matching any of those patterns.
  • The SDK exports over HTTPS to in.sophonz.ai. If a NetworkPolicy restricts egress, allow it.

Graceful shutdown

When Kubernetes stops a pod, it sends SIGTERM, waits terminationGracePeriodSeconds, then sends SIGKILL. Telemetry buffered at SIGKILL is lost, so the whole sequence has to fit in the grace period.

gunicorn (Flask, Django). Each worker receives SIGTERM. The SDK's handler flushes (bounded at 6 seconds) and hands the signal to gunicorn, which stops accepting connections and waits up to graceful_timeout for in-flight requests. worker_exit then calls shutdown(), which exports what those requests recorded.

uvicorn (FastAPI). The SDK's handler flushes and hands over to uvicorn's graceful shutdown, which drains requests for up to --timeout-graceful-shutdown and runs the lifespan shutdown. SophonzASGIMiddleware flushes once the lifespan shutdown completes, before uvicorn ends the process.

A grace period of graceful timeout + 10 seconds leaves room for both flushes. With the defaults above: 20 + 10 = 30 seconds.

Batches are also exported on a schedule while the process runs: spans every 5 seconds by default (OTEL_BSP_SCHEDULE_DELAY), and logs on their own schedule (OTEL_BLRP_SCHEDULE_DELAY). A process killed without a flush loses at most the last few seconds.

If your process manager already handles signals and you would rather call shutdown() yourself, pass stop_on_termination_signals=False (or SOPHONZ_PYTHON_STOP_ON_TERMINATION_SIGNALS=false).

Checking a deployment

  1. Startup. With startup logs on, each process prints lines such as [Sophonz] Service name is configured to be "checkout-api", [Sophonz] Sending traces to "https://in.sophonz.ai/v1/traces", and [Sophonz] OpenTelemetry SDK initialized successfully. Under gunicorn, expect one set per worker.
  2. Skipped. A line containing OpenTelemetry SDK initialization skipped means the key did not reach the process.
  3. Payload. For one pod, SOPHONZ_DEBUG_PAYLOAD=true prints every exported span and log record to stdout, which shows exactly what leaves the process.
  4. Arrival. Send a request and find the service in Sophonz. If spans print but never arrive, check that the key is a registered app key.

Next steps

TIP — This is just the beginning

Now ship your app. Sophonz surfaces the problems real users hit — so your app evolves on its own.