Self-Hosted eBPF Database Observability: Tracing SQL Latency and Lock Contention in PostgreSQL and MySQL
Quick Summary (TL;DR)
- eBPF uprobes attach directly to PostgreSQL/MySQL user-space functions, capturing per-query latency, lock waits, and connection lifecycle events without application changes.
- You need Linux kernel 4.9+ (5.x+ strongly recommended),
bpftrace/BCC, and symbol-rich database binaries (do not strip them).- Trace
exec_simple_query/LockAcquire(PostgreSQL) anddispatch_command/lock_wait(MySQL) as your anchor probes.- Aggregate in-kernel with per-CPU maps, then ship to a self-hosted stack (Prometheus + Grafana, or ClickHouse + Grafana).
- This guide walks through prerequisites, working
bpftracescripts, a full pipeline, and the pitfalls that bite people in production.
Why eBPF for Database Observability?
Traditional database monitoring forces a trade-off. You either enable verbose server-side logging (e.g., PostgreSQL log_min_duration_statement, MySQL slow query log), which adds I/O overhead and gives you coarse timings, or you instrument the application with drivers and agents, which requires code changes, redeploys, and often misses the database’s internal view of the world.
eBPF sidesteps both. By attaching uprobes to functions inside the database server process, you observe the actual execution path—parse, plan, execute, lock acquisition, connection handshake—at the source, with kernel-level timestamps and minimal overhead. No application changes, no query log parsing, no sampling bias from a driver library.
The trade-off is operational: eBPF requires kernel privileges, symbol resolution, and careful probe design. This guide treats it as a production engineering problem, not a demo.
Prerequisites and Environment Setup
Kernel and Tooling Requirements
| Component | Minimum | Recommended | Notes |
|---|---|---|---|
| Linux kernel | 4.9 | 5.10+ | 5.x+ has better uprobe & BPF map support |
| Kernel config | CONFIG_BPF=y, CONFIG_UPROBES=y | + CONFIG_BPF_JIT=y, CONFIG_BPF_EVENTS=y | Verify with zgrep on /boot/config-* |
| Tooling | bpftrace 0.14 | bpftrace 0.20+, BCC | BCC for custom C probes |
| Privileges | root or CAP_SYS_ADMIN + CAP_BPF | Same | CAP_PERFMON helps on 5.8+ |
| Compiler | clang/LLVM for custom probes | clang 14+ | Only needed for BCC, not bpftrace |
Verify uprobe support before anything else:
# Confirm BPF and uprobes are available
grep -E "CONFIG_(BPF|UPROBES|BPF_EVENTS)=" /boot/config-$(uname -r)
# Quick smoke test: count syscalls (proves BPF works)
sudo bpftrace -e 'tracepoint:syscalls:sys_enter_openat { @[comm] = count(); }'
Database Configuration for Instrumentation
The critical requirement is unstripped binaries with symbol tables. Distro packages sometimes ship stripped binaries; check with nm or readelf.
# PostgreSQL: confirm symbols are present
nm -D /usr/lib/postgresql/16/bin/postgres | grep -E "exec_simple_query|LockAcquire"
# MySQL: symbols may live in the server binary or a shared lib
nm -D /usr/sbin/mysqld | grep -E "dispatch_command|lock_wait"
# If missing, check the shared client/server libs:
nm -D /usr/lib/mysql/libmysqlservices.so 2>/dev/null | grep dispatch_command
If symbols are absent, install a debug-symbol package (e.g., postgresql-16-dbgsym on Debian/Ubuntu, mysql-server-debuginfo on RHEL) or build from source with -g. Do not strip the binary during your build.
For MySQL, ensure the server is built with -fno-omit-frame-pointer if you plan to walk stacks; for latency timing alone, this is optional.
Instrumenting PostgreSQL with eBPF Uprobes
Key PostgreSQL Functions to Trace
| Function | Purpose | When to Trace |
|---|---|---|
exec_simple_query | Simple-protocol query execution | Latency for non-prepared queries |
exec_parse_message | Parse phase (extended protocol) | Parse latency, plan cache misses |
exec_bind_message | Bind phase | Parameter binding cost |
LockAcquire / LockRelease | Lock manager | Lock waits, contention |
PostgresMain / BackendInitialize | Backend lifecycle | Connection establishment |
ClientRead | Waiting for client input | Idle-in-transaction detection |
Example: Capturing Query Latency with bpftrace
This probe times exec_simple_query from entry to return and buckets the results into a histogram, aggregated per CPU to minimize lock contention:
sudo bpftrace -e '
uprobe:/usr/lib/postgresql/16/bin/postgres:exec_simple_query {
@start[tid] = nsecs;
}
uretprobe:/usr/lib/postgresql/16/bin/postgres:exec_simple_query
/ @start[tid] /
{
$dur = nsecs - @start[tid];
@query_latency_ns = hist($dur);
delete(@start[tid]);
}
'
Run a few queries against the database and you’ll see a latency histogram in microseconds. To capture which query, read the query string pointer from the function argument—exec_simple_query takes const char *query_string as arg0. For production, read the string via str(arg0) (bounded) and emit it into a ring buffer instead of printing to stdout.
For prepared statements, mirror the pattern on exec_parse_message and exec_bind_message, keying the map by tid so overlapping phases stay separated.
Tracing Lock Waits in PostgreSQL
Lock contention is where latency hides. Time LockAcquire and flag calls that block:
sudo bpftrace -e '
uprobe:/usr/lib/postgresql/16/bin/postgres:LockAcquire {
@lock_start[tid] = nsecs;
}
uretprobe:/usr/lib/postgresql/16/bin/postgres:LockAcquire
/ @lock_start[tid] /
{
$dur = nsecs - @lock_start[tid];
if ($dur > 1000000) { // > 1 ms = contended
@lock_wait_ns = hist($dur);
@contended[tid] = count();
}
delete(@lock_start[tid]);
}
'
The return value of LockAcquire is a LockAcquireResult enum; LOCKACQUIRE_NOT_AVAIL (or a wait) indicates contention. For a richer signal, pair this with pg_locks snapshots to attribute waits to specific relations.
Instrumenting MySQL with eBPF Uprobes
Key MySQL Functions to Trace
| Function | Purpose | When to Trace |
|---|---|---|
dispatch_command | Top-level command dispatch | Coarse query latency |
mysql_execute_command | SQL execution | Fine-grained execution latency |
mysql_parse | Parse + dispatch | Parse cost |
lock_wait / lock_rec_lock | InnoDB row lock acquisition | Lock contention |
do_handshake | Connection handshake | Connection establishment |
close_connection | Connection teardown | Pool churn |
Example: Capturing Query Latency with bpftrace
sudo bpftrace -e '
uprobe:/usr/sbin/mysqld:dispatch_command {
@start[tid] = nsecs;
}
uretprobe:/usr/sbin/mysqld:dispatch_command
/ @start[tid] /
{
$dur = nsecs - @start[tid];
@mysql_query_latency_ns = hist($dur);
delete(@start[tid]);
}
'
dispatch_command is the robust anchor: it wraps every command (queries, prepared statement ops, admin). For finer granularity, attach to mysql_execute_command instead—but note it may be inlined in some builds; verify with nm first.
Tracing Lock Contention in MySQL
InnoDB lock waits are the classic culprit behind mysterious p99 spikes. lock_wait is called when a thread must wait for a row lock:
sudo bpftrace -e '
uprobe:/usr/sbin/mysqld:lock_wait {
@lock_start[tid] = nsecs;
}
uretprobe:/usr/sbin/mysqld:lock_wait
/ @lock_start[tid] /
{
$dur = nsecs - @lock_start[tid];
@innodb_lock_wait_ns = hist($dur);
delete(@lock_start[tid]);
}
'
Because lock_wait only fires when a thread actually blocks, this histogram is a direct measure of contention severity. Combine it with lock_rec_lock counts to distinguish “many short waits” from “few long waits”—the former often means hot-row contention, the latter usually indicates a long-running transaction holding a lock.
Monitoring Connection Pool Behavior
Tracking Connection Establishment and Teardown
Connection churn is a silent killer of throughput. Trace the handshake and teardown functions to count new connections and their setup cost:
# PostgreSQL: time backend initialization
sudo bpftrace -e '
uprobe:/usr/lib/postgresql/16/bin/postgres:BackendInitialize { @conn_start[tid] = nsecs; }
uretprobe:/usr/lib/postgresql/16/bin/postgres:BackendInitialize
/ @conn_start[tid] /
{
@conn_setup_ns = hist(nsecs - @conn_start[tid]);
@new_conns = count();
delete(@conn_start[tid]);
}
'
For MySQL, substitute do_handshake and close_connection. A rising @new_conns rate against a stable query rate is a strong signal your pool is thrashing—connections being opened and closed faster than they’re reused.
Detecting Connection Pool Exhaustion
Pool exhaustion shows up as connection wait time, not connection count. Instrument the accept path and correlate with active backends:
flowchart TD
A[App requests connection] --> B{Pool slot free?}
B -- Yes --> C[Reuse pooled conn]
B -- No --> D[Block on pool / open new]
D --> E[eBPF: time accept + handshake]
E --> F{Wait > threshold?}
F -- Yes --> G[Alert: pool exhaustion]
F -- No --> C
C --> H[eBPF: time query via dispatch_command]
H --> I[Emit to ring buffer → pipeline]
The practical detection rule: if p95(connection_setup_time) climbs while active_connections sits at max_connections, you’re exhausting the pool. eBPF gives you the setup-time side of that equation directly, which pg_stat_activity alone cannot.
Building a Self-Hosted Observability Pipeline
Data Collection and Aggregation
bpftrace is excellent for exploration but not a production daemon. For a durable pipeline, write probes with BCC or libbpf in C, emitting events to a BPF ring buffer. A small userspace collector (Go or Rust) reads the ring buffer, enriches events with query text and connection IDs, and forwards them.
flowchart LR
P[PostgreSQL / MySQL] -->|uprobes| K[eBPF kernel programs]
K -->|ring buffer| C[Userspace collector]
C -->|OTLP / line protocol| A[Aggregator<br/>Vector / OTel Collector]
A --> S[(Storage<br/>Prometheus / ClickHouse)]
S --> G[Grafana dashboards]
A --> L[Loki / log store]
Key design choices:
- Aggregate in-kernel with per-CPU hash maps for histograms and counters; only emit raw events (with query text) for slow queries above a threshold.
- Bound string reads with
bpf_probe_read_user_strand a fixed max length (e.g., 256 bytes) to avoid overhead. - Sample high-frequency probes if you exceed ~50k events/sec.
Storage and Visualization
| Layer | Option | Best For |
|---|---|---|
| Metrics | Prometheus | Histograms, counters, alerting |
| Events | ClickHouse | High-cardinality per-query records, fast SQL |
| Logs | Loki | Query text correlation |
| Viz | Grafana | Unified dashboards across all three |
A pragmatic split: send aggregated histograms to Prometheus for alerting on p99 latency and lock-wait rates, and sampled slow-query events to ClickHouse for forensic “which query caused this spike” analysis.
Comparison: eBPF vs. Traditional Database Monitoring
| Dimension | eBPF Uprobes | Query Logging | APM / Driver Agents |
|---|---|---|---|
| Application changes | None | None | Required (agent/SDK) |
| Overhead | Low (JIT, in-kernel agg) | Moderate–high (I/O) | Moderate |
| Granularity | Function-level, per-query | Per-query (sampled) | Per-request |
| Internal DB visibility | High (locks, parse, bind) | Medium | Low (sees driver only) |
| Setup complexity | High (kernel, symbols) | Low | Low–medium |
| Production safety | Good (verifier) | Good | Good |
| Query text capture | Possible (bounded reads) | Native | Native |
| Cross-DB consistency | Same tooling for both | Per-DB formats | Varies |
eBPF wins on visibility and consistency; it loses on setup effort. The realistic posture is eBPF for latency and lock internals, plus existing APM for request-level context—join them on connection ID or timestamp.
Best Practices and Pitfalls
- Never strip database binaries. Symbol loss silently breaks every probe. Add a CI check that asserts
nmfinds your anchor functions. - Test probes in staging first. A bad probe on a hot function can add measurable latency; always measure overhead with
perf statbefore/after. - Use per-CPU maps. Shared hash maps serialize under load; per-CPU maps eliminate the contention.
- Bound every string read. Unbounded
bpf_probe_readon user memory is a fast path to dropped events and verifier rejections. - Watch for inlined functions. Modern compilers inline aggressively; if a probe never fires, the symbol may not exist as a discrete function—check
nmand fall back to a parent function. - Respect kernel security policy. Kernel lockdown mode or restricted
kernel.unprivileged_bpf_disabledsettings can block loading; plan for privileged sidecars. - Version-pin your probes. Function signatures change between PostgreSQL/MySQL major versions; a probe written for PG 15 may misread arguments on PG 16.
Conclusion
eBPF uprobes give you something neither query logs nor APM agents can: a direct, low-overhead view of the database’s internal execution path—parse, execute, lock, and connection lifecycle—without touching application code. Start with a single anchor probe (exec_simple_query or dispatch_command), prove the histogram matches reality, then expand to lock waits and connection churn. Once those signals are flowing into a self-hosted Prometheus + ClickHouse + Grafana stack, you have production-grade database observability that no vendor can take away.
FAQ
What are the system requirements for running eBPF-based database observability?
You need Linux kernel 4.9 or later (5.10+ recommended for better uprobe and BPF map support), with CONFIG_BPF, CONFIG_UPROBES, and CONFIG_BPF_EVENTS enabled. Ensure root or CAP_SYS_ADMIN/CAP_BPF privileges to load programs. Install bpftrace and/or BCC, plus clang/LLVM if you write custom C probes.
Can I use eBPF to trace queries without modifying my application code?
Yes. Uprobes attach to user-space functions inside the database server process—exec_simple_query, dispatch_command, lock_wait—so you instrument the database binaries directly. No application changes, redeploys, or driver configuration are required.
How does eBPF handle high query throughput without adding significant overhead? eBPF programs are JIT-compiled and run in-kernel. For high throughput, aggregate with per-CPU hash maps, bound all string reads, and sample or threshold-emit raw events (e.g., only slow queries). This keeps overhead typically under a few percent even at tens of thousands of queries per second.
What specific PostgreSQL and MySQL functions should I trace?
For PostgreSQL: exec_simple_query, exec_parse_message, exec_bind_message for latency; LockAcquire/LockRelease for locks; BackendInitialize/PostgresMain for connections. For MySQL: dispatch_command, mysql_execute_command, mysql_parse for latency; lock_wait/lock_rec_lock for contention; do_handshake/close_connection for connection lifecycle.
Is it safe to run eBPF probes in production, and how do I correlate with application traces? Yes—eBPF’s verifier enforces safety, but always test in staging and measure overhead first. To correlate with application traces, capture thread IDs or connection IDs in your probes and propagate them via application logs or headers, then join on those keys (or on timestamp + query text) in your observability backend.