DuckDB Extension
Events
Send DuckDB query and transaction events to an external handler as JSON. Configure event types and session labels for logging or monitoring.
On this page
Send DuckDB activity to an event handler
Events exposes query, transaction, and connection activity from a DuckDB process. It starts a handler program and writes structured JSON events to that programβs standard input.
Use the stream to build a query log, track failures, or feed an existing monitoring system. You choose which events to capture and what the handler does with them. The extension provides the events; storing them and sending alerts are responsibilities of the handler.
Example
Send query events to a handler
Configure an executable that reads JSON from standard input, then run a query that produces events.
Before you run it: Create an executable handler and replace the placeholder path. The handler example explains the input contract.
Run this example in the DuckDB CLI or a native client.
INSTALL events FROM community;
LOAD events;
-- Replace this path with your executable event handler.
SET events_destination = '/absolute/path/to/event-handler';
SET events_types = ['query_begin', 'query_end'];
SET events_session_name = 'example-session';
SELECT 42 AS answer;
The SQL returns 42; the event payloads go to the handler, not the result table. Configure only the event types your handler needs.
Common tasks
Deep Dive
Technical Details
These examples use DuckDB 2.0 or later. Complete the repository setup and installation first.
What you can do with four PRAGMAs
The single most useful pattern: turn every query DuckDB runs into a structured JSON line on the stdin of a program of your choice, with no SQL functions to call and no application code to change:
LOAD events FROM query_farm;
SET events_destination = '/usr/local/bin/event-handler.py';SET events_types = ['query_begin', 'query_end'];SET events_session_name = 'analytics-replica';SET events_async = TRUE;From this point on, every statement you run produces a query_begin and query_end line on the handlerβs stdin β paired by query_id, tagged with the session name, with has_error and error_message populated when something goes wrong. The handler can be a shell script, a Python service, a Go binary, or anything else that reads stdin a line at a time.
Events is configured per running DuckDB process, not in the database file. PRAGMAs are forgotten on restart β set them again at session start, or stash them in a startup script. The same caveat applies to the sibling cronjob extension: both are βoperate your DuckDB processβ tools and observability is only available while the process is up.
For a durable audit trail, point events_destination at a handler that writes to durable storage (file, S3, Kafka, syslog) β the destination is durable, the configuration is not.
How delivery works
The extension launches the program at events_destination as a child process and writes one JSON event per line to its stdin. The handler is a long-lived consumer β DuckDB does not re-spawn it per event.
- Synchronous (default). DuckDB writes the event line and waits for the handler to consume it before returning from the originating query. Reliable: every event the database emits is acknowledged by the handler before the query completes. The cost is latency on every query.
SET events_async = TRUE. Fire-and-forget. DuckDB does not block on the handler. If the handler stalls, dies, or canβt keep up, events are dropped silently. Use for high-throughput workloads where βbest-effort observabilityβ is the right tradeoff.
Thereβs no in-between mode β pick one per session.
Event types and what they carry
All events share a common envelope: event, timestamp (ISO 8601), database_path, session_name, connection_id, process_id. Per-type fields layer on top:
| Event | Extra fields |
|---|---|
connection_opened, connection_closed |
(envelope only) |
query_begin |
query_id, transaction_id, attached_databases[] |
query_end |
query_id, transaction_id, has_error, error_message?, error_type?, attached_databases[] |
transaction_begin, transaction_commit |
transaction_id, start_timestamp, is_read_only |
transaction_rollback |
transaction_id, start_timestamp, is_read_only, has_error, error_message?, error_type? |
query_id correlates query_begin and query_end for the same statement; transaction_id ties query events to the surrounding transaction. attached_databases is an array of {name, path, type, read_only, temporary} records describing every database visible to the connection at event time β useful when you have multiple ATTACH-ed catalogs and want to attribute activity to one of them.
Choosing what to capture
The default ['query_begin', 'query_end'] is the right starting point: query-level audit visibility, two events per statement. Scale up or down as needed:
- Audit-only: keep the default. Two events per query, both with
query_idso you can pair them. - Errors-only:
['query_end']and filterhas_error = truein the handler β half the volume. - Connection churn: add
connection_opened,connection_closedto spot connection leaks or ephemeral session storms. - Transactional forensics: add the three
transaction_*events; group bytransaction_idto reconstruct exactly which statements ran inside each commit or rollback.
Thereβs no per-query filter at the extension layer β every event of an enabled type is emitted. Filter downstream in the handler if you need to.
Operational guidance
- Path must be fully qualified.
events_destinationis invoked directly, not via a shell.python3 my_handler.pywonβt work β point at the executable file (/usr/local/bin/my-handler.pywith a shebang, or/usr/bin/python3with the script asargv[1]if you wrap it). - The handler runs as DuckDB. It inherits the database processβs privileges and environment. Treat the destination path as security-sensitive: write-protect it from the database user.
- Sync mode = your handler is on the critical path. A 50ms-per-event handler adds 50ms to every query. Add timeouts and a fast path; or accept the tradeoff and switch to async.
- Use
events_session_namefor attribution. When several DuckDB processes feed the same handler β replicas, tenant-per-process layouts, CI runners β give each one a session name so events are distinguishable downstream.
Reference
Extension Contents
Quick reference to all available functions and settings organized by category.
| Name | Type | Description |
|---|---|---|
|
Configuration
PRAGMAs that wire DuckDB's internal event stream to an external program. Set |
||
| events_async | Object type: Setting | When TRUE, events are delivered fire-and-forget β DuckDB doesn't wait for the handler before returning from the originating query. |
| events_destination | Object type: Setting | Path to an external program that receives event JSON via stdin. |
| events_session_name | Object type: Setting | Optional string included in every event. |
| events_types | Object type: Setting | List of event types to capture. |
No extension contents match that search.
Configuration
Settings
Configure the events extension behavior using these settings.
events_async
When TRUE, events are delivered fire-and-forget β DuckDB doesn't wait for the handler before returning from the originating query. Trades reliability for latency.
false
events_destination
Path to an external program that receives event JSON via stdin. Set to enable event forwarding; unset to disable. Must be a fully-qualified executable path.
β
events_session_name
Optional string included in every event. Useful for distinguishing events from multiple DuckDB processes feeding the same handler.
β
events_types
List of event types to capture. Available: 'connection_opened', 'connection_closed', 'query_begin', 'query_end', 'transaction_begin', 'transaction_commit', 'transaction_rollback'. Default: ['query_begin', 'query_end'].
[query_begin, query_end]
Practical Examples
Cookbook
Real-world recipes and patterns for common use cases.
These examples use DuckDB 2.0 or later. Complete the repository setup and installation first.
Wire up a handler
LOAD events FROM query_farm;
-- Required: a fully-qualified path to an executableSET events_destination = '/usr/local/bin/event-handler.py';
-- Pick the event types (default is ['query_begin', 'query_end'])SET events_types = ['query_begin', 'query_end'];
-- Optional: a tag included in every event lineSET events_session_name = 'analytics-replica';
-- Optional: don't block queries on the handlerSET events_async = TRUE;Append every query to a daily log file
The smallest possible audit trail β one JSONL file per day, written by a shell handler:
#!/usr/bin/env bash# /usr/local/bin/log-to-file.sh β append every event to a daily logexec >> "/var/log/duckdb/events-$(date +%F).jsonl"catSET events_destination = '/usr/local/bin/log-to-file.sh';SET events_types = ['query_begin', 'query_end'];
-- Every query now appends two lines to today's log fileSELECT count(*) FROM orders;Page on query errors
query_end includes has_error, error_message, and error_type when a query fails. Filter in the handler and post to your alerting system:
#!/usr/bin/env python3# /usr/local/bin/error-alerter.pyimport json, sys, urllib.request
for line in sys.stdin: e = json.loads(line) if e.get('event') == 'query_end' and e.get('has_error'): urllib.request.urlopen( 'https://alerts.example.com/page', data=line.encode(), )SET events_destination = '/usr/local/bin/error-alerter.py';SET events_types = ['query_end'];SET events_async = TRUE; -- don't let a slow alerter block queries
-- A failed query produces a query_end with has_error=trueSELECT * FROM nonexistent_table;Track transaction lifecycle
Capture the full begin/commit/rollback sequence and group by transaction_id:
SET events_destination = '/usr/local/bin/txn-tracker.py';SET events_types = ['transaction_begin', 'transaction_commit', 'transaction_rollback'];
BEGIN;INSERT INTO orders VALUES (1, 'widget', 99.99);COMMIT;-- Two events: transaction_begin and transaction_commit, same transaction_id.A transaction_rollback carries has_error and error_message when the rollback was triggered by a failure.
Per-tenant attribution
When several DuckDB processes feed the same handler, tag each one and group downstream by session_name:
-- In the per-tenant startup scriptSET events_destination = '/usr/local/bin/multi-tenant-collector.py';SET events_session_name = 'tenant-acme';SET events_types = ['query_begin', 'query_end'];SET events_async = TRUE;# /usr/local/bin/multi-tenant-collector.py β bucket events by tenantimport json, sys, collections
counts = collections.Counter()for line in sys.stdin: e = json.loads(line) if e.get('event') == 'query_end': counts[e.get('session_name', 'unknown')] += 1 # ... ship to your metrics backend, or write to per-tenant filesPair query_begin and query_end for latency
Both events share a query_id. Maintain a small in-memory map in the handler:
#!/usr/bin/env python3# /usr/local/bin/latency-recorder.pyimport json, sysfrom datetime import datetime
starts = {}for line in sys.stdin: e = json.loads(line) qid = e.get('query_id') ts = datetime.fromisoformat(e['timestamp'].replace('Z', '+00:00'))
if e['event'] == 'query_begin': starts[qid] = ts elif e['event'] == 'query_end' and qid in starts: latency_ms = (ts - starts.pop(qid)).total_seconds() * 1000 print(f"qid={qid} latency_ms={latency_ms:.1f} error={e.get('has_error')}", flush=True)SET events_destination = '/usr/local/bin/latency-recorder.py';SET events_types = ['query_begin', 'query_end'];Fan out to multiple consumers
Only one events_destination is allowed. Point it at a small dispatcher that forks the stream:
#!/usr/bin/env bash# /usr/local/bin/fanout.sh β split the event stream three waysexec tee \ >(cat >> /var/log/duckdb/events.jsonl) \ >(curl -s -X POST -H 'content-type: application/x-ndjson' \ --data-binary @- https://collector.example.com/ingest) \ > /dev/nullSET events_destination = '/usr/local/bin/fanout.sh';Re-applying configuration on session start
PRAGMAs do not persist across restarts (same caveat as the cronjob extension). Stash the four SET statements in a startup file that every connection runs:
-- /etc/duckdb/init.sqlLOAD events FROM query_farm;SET events_destination = '/usr/local/bin/event-handler.py';SET events_types = ['query_begin', 'query_end'];SET events_session_name = 'prod-replica-1';SET events_async = TRUE;duckdb -init /etc/duckdb/init.sql /data/analytics.duckdbPlatform Support
Compatibility
Extension availability may vary by platform and DuckDB version. Check below to ensure this extension supports your environment before installation.
Quick Facts
Platforms
Haybarn 1.5.6
- Linux x86_64aarch64
- Linux (musl) Not available
- macOS IntelApple Silicon
- Windows x86_64x86_64 (MinGW)
- WASM Not available
Compiled binary sizes
| Platform | Architecture | Size |
|---|---|---|
| Linux | x86_64 | 3.22 MB |
| Linux | aarch64 | 2.85 MB |
| macOS | Intel | 2.60 MB |
| macOS | Apple Silicon | 2.26 MB |
| Windows | x86_64 | 7.39 MB |
| Windows | x86_64 (MinGW) | 12.85 MB |
Compressed download sizes for the release shown above.
DuckDB & Haybarn
Release calendar- Haybarn v1.5.6 Built-in community repository Supported
Browser examples use Haybarn-Wasm 2.0.0-rc12.
Checked .