Tracing
PG Proxy records query and protocol spans with either Datadog or OpenTelemetry. See Telemetry configuration for enabling tracing, choosing an exporter, and setting sampling. For application-owned providers, see Go telemetry configuration.
Span operations
Section titled “Span operations”| Operation | Purpose |
|---|---|
Proxy forwarding |
Root operation; the current name includes a trailing space. |
Handling messages |
Client-message handling. |
Forwarding to postgres |
Forwarding messages to the backend. |
Query Execution and proxying |
Query execution and proxy work. |
Batch execution and proxying |
Grouped batch execution. |
Returning rows to client |
Returning results. |
The OpenTelemetry adapter marks the incoming request span as SERVER and its processing child spans as INTERNAL. The native Datadog adapter marks both root and child spans as server. Both adapters set the database system to postgres. The exact query -- ping does not start a root trace.
Child spans and operation metrics
Section titled “Child spans and operation metrics”With -telemetry datadog, the pg-proxy binary defaults to sampled. To create
every child span, pass -child-span-mode full.
| Mode | Behavior |
|---|---|
sampled (default) |
Sends DogStatsD operation metrics and skips children on proxy-local roots with a rejected sampling decision. Roots with propagated context, kept roots and undecided roots retain their children. Requires -telemetry datadog. |
full |
Creates every child span, including children of rejected traces that Datadog APM can use to compute statistics. |
The direct metrics are datadog.pg_proxy.trace_operations.hits,
datadog.pg_proxy.trace_operations.errors, and
datadog.pg_proxy.trace_operations.latency_us (a distribution). They follow
the child operation boundaries and use a bounded operation tag. Errors add
source:postgres for PostgreSQL error responses or source:proxy for
proxy-observed failures. The root span keeps its own errors and timing behavior.
In sampled mode, the DogStatsD client created by PG Proxy
flushes aggregated metrics every 250 ms to reduce the work per flush.
Embedders can set a different interval through StatsdOptions or supply their
own metrics client.
Existing child-derived trace.* metrics lose coverage in sampled mode. The
DogStatsD metrics use a separate namespace and bounded dimensions and may differ
in timing and aggregation. Compare counts, error rates and latency distributions
across full and sampled runs on the same workload before migrating monitoring.
Use full when the trace may be promoted after phase recording begins.
Throughput gains depend on the fraction of rejected local roots.
PG Proxy logs a startup warning in sampled mode when
DD_SPAN_SAMPLING_RULES or DD_SPAN_SAMPLING_RULES_FILE is set. Use full
mode to apply single-span rules to every child span. In sampled mode, rules
can apply only to spans that PG Proxy creates.
For Go embedders, datadog.Start defaults to sampled when it owns the tracer
and metrics are enabled. Set datadog.Options.ChildSpanMode to
datadog.ChildSpansFull to create every child span.
Go embedders can set datadog.Options.SamplingRules to the result of
tracer.SpanSamplingRules(...) for the same startup warning. The SDK’s raw
TracerOptions are opaque to PG Proxy and can contain rules it cannot detect.
Propagation
Section titled “Propagation”Without incoming context, each traced query or protocol batch gets a
proxy-local root span. For OpenTelemetry, leading or trailing sqlcommenter blocks
can supply W3C traceparent and URL-encoded tracestate:
SELECT 1 /*traceparent='00-0123456789abcdef0123456789abcdef-0123456789abcdef-01'*/The first valid context wins: a valid leading context takes precedence. An ordinary leading comment, metadata-only comment, or invalid leading context does not hide a valid trailing context.
In Go, use the application’s active span and the standard propagator to obtain that context before sending SQL:
carrier := propagation.MapCarrier{}propagation.TraceContext{}.Inject(ctx, carrier)// sql is the query text. Avoid adding per-request context to reusable named SQL.if parent := carrier.Get("traceparent"); parent != "" { sql += " /*traceparent='" + url.PathEscape(parent) + "'" if state := carrier.Get("tracestate"); state != "" { sql += ",tracestate='" + url.PathEscape(state) + "'" } sql += "*/"}This fragment uses net/url and go.opentelemetry.io/otel/propagation; the client
must send SQL through a protocol mode that includes its text for that request.
It follows sqlcommenter formatting.
The client must replace these example IDs with the active application context. The root then shares the application’s trace ID and uses the supplied span as its remote parent. Sampling and trace state are preserved. Invalid or absent context starts a local trace. SQL is forwarded unchanged; PostgreSQL does not automatically become an instrumented participant.
Context is available when Query or Parse contains SQL. Reusing a prepared statement through Bind/Execute alone cannot provide fresh application context.
The session code warns when named prepared statements contain per-query trace context: changing SQL text for each trace undermines prepared-statement reuse.
Interpreting durations
Section titled “Interpreting durations”Query Execution and proxying covers the wait for backend results and proxy work; it is not a pure measurement of PostgreSQL execution time. Returning rows to client helps separate result delivery from that work. Large results or a slow-reading client can increase delivery time without a slow SQL plan.
For batches, use Batch execution and proxying rather than assuming every query has its own complete span tree. Trace visibility also depends on the application’s tracer setup and sampling.
Recorded data
Section titled “Recorded data”The root span receives the query text as db.statement.
For OTel export, SQL containing invalid UTF-8 is quoted with byte escapes, such as \xe9. Valid UTF-8 stays unchanged. This prevents one query from causing the entire export batch to fail; the SQL and parameters sent to PostgreSQL stay unchanged.
Completed child spans can include messages, rowsReturned/Affected, and rowsTotalSize. messages lists the type names of the first 15 protocol messages the span handled; DataRow and CopyData messages are not counted, and if there are more, the span gets messages_truncated. rowsTotalSize is a human-readable string such as 1.2 kB, not a number. The row fields are added when the tracked total size is positive. Non-EOF errors are attached when a span finishes; EOF-only finishes are not marked as errors by this code.
The pg-proxy binary omits bind parameter values by default in both Datadog and OTel
modes. Set -trace-parameters=true to capture actual values, without obfuscation.
The library also defaults to capture disabled; embedders can
set server.RuntimeConfig.EnableTraceParameters (or session.Config.EnableTraceParameters
when constructing sessions directly) to true to enable it.
With capture on, the root span carries one tag per parameter position,
db.parameters.0 through db.parameters.n, taken from the first Bind of the
trace. $1 is db.parameters.0. A binary value is decoded with the type
declared in Parse, else the one PostgreSQL reported for the statement in a
ParameterDescription; a type declared as 0 or unknown counts as not declared.
A binary value whose type is neither declared nor described renders as hex.
Values are strings, including numbers, so values above 2^53 keep their precision.
| Value | Tag value |
|---|---|
| NULL | null |
| Text format | Up to the first 256 bytes, cut at the start of a UTF-8 character, then (+N bytes) for the rest |
Binary bool, int2, int4, int8, oid, float4, float8, numeric, uuid, date, timestamp, timestamptz |
PostgreSQL’s text form; timestamps are shown in UTC |
Binary text, varchar, bpchar, name, json, jsonb, xml |
As text |
| Binary arrays of those types | array[len=N]{…} with the first 10 elements; text elements are double-quoted |
| Any other type, malformed binary value, or format code other than text or binary | \x and the hex of the first 128 bytes, then (+N bytes) |
Tag values are not quoted, so NULL and the text null render alike, and a text
value that itself ends in (+N bytes) looks truncated.
The tags total at most about 4 KB and 32 positions. When a limit drops
positions, the root also gets pgproxy.bind.truncated=true and
pgproxy.bind.rendered with the number of positions emitted. Invalid UTF-8 is
escaped as \xNN for both tracers.
Each position adds one attribute, so a full Bind adds at most 34, within the
OpenTelemetry SDK’s default of 128 per span. If the SDK’s
attribute limit is lowered below that, it drops the positions that do not fit
and counts them in the span’s dropped-attribute count; pgproxy.bind.truncated
and pgproxy.bind.rendered describe only the proxy’s own limits. They are set
before the positions, so the SDK keeps them.
Values are recorded only when the root span’s head sampling decision keeps the
trace: a Datadog sampling priority above zero or not yet set, or an OTel span that is recording
and sampled. Traces kept later, for example because they contain errors, omit
db.parameters. Root spans that do not implement pgproxy.SamplingReporter
are treated as sampled.
Disabling capture skips parameter formatting and trace tagging; it does not change
the values forwarded to PostgreSQL. SQL text in db.statement, including literal
values, and error messages are unaffected. This option is not SQL obfuscation or
a general telemetry redaction policy.
See Telemetry configuration for exporter selection, destinations, and sampling options.
