Self-hosted PostgreSQL

Use the pg_tracing extension to have PostgreSQL emit its own spans. Covers building the image, server settings, the verification procedure, and the app key constraint.

Where the database process is operated directly, the pg_tracing extension can be installed. PostgreSQL then includes its own query plan in the application trace, so a slow query can be traced to its cause, such as a sequential scan where an index was expected.

postgres-telemetry

How it works

pg_tracing reads the W3C traceparent that the application passes down as a SQLCommenter comment on the query. It creates server-side spans as children of that trace, and a background worker exports them over OTLP directly, without passing through an SDK.

Spans are produced in two layers: statement-level spans from track, and plan-node spans from planstate_spans. Disabling the latter omits nodes such as SeqScan and Hash Join, leaving only the total statement duration.

Requirements

ItemValue
PostgreSQL14, 15, 16 — 17 is not yet supported
Extensionpg_tracing (DataDog)
BuildA C extension compiled against the server headers, so postgresql-server-dev-<version> and libcurl are required
RuntimeThe OTLP exporter sends over libcurl. An https endpoint also needs ca-certificates

Building the image

The extension is not distributed as a package, so it must be built. Sophonz uses an image produced by the following Dockerfile.

Dockerfile
FROM postgres:16-bookworm AS build
ARG PG_TRACING_REF=v0.1.3
 
RUN set -eux; \
    apt-get update; \
    apt-get install -y --no-install-recommends \
        build-essential git ca-certificates postgresql-server-dev-16 \
        libcurl4-openssl-dev; \
    git clone --depth 1 --branch "${PG_TRACING_REF}" \
        https://github.com/DataDog/pg_tracing.git /tmp/pg_tracing; \
    make -C /tmp/pg_tracing install; \
    rm -rf /var/lib/apt/lists/* /tmp/pg_tracing
 
FROM postgres:16-bookworm
RUN set -eux; \
    apt-get update; \
    apt-get install -y --no-install-recommends libcurl4 ca-certificates; \
    rm -rf /var/lib/apt/lists/*
 
COPY --from=build /usr/lib/postgresql/16/lib/pg_tracing.so /usr/lib/postgresql/16/lib/
COPY --from=build /usr/share/postgresql/16/extension/pg_tracing* /usr/share/postgresql/16/extension/

The Debian base is deliberate: it is the supported environment for the pgxs toolchain. On Alpine the headers and toolchain must be assembled separately.

Server settings

shared_preload_libraries is read at server start, so it is passed as a server argument.

postgres server args
- -c
- shared_preload_libraries=pg_tracing
- -c
- compute_query_id=on
- -c
- pg_tracing.track=all
- -c
- pg_tracing.planstate_spans=on
- -c
- pg_tracing.otel_naptime=2000
- -c
- pg_tracing.otel_service_name=my-postgres
- -c
- pg_tracing.otel_endpoint=https://in.sophonz.ai/v1/traces
SettingMeaning
shared_preload_librariesLoads the extension. Requires a server restart
compute_query_idAssigns a stable query ID to spans so identical queries can be grouped
trackall includes both top-level and nested statements
planstate_spansEmits plan nodes as individual spans
otel_naptimeExport interval, in ms
otel_service_nameThe service name the trace will show
otel_endpointOTLP traces endpoint, including the path

Then enable the extension in the database.

CREATE EXTENSION IF NOT EXISTS pg_tracing;

Sampling

The defaults are sample_rate = 0 and caller_sample_rate = 1. PostgreSQL traces only queries that arrive with a sampled traceparent and does not trace the rest. Because the database makes no independent sampling decision, a request captured in the application trace also carries its database spans.

Raising sample_rate causes the database to start traces independently of the application. The resulting spans have no parent and are recorded as separate traces.

Application configuration

For PostgreSQL to read a traceparent, the application must send one with the query. SQLCommenter is what does this. It is not a language-specific feature but a convention shared by several OpenTelemetry implementations, and it is not enabled by default — it has to be turned on explicitly.

In the Node.js SDK it is passed to the underlying instrumentation through the instrumentations option.

init({
  service: 'my-api',
  apiKey: process.env.SOPHONZ_API_KEY,
  instrumentations: {
    '@opentelemetry/instrumentation-pg': {
      addSqlCommenterCommentToQueries: true,
    },
  },
});

Without it no comment is appended, and PostgreSQL has nothing to trace against. The extension runs normally but produces no spans.

CAUTION — If you use named prepared statements

The comment carries a different trace ID per query, so the statement text changes every time. Where statements are named and reused, this can reduce cache effectiveness. It does not apply where statements are unnamed.

The app key constraint

WARNING — Spans may not be ingested in a self-hosted deployment

The Sophonz collector resolves the tenant from the service.key resource attribute and discards the resource when it cannot. However, the only settings pg_tracing exposes are otel_service_name and otel_endpoint, so an arbitrary resource attribute cannot be attached.

A discarded resource still receives a 200, so no error appears in the PostgreSQL log.

The fix depends on the deployment.

  • Sophonz managed — already configured. The collector has an internal-only ingest port that applies the key on arrival.
  • On-premises and self-hosted — configured during onboarding. See the Enterprise overview or contact us.

NOTE — Patching the extension is the definitive fix

Adding a GUC that sets resource attributes removes the need for the workaround entirely. The image is built in-house, so the patch can be applied, and the change is suitable for contribution upstream.

Verification

First confirm that the extension is generating and exporting spans.

SELECT * FROM pg_tracing_info();

This returns the number of spans processed and the last export time. If these values increase while the trace remains empty, the loss occurred in the ingest path rather than in the database.

Check which settings took effect in pg_settings. A misspelled GUC is ignored without warning, so the server arguments alone are not sufficient confirmation.

SELECT name, setting FROM pg_settings
WHERE name LIKE 'pg_tracing%' ORDER BY name;

Finally, confirm which services are present in a single trace.

SELECT serviceName, count()
FROM sophonz_traces.distributed_sophonz_index_v2
WHERE traceID = '...'
GROUP BY 1;

Both the application and the database should be returned. If only the database is missing, the problem is in ingest rather than in context propagation. Propagation can be verified separately: if the application's Server-Timing response header returns the same trace ID that was sent, propagation is working.