Metadata-Version: 2.4
Name: pg_lock_tracer
Version: 0.8.0
Summary: An eBPF based lock tracer for PostgreSQL
Author-email: Jan Nidzwetzki <jnidzwetzki@gmx.de>
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/jnidzwetzki/pg-lock-tracer
Project-URL: Bug Tracker, https://github.com/jnidzwetzki/pg-lock-tracer/issues
Keywords: postgresql,postgres,ebpf,locktracer
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Debuggers
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: graphviz
Requires-Dist: igraph
Requires-Dist: prettytable
Requires-Dist: psycopg2
Requires-Dist: pyelftools
Dynamic: license-file

<p align="center">
  <img src="https://raw.githubusercontent.com/jnidzwetzki/pg-lock-tracer/main/docs/logo.png" alt="pg-lock-tracer logo" width="300">
</p>

# Lock tracing tools for PostgreSQL
[![Build Status](https://github.com/jnidzwetzki/pg-lock-tracer/actions/workflows/tests.yml/badge.svg)](https://github.com/jnidzwetzki/pg-lock-tracer/actions/workflows/tests.yml)
[![PyPI](https://img.shields.io/pypi/v/pg-lock-tracer?color=green)](https://pypi.org/project/pg-lock-tracer/)
[![PyPI - Downloads](https://img.shields.io/pypi/dm/pg-lock-tracer)](https://pypi.org/project/pg-lock-tracer/)
[![Release date](https://img.shields.io/github/release-date/jnidzwetzki/pg-lock-tracer)](https://github.com/jnidzwetzki/pg-lock-tracer/)
[![License](https://img.shields.io/github/license/jnidzwetzki/pg-lock-tracer)](https://github.com/jnidzwetzki/pg-lock-tracer/blob/main/LICENSE)
[![GitHub Repo stars](https://img.shields.io/github/stars/jnidzwetzki/pg-lock-tracer?style=social)](https://github.com/jnidzwetzki/pg-lock-tracer/)

A set of eBPF-based tools designed to observe and visualize PostgreSQL 🐘 locking activity. These tools help users understand lock timing and contention behavior.

Key components:

- `pg_lock_tracer`: heavy lock tracer (e.g., table level locks)
- `pg_lw_lock_tracer`: lightweight lock (LWLock) tracer
- `pg_row_lock_tracer`: row-level lock tracer
- `pg_spinlock_delay_tracer`: spinlock delay tracer
- `animate_lock_graph`: render animated lock graphs from `pg_lock_tracer` tracer output

**Which tool do I need?**

| Tool | Traces | Typical question it answers |
|---|---|---|
| `pg_lock_tracer` | Table/relation locks (heavy locks) | Which tables are being locked, and how long do lock waits take? |
| `pg_lw_lock_tracer` | Lightweight locks (LWLocks) | Is a backend stuck waiting on an internal PostgreSQL lock (e.g. `WALWrite`, `ProcArray`)? |
| `pg_row_lock_tracer` | Row-level locks | Which rows are being locked (e.g. `SELECT ... FOR UPDATE`), and did the lock block? |
| `pg_spinlock_delay_tracer` | Spinlock delays | Is a backend busy-spinning on a low-level spinlock for too long? |

> [!NOTE]
> These tools rely on [eBPF](https://ebpf.io/) (_Extended Berkeley Packet Filter_) technology. At the moment, PostgreSQL 15, 16, 17, 18, and 19 are supported (see [Additional Information](#additional-information)).

## Contents

- [Comparison with Built-in PostgreSQL Tools](#comparison-with-built-in-postgresql-tools)
- [Quickstart](#quickstart)
- [pg_lock_tracer](#pg_lock_tracer)
- [pg_lw_lock_tracer](#pg_lw_lock_tracer)
- [pg_row_lock_tracer](#pg_row_lock_tracer)
- [pg_spinlock_delay_tracer](#pg_spinlock_delay_tracer)
- [Additional Information](#additional-information)
- [License](#license)

## Comparison with Built-in PostgreSQL Tools

PostgreSQL includes several lock-related tools, but none of them offer a continuous, timestamped trace.

- **`pg_locks`** — a snapshot of locks currently held or waited for, but it does not track the history of acquisitions, releases, or their durations.
- **`pg_stat_activity.wait_event` / `wait_event_type`** — shows what a backend is currently waiting on (such as `Lock`, `LWLock`, or `BufferPin`), but this is also just a snapshot.
- **`log_lock_waits` + `deadlock_timeout`** record heavy-lock waits that go over a set threshold, but they do not cover LWLocks, row locks, or spinlock delays.

`pg-lock-tracer` fills this gap by providing a continuous, nanosecond-timestamped event stream with statistics and stack traces for heavy locks, LWLocks, row locks, and spinlock delays, all without changing the running server.

## Quickstart
1. Install the pg-lock-tracer tools:

```shell
pip install pg-lock-tracer
```

2. Identify the PostgreSQL server binary used by your instance (e.g., `/usr/lib/postgresql/X/bin/postgres`).
3. Start tracing a running Postgres PID (requires root privileges):

```shell
sudo pg_lock_tracer -x /path/to/postgres
```

This shows the locking activity of all processes running this PostgreSQL binary. 

## pg_lock_tracer
`pg_lock_tracer` observes the locking activity of a running PostgreSQL process (using _eBPF_ and _UProbes_), giving you a continuous view of table-level lock activity, timings, and statistics — unlike `pg_locks`, which only shows locks held right now.

```shell
pg_lock_tracer -x /usr/lib/postgresql/18/bin/postgres -p 1234
```

📖 **[Full documentation](https://github.com/jnidzwetzki/pg-lock-tracer/blob/main/docs/pg_lock_tracer.md)** — usage examples, JSON output, statistics, event filtering, stack traces, and animated lock graphs.

## pg_lw_lock_tracer
`pg_lw_lock_trace` allows to trace lightweight locks ([LWLocks](https://github.com/postgres/postgres/blob/c8e1ba736b2b9e8c98d37a5b77c4ed31baf94147/src/backend/storage/lmgr/lwlock.c)) in a PostgreSQL process via _Userland Statically Defined Tracing_ (USDT).

```shell
pg_lw_lock_tracer -p 1234
```

📖 **[Full documentation](https://github.com/jnidzwetzki/pg-lock-tracer/blob/main/docs/pg_lw_lock_tracer.md)** — usage examples, output samples, and statistics.

## pg_row_lock_tracer
`pg_row_lock_tracer` allows to trace row locks (see the PostgreSQL [documentation](https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-ROWS)) of a PostgreSQL process using _eBPF_ and _UProbes_.

```shell
pg_row_lock_tracer -x /usr/lib/postgresql/18/bin/postgres
```

📖 **[Full documentation](https://github.com/jnidzwetzki/pg-lock-tracer/blob/main/docs/pg_row_lock_tracer.md)** — usage examples, output samples, and statistics.

## pg_spinlock_delay_tracer
`pg_spinlock_delay_tracer` allows tracing spinlock delays in a PostgreSQL process. Spin locks protect short critical sections in the code; if another process already holds one, the requesting process repeatedly checks (i.e., "spins") until it becomes available, and after a while PostgreSQL performs a ["spin delay"](https://github.com/postgres/postgres/blob/0c8e082fba8d36434552d3d7800abda54acafd57/src/backend/storage/lmgr/s_lock.c#L106) and yields the CPU to avoid busy-waiting. `pg_spinlock_delay_tracer` reports these delays, including the spin/delay counts and the source location where the delay occurred.

```shell
pg_spinlock_delay_tracer -x /usr/lib/postgresql/17/bin/postgres
```

📖 **[Full documentation](https://github.com/jnidzwetzki/pg-lock-tracer/blob/main/docs/pg_spinlock_delay_tracer.md)** — usage examples and a step-by-step guide to reproduce a spinlock delay.

## Additional Information

### Installation

The PostgreSQL lock tracing tools are available as a Python package and require Python 3.11 or newer. These tools depend on the Python package for BPF. Unfortunately, this package is currently not available via `pip` (the Python package manager). Therefore, the package of the Linux distribution needs to be installed to provide this dependency. On Debian and Ubuntu, this can be done by executing the following command:

```shell
apt install python3-bpfcc
```

The tracing tools can be installed system-wide or in a dedicated [virtual environment](https://docs.python.org/3/library/venv.html). To create and install the tools in such a virtual environment, the following steps must be performed. To install the tools system-wide, these steps can be skipped.

```shell
cd <installation directory>
python3 -m venv .venv
source .venv/bin/activate

# Copy the distribution Python BCC packages into this environment
cp -av /usr/lib/python3/dist-packages/bcc* $(python -c "import sysconfig; print(sysconfig.get_path('platlib'))")
```

Now, the tracing tools can be installed directly via `pip` by executing:

```shell
pip install pg-lock-tracer
```

The tools are now installed and can be invoked by calling `pg_lock_tracer` or `pg_lw_lock_tracer`.

If you want to install the latest development snapshot of the tools, the following command needs to be executed:

```shell
pip install git+https://github.com/jnidzwetzki/pg-lock-tracer
```

Want to work on the tools themselves? See [CONTRIBUTING.md](https://github.com/jnidzwetzki/pg-lock-tracer/blob/main/CONTRIBUTING.md) for the development setup.

### PostgreSQL Build
The software is tested with PostgreSQL versions 15, 16, 17, 18, and 19. In order to be able to attach the _uprobes_ to the functions, they should not to be optimized away (e.g., inlined) during the compilation of PostgreSQL. Otherwise errors like `Unable to locate function XXX` will occur when `pg_lock_tracer` is started. For optimized builds, see the experimental support for production builds below.

It is recommended to compile PostgreSQL with the following CFLAGS: `CFLAGS="-ggdb -Og -g3 -fno-omit-frame-pointer"`. 

#### Production Builds (Experimental)

> [!WARNING]
> `pg_lock_tracer` and `pg_spinlock_delay_tracer` now support experimental optimized production builds on x86_64. In these builds, the compiler inlines functions into their callers. For example, `GrantLock` is inlined into `LockAcquireExtended`, `FastPathGrantRelationLock` appears only as an inlined copy, and the spin counting of `perform_spin_delay` is inlined into `s_lock`. A _uprobe_ on the function symbol will not detect calls to these inlined copies.

The following table shows which tools work with which PostgreSQL builds:

| Tool | Traced via | Debug build | Production build (e.g., `-O2`, LTO) |
|---|---|---|---|
| `pg_lock_tracer` | _uprobes_ on lock, table, transaction, and query functions | ✅ | ⚠️ Experimental (x86_64), needs the debug symbols to trace inlined functions |
| `pg_lw_lock_tracer` | USDT probes | ✅ (with `--enable-dtrace`) | ✅ with `--enable-dtrace` (the apt.postgresql.org packages are built with it) |
| `pg_row_lock_tracer` | _uprobe_ on `heapam_tuple_lock` | ✅ | ✅ (the function is called via the table access method and is never inlined) |
| `pg_spinlock_delay_tracer` | _uprobe_ on `perform_spin_delay` | ✅ | ⚠️ Experimental (x86_64), needs the debug symbols to trace the inlined copies; without them, only calls of the out-of-line copy are traced (with LTO, almost none) |

If [DWARF](https://dwarfstd.org/) debug information is available, `pg_lock_tracer` and `pg_spinlock_delay_tracer` use it to find all inlined copies of the traced functions and attach a probe to each one. They read function parameters, such as the lock mode, from the locations given by the debug information, like registers. The tools search for debug information in the binary itself (if PostgreSQL is compiled with `-g`), in `/usr/lib/debug/.build-id/`, and in the file referenced by the `.gnu_debuglink` section. To install debug symbols from [apt.postgresql.org](https://wiki.postgresql.org/wiki/Apt), use the following command:

```shell
apt install postgresql-17-dbgsym
```

When you start one of these tools, it lists the inlined copies being probed. If you use the `-v` option, it shows more details about these copies and where the parameters are located.

```text
===> Function FastPathGrantRelationLock not found in the binary (probably inlined), falling back to the DWARF debug information; this may take a while
===> GrantLock: probed on its symbol and at 5 inlined copies
===> FastPathGrantRelationLock: no symbol, probed at 1 inlined copy
```

Limitations:

* Only x86_64 is supported.
* Reading the debug information takes a few seconds at startup. The packages of the Linux distributions are built with link time optimization (LTO), which inlines functions across source files. For these packages, reading the debug information takes up to a minute, and several hundred inlined copies are probed (e.g., `table_close` alone is inlined at more than 600 places).
* Parameters that are optimized out at an inlined copy are shown as `Unknown` (e.g., the lock mode).
* The return of a function (`QUERY_END` for `exec_simple_query` and `LOCK_RELATION_OID_END` for `LockRelationOid`) is traced only on the function symbol, which includes symbols renamed by LTO (e.g., `exec_simple_query.lto_priv.0`). Returns from inlined copies of these functions are not traced. If a build inlines one of these functions completely, its return events are missing, and `pg_lock_tracer` prints a warning at startup.
* Stack traces (`-s`) require frame pointers (`-fno-omit-frame-pointer`), which are omitted by many production builds.
* If neither the function symbol nor debug information is available, `pg_lock_tracer` stops with an error that asks to install the debug symbols.

`pg_lw_lock_trace` uses [USDT probes](https://www.postgresql.org/docs/current/dynamic-trace.html). Therefore, PostgreSQL has to be compiled with `--enable-dtrace` to use this script.

## License

This project is licensed under the [Apache License 2.0](https://github.com/jnidzwetzki/pg-lock-tracer/blob/main/LICENSE).
