Disclaimer: The opinions stated here are my own, not those of my employer.
Over my past two posts on bringing native gRPC, Protocol Buffers, and Cloud/GenAI SDKs and modern columnar I/O, vector search, and ML engines to Perl (now tracked across 35 distributions in the PDL Data & ML Ecosystem PR Reviewer’s Guide), a long-standing architectural gap kept resurfacing: once a Perl service is speaking multiplexed HTTP/2 RPCs and streaming Arrow batches in contiguous C memory, how should it talk to relational and cloud databases without blocking the event loop?
This post introduces an upstream RFC issue (perl5-dbi/dbi#183), a perl.dbi.dev mailing list discussion, a working core implementation in perl5-dbi/dbi#185 (branch feature/non-blocking-core, accompanied by a commit-by-commit PR #185 Reviewer’s Guide), and 8 companion DBD::* pull requests bringing a unified, zero-ABI-breakage non-blocking contract to Perl’s DBI. Nothing in this API surface is set in stone: the primary goal right now is gathering critical review from DBI and DBD::* maintainers, async framework authors, and Perl application developers before finalizing the driver contract.
1. Twenty Years in the Making: Why Async Perl Databases Fragmented
When Tim Bunce architected DBI in 1994, vendor C client libraries were overwhelmingly synchronous. As event loops and coroutines grew in popularity, standardizing non-blocking execution inside DBI became one of Perl’s longest-running open design threads:
- 2004: Tim Bunce’s official August 2004
DBIroadmap listed “Support non-blocking mode for drivers that can enable it in their client API”, and earlydbi-devproposals around$sth->readyand$sth->doneexplored how to reconcile differing vendor C state machines. - 2010:
DBI 1.615shippedDBD::Gofer::Transport::corostreamas an experimentalCoro/AnyEventproxy, while noting in the documentation that globally overridingCORE::selectwas fragile. - 2018: Pali opened
perl5-dbi/dbi#52requesting a stable, driver-independentDBIAPI unifyingDBD::PgandDBD::mysql(alongside parallel statement execution). Tim Bunce replied with an open invitation for someone to synthesize the prior discussions ondbi-devand drive a concrete implementation forward.
In the absence of a core contract, individual drivers and frameworks solved the problem incompatibly:
DBD::PgexposedPG_ASYNC,pg_ready,pg_result, and$dbh->{pg_socket}overlibpq.DBD::mysqladdedmysql_async,mysql_async_ready,mysql_async_result, and$dbh->mysql_fd.DBD::MariaDBintroducedmariadb_async,mariadb_async_ready,mariadb_async_result, and$dbh->mariadb_sockfd.DBD::ODBCrelied on ODBC’sSQL_ATTR_ASYNC_ENABLEandSQL_STILL_EXECUTINGpolling model without exposing a POSIX socket descriptor at all.
Higher-level frameworks either had to reach underneath DBI for driver-specific file descriptors (as Mojo::Pg and DBIx::Poggy do), spin up separate worker processes (AnyEvent::DBI, DBIx::Class::Async), or bypass DBI altogether (Database::Async).
2. Core Design of perl5-dbi/dbi#185: Five Engineering Pillars

Pull request perl5-dbi/dbi#185 implements a minimal, opt-in non-blocking core across 8 focused commits (56bd55e through 2ad72af, touching 13 files at +1,412 / -13 lines, with all 228 test files and 12,104 assertions passing; see the local verification commands), alongside a POSIX-pipe reference driver (DBD::MockAsync), DBI::PurePerl and DBD::Gofer parity (2af5246), and a formal driver specification in DBI::DBD (4731bd9). Five constraints guided the design:
- Zero Binary ABI Breakage (
56bd55e,5c3d3c0): Five new handle flags (DBIcf_Async,DBIcf_AsyncWantRead,DBIcf_AsyncWantWrite,DBIcf_AsyncMultiplex, andDBIcf_AsyncBufferWrites) pack into unused upper bits (0x01000000through0x10000000) ofdbih_com_std_t.flags, while two new per-interpreterdbistate_tfields (async_wouldblock_svandasync_notify_watcher) claim 2 of the 3 existing reservedpad2pointer slots (leavingpad2[1]free). Neither struct sizes nor field offsets change. For OS packagers maintaininglibdbi-perlalongside dozens of precompiled XS drivers in Debiantrixie/forkyor Enterprise Linux, upgradingDBIrequires zero binaryperl-dbi-abirebuild transitions. - Strict Synchronous Isolation: All
WOULDBLOCKsentinel interception and suppression ofRaiseError,PrintError, andHandleErrorare strictly gated onDBIc_ASYNC(imp_xxh). Existing synchronous applications (even when using legacy drivers that emiterr == -1) behave identically to stockDBI. - Event-Loop-Agnostic Readiness (
2ad72af): Drivers notify an optionalAsyncWatcherobject viaon_add,on_modify, andon_removecallbacks carrying the socket descriptor and readiness mode ("r","w", or"rw"), and event loops drive state machines forward via$h->async_read_ready()and$h->async_write_ready(). Optional lazy-loadedDBI::AsyncWatcheradapters coverIO::Async,AnyEvent,EV, andMojo::IOLoop(orFuture::AsyncAwaitwrappers) with zero new core CPAN prerequisites. - First-Class C/XS Driver Helpers:
DBIXS.hexposesDBIh_ASYNC_SET_WOULDBLOCK,DBIh_ASYNC_NOTIFY_WATCHER, andDBIh_ASYNC_CLEAR_WANTunder#ifdef DBIcf_Async, eliminating roughly 50 lines of error-prone Perl-stack andPERL_MAGIC_tiedC boilerplate per driver while allowing updated XS drivers to compile cleanly against olderDBIreleases. - Concurrency,
fork(), and Thread Safety (2ff8959,76aeab9): A parent-aware concurrency guard blocks accidental synchronous calls whileAsyncWantReadorAsyncWantWriteis active on a statement handle or its parent$dbh(unlessAsyncMultiplex => 1is advertised by an HTTP/2 or multiplexed transport); storing async state on per-interpreterdbistate_tkeeps Perlithreadsclean under Valgrind; andDESTROYskips PID checks soAutoInactiveDestroycontinues to work safely acrossfork().
3. What It Looks Like in Practice
From Perl application code, connecting in non-blocking mode, attaching an event-loop watcher, and streaming rows without driver-specific method names looks identical whether the backend is PostgreSQL, MariaDB, MySQL, or Cloud Spanner:
use strict;
use warnings;
use DBI qw(:async);
use DBI::AsyncWatcher;
my $dbh = DBI->connect('dbi:Pg:dbname=app', $user, $pass, {
RaiseError => 1,
Async => 1,
});
$dbh->{AsyncWatcher} = DBI::AsyncWatcher->new('AnyEvent', $dbh);
my $sth = $dbh->prepare('SELECT id, name FROM accounts WHERE active = ?');
my $rv = $sth->execute(1);
if (DBI::is_wouldblock($sth->err)) {
defined(my $rows = $sth->async_read_ready()) or die $sth->errstr;
}
while (my $row = $sth->fetch_async_row()) {
last if DBI::is_wouldblock($row);
}
Inside a C/XS driver’s dbdimp.c, signaling a non-blocking read yield and registering the underlying socket file descriptor with the caller’s watcher takes just a few lines guarded by #ifdef DBIcf_Async:
#ifdef DBIcf_Async
if (DBIc_ASYNC(imp_sth)) {
DBIc_ASYNC_WANT_READ_on(imp_sth);
DBIc_ASYNC_WANT_READ_on(imp_dbh);
DBIh_ASYNC_SET_WOULDBLOCK(sth, imp_sth);
DBIh_ASYNC_NOTIFY_WATCHER(sth, imp_sth, fd, "on_add", "r");
return 0;
}
#endif
4. Proving the Contract Across 8 Companion Drivers
A core specification is only useful if real drivers with very different wire models can implement it cleanly. Early community engagement across dbi-users, perl.dbi.dev, and perl5-dbi/dbi#185 shaped every major trade-off in this prototype:
- The Single-Event-Loop Principle & Core Isolation (David Nicol): David immediately highlighted the core constraint (“a system should have only one event loop”), arguing for a simple “async-check-and-do” readiness model and lightweight cooperative
defer/yieldprimitives rather than baking heavy futures or promises intoDBIcore. He also pushed us to explicitly weigh three architectural paths: core C-engine flags, a higher-level named-template facade (handling handle weakening to prevent closure leaks), or a greenfield parallel namespace (DBI_NB::/DBD_NB::) to leave rock-solid blockingDBIuntouched. Weighing that clean-break simplicity against Python 2-to-3-style ecosystem fragmentation led directly to the backward-compatiblendbiproof-of-concept fork. POEPatterns & Review Stewardship (Kurt Starsinic, H. Merijn Brand /Tux, and Daniël van Eeden): WithTuxand Daniël van Eeden following the design thread from July 2026 onward, Kurt stepped up to evaluate howPOE::Component::EasyDBIandPOEevent-loop patterns fit the readiness contract, andTuxboth encouraged careful multi-reviewer scrutiny (motivating the 8-commit split and Reviewer’s Guide) and suggested Kurt as an arbiter for the PR#185review.- Security Hardening & Driver Adoption (Robert Rothenberg /
robrwoand Ed Sabol /esabol): Robert (CPAN Security Group) contributed an incisive review catching unconditionalerr == -1suppression, file-staticithreadslifetimes, statement-level capability gates,DESTROYacrossfork(), and mortal accumulation infetch_async_*, while Ed asked, “What do we need to do forDBD::Pg? PR welcome!”
Answering that question led to building and testing 8 companion pull requests spanning traditional C/XS SQL sockets, timer-polled ODBC handles, and HTTP/2 multiplexed gRPC cloud databases:
| Driver | Pull Request | Transport & Verification Highlights |
|---|---|---|
DBD::Pg (Debian) | bucardo/dbdpg#224 | libpq (PG_ASYNC, PQsocket, PQflush); verified against live PostgreSQL 17 (14/14 new t/09async_dbi.t + 127/127 existing t/08async.t PASS) |
DBD::mysql (Debian) | DBD-mysql#505 | C client mysql_async, mysql_async_ready, mysql_async_result, and net.fd socket readiness |
DBD::MariaDB (Debian) | DBD-MariaDB#257 | Non-blocking MariaDB wire state machine (mariadb_async_* and sock_fd) |
DBD::ODBC | DBD-ODBC#35 | ODBC SQL_ATTR_ASYNC_ENABLE / SQL_STILL_EXECUTING timer-driven polling without requiring a POSIX socket FD |
DBD::Spanner | google-auth-library-perl#42 | Concurrent statement execution over multiplexed HTTP/2 gRPC (AsyncMultiplex => 1) with legacy-DBI fallback |
DBD::BigQuery | google-auth-library-perl#43 | Async JobServiceClient polling plus optional lazy-loaded Storage Read API and PDL::IO::Arrow columnar batch side-loading |
DBD::Bigtable | google-auth-library-perl#44 | GoogleSQL v2 ExecuteQuery streaming over non-blocking HTTP/2 gRPC (AsyncMultiplex => 1) |
DBD::Datastore | google-auth-library-perl#45 | GQL v1 RunQuery over non-blocking HTTP/2 gRPC (AsyncMultiplex => 1) |
Exercising all eight drivers against live databases and event loops immediately surfaced subtleties a synthetic mock could have missed: exempting diagnostic accessors ($sth->err, errstr, state, and set_err) from the active-handle concurrency guard during live PostgreSQL 17 runs; switching DBI::AsyncWatcher from Perl’s FD-aliasing '<&=' mode to dup(2)-backed '<&' so watcher garbage collection never closes a driver’s underlying socket; standardizing async_read_ready() return values (0 while pending, row count or '0E0' on completion, undef strictly on error); supporting non-FD drivers like DBD::ODBC via timer polling; and proving pure-Perl dual-DBI compatibility via defined(&DBI::is_wouldblock) so updated drivers remain installable on older DBI releases.
5. Open Design Questions: Looking for Community Feedback
Because a core DBI contract will live for decades once released, getting the ergonomics and edge cases right matters far more than merging quickly. We would especially value maintainer and user feedback on five open design questions:
fetch_async_row()yield convention: Shouldfetch_async_row()return theDBI_ASYNC_WOULDBLOCKsentinel on a non-blocking yield, or should it returnundef(using$sth->{AsyncWantRead}to distinguish a temporary pause from end-of-stream) so a naivewhile (my $row = $sth->fetch_async_row)loop can never accidentally dereference a truthy sentinel?- Signaling
WOULDBLOCKvia$h->errvs. handle attributes: Is signaling would-block via$h->err(analogous to POSIXEAGAIN, strictly gated onAsync => 1) ergonomic for Perl callers, or is leaving$h->erruntouched on yield and inspecting$h->{AsyncWantRead}cleaner? DBI::AsyncWatcherpackaging: Should the lazy-loaded event-loop adapters inDBI::AsyncWatchership inDBIcore (where they introduce zero hard dependencies), or live in a separate CPAN distribution so adapter release cadence stays decoupled fromDBI?- Driver capability opt-in: Is checking for a driver-implemented
async_read_readymethod the cleanest capability gate forAsync => 1, or wouldDBD::*authors prefer an explicit driver capability flag? - Additional
DBD::*prototypes: Which other driver maintainers (for exampleDBD::Oracle,DBD::SQLite,DBD::Firebird, orDBD::DB2) would like to test or co-author non-blocking prototypes againstperl5-dbi/dbi#185?
If you maintain a DBD::* driver, work on IO::Async, Future::AsyncAwait, AnyEvent, POE, or Mojolicious, or run high-concurrency Perl services in production, please check out the PR #185 Reviewer’s Guide and share your thoughts on perl5-dbi/dbi#185, the RFC issue (#183), or the perl.dbi.dev mailing list thread.