NAME

Dancer2::Plugin::DBIC::Async - High-concurrency DBIx::Class bridge for Dancer2

VERSION

Version 0.05

BENEFITS

The primary benefit of this plugin is Concurrency Throughput. Unlike traditional database plugins that block your Dancer2 worker during a query, this plugin delegates I/O to a background worker pool.

Non-Blocking I/O (Concurrency)

In a traditional sync app, if a database query takes 500ms, that Dancer2 worker is "busy" and cannot accept any other incoming requests for that half a second.

Sync

10 workers can handle exactly 10 simultaneous long-running queries. The 11th user must wait in the TCP queue.

Async

A single worker can initiate dozens of database queries. While the database is processing the data, the worker remains free to handle other incoming requests or perform other I/O tasks.

Parallelism within a Single Route

With the sync plugin, if you need to fetch data from five different tables that don't depend on each other, you must do them sequentially. With the async plugin, you can fire all five queries simultaneously.

# Regular Sync (Total time = sum of all queries)
my $user    = rset('User')->find(1);
my $posts   = rset('Post')->search({ uid => 1 });
my $friends = rset('Friend')->search({ uid => 1 });

# Async (Total time = the time of the single slowest query)
my $user_f    = async_rs('User')->find(1);
my $posts_f   = async_rs('Post')->search({ uid => 1 });
my $friends_f = async_rs('Friend')->search({ uid => 1 });

# Wait for all to finish
my ($user, $posts, $friends) = Future->wait_all($user_f, $posts_f, $friends_f)->get;

Key Technical Differences

Context Switching

In the sync version, the operating system might pause the process (context switch) while waiting for the disk. In the async version, the Event Loop (IO::Async) manages this, which is much lighter on the CPU.

Wait vs. Block

In the async version, we use wait_all or then. This tells the server: "Keep this request in mind, but go help other users until the data comes back."

Error Handling

Futures have built-in on_fail handlers, making it easier to manage database timeouts without crashing the whole worker process.

Better Resource Utilisation

Sync apps often solve scaling issues by adding more worker processes (e.g., increasing Starman workers). However, each worker consumes significant RAM.

Sync Scaling

High Memory usage (100 workers = 100x memory).

Async Scaling

Low Memory usage (1 worker handles 100 connections).

SYNOPSIS

# In config.yml
plugins:
  "DBIC::Async":
    default:
      schema_class: "MyApp::Schema"
      dsn: "dbi:SQLite:dbname=myapp.db"
      async:
        workers: 4

# In your Dancer2 app
use Dancer2;
use Dancer2::Plugin::DBIC::Async;
use Future;

# Basic non-blocking count
get '/count' => sub {
    my $count = async_count('User')->get;
    return to_json({ total_users => $count });
};

# Advanced: Parallel queries (non-blocking)
get '/dashboard' => sub {
    my $query = query_parameters->get('q');

    # 1. Fire multiple queries simultaneously
    my $search_f = async_search('User', { name => { -like => "%$query%" } });
    my $count_f  = async_count('User');

    # 2. Wait for all background workers to finish
    Future->wait_all($search_f, $count_f)->get;

    # 3. Retrieve results (already deflated to HashRefs)
    my @users = @{ $search_f->get };
    my $total = $count_f->get;

    template 'dashboard' => {
        users => \@users,
        total => $total,
    };
};

# Flexible Update (Scalar ID or HashRef query)
post '/user/:id/deactivate' => sub {
    my $id = route_parameters->get('id');
    async_update('User', $id, { active => 0 })->get;
    return "User deactivated";
};

KEYWORDS

async_db

my $schema = async_db();
my $schema = async_db('custom_connection');

Returns the underlying DBIx::Class::Async::Schema instance for the specified connection. Use this for complex operations like txn_do or direct storage management. The connection name defaults to 'default'.

async_rs

my $rs = async_rs('User');
my $f  = $rs->search({ active => 1 })->page(2)->all;

Returns a DBIx::Class::ResultSet proxy for the specified source. Methods called on this proxy return Future objects instead of data. This is the most flexible way to build complex, non-blocking queries.

async_count

my $f = async_count('User');
my $f = async_count('User', 'custom_connection');

Returns a Future that resolves to the integer count of records in the specified source.

async_find

my $f = async_find('User', $id);
my $f = async_find('User', $id, 'custom_connection');

Returns a Future that resolves to a single record (as a deflated HashRef) matching the provided primary key. Returns undef if no record is found.

my $f = async_search('Contact', { active => 1 });
my $f = async_search('Contact', { id => 5 }, 'archive');

Returns a Future that resolves to an ArrayRef of HashRefs representing the rows. This is the recommended way to fetch multiple records for non-blocking templates or JSON responses.

async_create

my $f = async_create('User', { name => 'Alice', email => 'alice@example.com' });

Returns a Future that resolves to the newly created record as a deflated HashRef.

async_update

my $f = async_update('User', $id, { status => 'inactive' });
my $f = async_update('User', { status => 'pending' }, { status => 'active' });

Returns a Future that resolves to the number of rows updated (as an integer).

Note: The second argument can be either a scalar primary key (assumed to be the column 'id') or a standard DBIx::Class search HashRef for complex updates.

async_delete

my $f = async_delete('User', $id);
my $f = async_delete('User', { status => 'spam' });

Returns a Future that resolves to the number of rows deleted (as an integer).

Note: Like async_update, the second argument can be a scalar primary key (targeting the column 'id') or a search HashRef.

DATA FORMAT

All keywords that return row data (async_find, async_search, async_create) return deflated HashRefs rather than DBIx::Class::Row objects. This ensures that the data is safe to use outside of the background worker's event loop and is ready for serialization to JSON or rendering in templates.

AUTHOR

Mohammad Sajid Anwar, <mohammad.anwar at yahoo.com>

REPOSITORY

https://github.com/manwar/Dancer2-Plugin-DBIC-Async

BUGS

Please report any bugs or feature requests through the web interface at https://github.com/manwar/Dancer2-Plugin-DBIC-Async/issues. I will be notified and then you'll automatically be notified of progress on your bug as I make changes.

SUPPORT

You can find documentation for this module with the perldoc command.

perldoc Dancer2::Plugin::DBIC::Async

You can also look for information at:

LICENSE AND COPYRIGHT

Copyright (C) 2026 Mohammad Sajid Anwar.

This program is free software; you can redistribute it and / or modify it under the terms of the the Artistic License (2.0). You may obtain a copy of the full license at:

http://www.perlfoundation.org/artistic_license_2_0

Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License.By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license.

If your Modified Version has been derived from a Modified Version made by someone other than you,you are nevertheless required to ensure that your Modified Version complies with the requirements of this license.

This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder.

This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement,then this Artistic License to you shall terminate on the date that such litigation is filed.

Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.