Search by

lekoala / kaly-tasks

lekoala

Durable PostgreSQL, MySQL or SQLite task queue for invocable PHP tasks

Package info

github.com/lekoala/kaly-tasks

pkg:composer/lekoala/kaly-tasks

Statistics

Installs: 23

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

0.8.0 2026-11-19 09:16 UTC

This package is auto-updated.

Last update: 2026-11-28 21:35:40 UTC


README

A durable SQL task queue for invocable PHP objects, with first-class Kaly integration.

It stores tasks in PostgreSQL, MySQL or SQLite and runs them in supervised worker processes: a durable task queue without a queue server. It implements the task dispatcher contracts of kaly-contracts, without depending on Kaly itself, so with Kaly it is one optional engine and application code does not change:

$this->tasks->dispatch(new GeneratePdf($documentId));

A task stays a plain invocable object, with its data in the constructor and its services in __invoke():

final readonly class GeneratePdf
{
    public function __construct(
        public string $documentId,
    ) {}

    public function __invoke(PdfGenerator $generator): void
    {
        $generator->generate($this->documentId);
    }
}

It is a specialized engine, not a messaging framework: no attributes, no handler registry, no events, no transports.

Scheduling

$tasks->dispatch(new DeliverSms($deliveryId), notBefore: $clock->now()->modify('+10 seconds'));
$tasks->dispatch(new SendReminder($appointmentId), notBefore: $reminderDate);

notBefore is an optional DateTimeImmutable lower bound. Without it, dispatch is immediate; a past date is immediately eligible. A future task cannot be reserved before its deadline, but polling and worker load may make it run later. stopWhenEmpty stops when nothing is due, even if future tasks remain queued.

The application expresses business dates with its injected PSR-20 clock. The stores keep SQL time for availability comparisons, leases, retries and retention; application and database clocks must be synchronized for relative business delays. Dates are normalized at the storage boundary: PostgreSQL stores timezone-aware instants and MySQL stores UTC DATETIME(6), both preserving microseconds. SQLite keeps integer epoch seconds and rounds fractional deadlines up to the next second, so precision never makes a task eligible early. No schema migration is needed.

For portable dates, use UTC years 1000 through 9999, the range of MySQL DATETIME(6). Dates outside this range are unsupported; use strict SQL mode so MySQL rejects out-of-range dates instead of coercing them to a zero date. PostgreSQL dates before the common era are also unsupported by this date codec.

Deduplication preserves the existing task, including its payload and deadline: a second dispatch with the same key neither advances nor postpones it. Retries use their normal SQL-clock delay after execution, independently of the original deadline. A scheduled insertion joins the application transaction as usual.

Kaly\Task\ScheduledTaskDispatcher comes from lekoala/kaly-contracts ^1.0. Kaly is optional; applications using it require Kaly 0.7 or later. Services that schedule work depend on this interface; services that only submit tasks can keep Kaly\Task\TaskDispatcher. Kaly's direct dispatcher offers the minimal contract, and its recording dispatcher supports scheduling with an injectable test clock.

Moving a scheduled reminder

Use a business version to supersede reminders without changing stored tasks:

final readonly class SendAppointmentReminder
{
    public function __construct(
        public string $appointmentId,
        public int $version,
        public string $deduplicationKey,
    ) {}

    public function __invoke(AppointmentRepository $appointments, ReminderSender $sender): void
    {
        $appointment = $appointments->find($this->appointmentId);
        if ($appointment === null || $appointment->cancelled) {
            return;
        }
        if ($appointment->version !== $this->version) {
            return; // superseded by a later change
        }
        $sender->send($appointment);
    }
}

$registry->register(
    'appointments.remind',
    SendAppointmentReminder::class,
    deduplicateBy: 'deduplicationKey',
);

// On booking or rescheduling, ideally in the same application transaction:
$tasks->dispatch(
    new SendAppointmentReminder(
        $appointment->id,
        $appointment->version,
        "{$appointment->id}:{$appointment->version}",
    ),
    notBefore: $appointment->startsAt->modify('-1 day'),
);

Increment the business version for every relevant change: date, location, recipient and cancellation. The handler explicitly checks deletion and cancellation too: matching a version does not establish that an appointment is still active. An obsolete reminder still runs at its original deadline, consumes one execution slot and returns without sending.

The version check is not atomic with sending: if the appointment changes during an external call, an outdated reminder may still be sent. Decide whether that race is acceptable for notifications; business writes need suitable concurrency control. Use a stable provider idempotency key for the reminder operation to prevent repeated external effects on retries; it does not make the version check atomic with sending.

Deduplicating by appointmentId alone cannot move a reminder because it preserves the existing deadline. Versioned keys provide a recipe without a cancellation or rescheduling API.

Recurring tasks

There is no recurring scheduler: cron or Symfony Scheduler decides which occurrences are due and dispatches them. Deduplicating by the occurrence stores it once, even when several hosts dispatch it:

$registry->register('reports.daily', GenerateDailyReport::class, deduplicateBy: 'period');

// On every host, from cron
$tasks->dispatch(new GenerateDailyReport($clock->now()->format('Y-m-d')));

This prevents duplicate insertions, not missed or repeated occurrences:

  • when no host dispatches at the scheduled time, the occurrence does not exist: catching up belongs to the scheduler or the application;
  • once its key is purged, dispatching an old period again stores it again;
  • a worker crashing after an external effect runs the task again.

For an effect that must happen once per period, such as billing, keep a business constraint (a unique row per period) and check it in the task.

Sequences

Submit a linear sequence without coupling each task to its successor:

$tasks->sequence([
    new PrepareConversation($id),
    new GenerateAnswer($id),
    new PublishAnswer($id),
], notBefore: $at);

DatabaseTaskDispatcher implements Kaly\Tasks\TaskSequenceDispatcher, a capability local to this package. Bind that interface to the same dispatcher instance when a service needs sequences; kaly-contracts remains unchanged. There is no builder or final dispatch() call: sequence() writes the first task and its continuation, subject to the application's transaction. It returns true for a new insertion and false when the first step's deduplication key is already stored. A true result inside an application transaction still needs that transaction to commit. A thrown error may leave the insertion outcome uncertain, just like dispatch().

  • Pass a non-empty list of registered task objects. One task is equivalent to an ordinary dispatch. Every step is encoded and validated before any insertion.
  • notBefore applies to the first step only. After each successful completion, the next step becomes eligible immediately, using the database clock.
  • Each step has its own queue and a fresh attempt count. Its retry policy is resolved from the worker's registry when it runs. A worker must poll that queue for the sequence to progress.
  • Future steps are a flat JSON continuation in the current task row's nullable chain column; they have no rows yet. Completing a step and inserting the next are one transaction, guarded by the current owner token. An old owner changes nothing. A database failure rolls back both writes and stops the worker; after an uncertain commit, the database may already have advanced the sequence.
  • Retries and lease recovery preserve the continuation. A terminal failure keeps it on the failed row. retryFailed() resumes that step with fresh attempts; deleteFailed() or purging that failed row abandons the remaining steps.
  • Reservations carry the raw continuation JSON. Before invoking the current task, the worker validates it. A malformed continuation fails only that task, without invoking it or blocking unrelated work. The original JSON stays on the failed row for inspection and repair through an application migration or SQL. Repair it before calling retryFailed(); retrying unchanged data fails again. complete() also rejects malformed continuations for callers using the store directly. Storage and settlement failures still stop the worker.
  • A completed row no longer keeps its continuation. Statistics count task rows, not future steps; there is no sequence history or global sequence status.

Only the first step may have a deduplication key. A conflict skips the whole new submission, preserving the original continuation even if the new steps differ. That protection lasts until the first row is deleted or purged, even if later steps are still running. Use a distinct business execution ID when needed. sequence() rejects deduplicated task types in later positions before calling the store. SQL stores also reject keys on continuation steps passed directly to push().

Tasks keep their results in durable application state identified by their payloads. Task return values are ignored. Delivery is still at least once: the atomic queue transition does not include business writes or external API calls, so task effects must be idempotent. Branches, parallel steps, compensation and an onFailure callback are outside this API.

Use sequences for short chains that benefit from independent retries or reusable steps. Each transition rewrites the remaining list, so the cumulative continuation data written grows quadratically with the number of equally sized steps. The number of task insertions remains linear.

Custom stores and the continuation codec

Implement Kaly\Tasks\Store\TaskStore for dispatch and worker operations. Implement Kaly\Tasks\Store\TaskStoreAdmin to expose failed-task management, statistics and retention. The built-in stores implement both contracts and expose their own schema() for migrations.

Kaly\Tasks\Store\TaskChain is a public storage codec:

$json = TaskChain::encode($encodedTask->chain); // string, or null for no continuation
$remaining = TaskChain::decode($json);         // list<EncodedTask>

It stores a flat JSON list of objects containing name, queue and payload strings. Payload text is preserved verbatim. Encoding rejects invalid steps, keys and nested continuations with InvalidArgumentException; decoding malformed stored data throws UnexpectedValueException.

A custom TaskStore validates and encodes EncodedTask::$chain before insertion, then returns that raw JSON in ReservedTask::$chain without decoding at reservation. This lets the worker isolate malformed continuations using the normal failed-task path. Completion decodes it with the same codec and atomically transfers the remaining steps to the successor, clearing the completed row. Other settlement and recovery operations preserve the raw value unchanged. A custom backend may choose its own persistence representation, but must return this JSON format in the reservation.

Upgrading an existing queue for sequences

All three stores require the new column, including for ordinary dispatches and reservations. schema() creates new tables; it does not migrate existing ones. Add the nullable column through your application's migrations, adapting the table name as needed:

-- PostgreSQL
ALTER TABLE kaly_tasks ADD COLUMN chain JSON;

-- SQLite
ALTER TABLE kaly_tasks ADD COLUMN chain TEXT;

-- MySQL / Aurora MySQL
ALTER TABLE kaly_tasks ADD COLUMN chain LONGTEXT;

Existing rows have chain = NULL and remain ordinary tasks. Add the column first, replace all workers, then enable sequence submissions. An old worker can mark a step done without inserting its continuation. Keep sequence producers disabled during the worker rollout; do not roll back to old workers while any continuations remain. No new indexes or statuses are needed.

Guarantees

  • At least once. A task runs until it succeeds, fails for good, or exceeds its attempts. After a crash, a task may run again: tasks must be idempotent.
  • Leases with owner tokens. A reserved task belongs to one worker for the lease duration. Settlement requires ownership, not a live lease: a worker finishing after its deadline can still record its result until recover() invalidates the reservation. Recovery clears the owner, and a new reservation gets a new token, so the late worker's settlement then changes nothing. A lease does not stop a live worker, so two runs may exceptionally overlap. Keeping timeout < lease helps prevent overlap; it is not a condition for accepting settlement.
  • Bounded retries. Exponential backoff per task type, then failed. A task can fail at once or choose its next delay, see Failures and retries. A task abandoned too often (worker crashes, timeouts) fails without running.
  • Whitelisted JSON payloads. Only registered types are stored and rebuilt, under stable names. No PHP serialization, no class name in the database.
  • Deduplication. A task type may declare a deduplication parameter: a task whose key is already stored is skipped, whatever its status, until it is purged. A failed task is not replaced by a new dispatch: inspect it and retryFailed().

Deduplicating a task is not deduplicating its effects. If a worker calls an external API and crashes before settling the task, the call is repeated. Carry a stable operation key in the task and use it for the provider idempotency, or reconcile the external state before acting.

When a dispatch fails

Situation What is known Response
Validation rejection before SQL: unregistered task, unencodable payload, NUL in an identifier or an out-of-range value No insertion was attempted Correct the input and dispatch again
A definite SQL rejection, such as an invalid type or a NOT NULL constraint violation That insertion was rejected Correct the cause and dispatch again; respect the transaction's error state
Lost connection, ambiguous COMMIT or a failure after sending the statement The task may have been stored Do not infer that the task is absent; retry with the same deduplication key while it is retained, or reconcile the stored state

Retrying with the same deduplication key prevents duplicate stored tasks while that key is retained. It does not guarantee exactly-once external effects. purge() and deleteFailed() free retained keys. An application transaction must commit before the task becomes durable; commit failures may themselves have an uncertain outcome.

PDO, Doctrine and Cycle cannot reliably classify every failure, so there is no OutcomeUnknownException hierarchy. An arbitrary exception is not proof that nothing was written. See Where the queue lives: with a dedicated queue database, business commit and dispatch are separate writes.

Where the queue lives

The table can live in the application database or in a database of its own. The connection given to the dispatcher decides what dispatch() guarantees:

Dispatcher connection When dispatch() returns
The application connection, inside a transaction The task is written in that transaction: durable with the commit, gone with a rollback (transactional outbox)
A dedicated queue database The task is durable immediately, independently of the business transaction

With a dedicated database, the business commit and the dispatch are two separate writes. For reliable publication, write a transactional application outbox and publish it idempotently: a process can crash between the business commit and a direct dispatch. Tasks must also tolerate changed business data.

The worker always uses its own connection to the queue database.

Stores

All three stores give the same guarantees and pass the same test suite. Use the database the application already has: on the application connection, a dispatch joins the business transaction.

PostgresTaskStore SqliteTaskStore MysqlTaskStore
Hosts Any number of hosts One host Any number of hosts
Reservation One statement with an indexed lookup per queue and SKIP LOCKED One UPDATE ... RETURNING Short transaction with SKIP LOCKED
Clock Database Host, in whole seconds Database, UTC microseconds
Requires PostgreSQL SQLite 3.38 through pdo_sqlite MySQL 8.0.16+ / Aurora MySQL v3, InnoDB

The SQLite store does not support ext-sqlite3 (Doctrine's sqlite3 driver): it runs a statement again when its rows are fetched, so a reservation would claim a second task. DoctrineConnection refuses that driver. See the PHP bugs:

  • #64531: SQLite3Result::fetchArray() may run the query again;
  • #81376: it explicitly affects UPDATE … RETURNING.

SQLite serializes writes, not tasks: a worker holds no lock while its task runs, so several workers process tasks in parallel. Contention only shows with many concurrent writes or long application transactions. The store leaves the connection settings to you:

  • a file on a local disk, never on a network share, in WAL mode (PRAGMA journal_mode = WAL);
  • a busy timeout on every connection (pdo_sqlite waits 60s by default, PDO::ATTR_TIMEOUT);
  • PRAGMA synchronous = FULL if a power loss must not lose the last dispatched tasks (WAL with NORMAL may);
  • backups taken with VACUUM INTO or the SQLite backup API, not by copying the file.

Connections

All SQL stores require Kaly\Tasks\Connection\TransactionalConnection, which extends the two statement operations of Connection with a transaction callback:

Library Connection
PDO new PdoConnection($pdo), or new PdoConnection(fn(): PDO => ...) for a lazy handle, which must return the handle running the transaction
Doctrine DBAL / ORM new DoctrineConnection($entityManager->getConnection())
Cycle new CycleConnection($databaseManager->database())

Statements run on the given connection, inside its current transaction. An EntityManager or a Cycle unit of work opened per operation does not matter: the transaction belongs to the shared connection.

TransactionalConnection is implemented by all three adapters. Its transaction() callback receives a connection pinned to the primary for the whole transaction, commits before returning and rolls back on failure. Existing transactions are refused for this callback: MySQL reservation must release its locks before executing the task, and a sequence completion must commit its transition before returning. Tasks must close their own transactions before returning to the worker. Dispatch and sequence submission still join an existing application transaction normally.

MySQL and Aurora

$pdo = new PDO($writerDsn, $user, $password);
$store = new MysqlTaskStore(new PdoConnection($pdo));

Requires MySQL 8.0.16+ with InnoDB, or Aurora MySQL v3. Use the writer endpoint for dispatch, reservation and maintenance. Reservations select with FOR UPDATE SKIP LOCKED, update the owner and lease, then commit before the worker invokes the task. The worker uses its own connection without an existing transaction. Database errors propagate and the supervisor restarts the worker; an uncertain commit is recovered through the lease, without running the task on the failed reservation.

MySQL polls queues individually through the pending index to avoid a filesort locking every ready task across several queues. Queue order is shuffled for each reservation; ordering by availability and ID is preserved within each queue. There is no global FIFO guarantee across queues. Use prioritizeQueues on the worker for a strict queue order.

Times are UTC DATETIME(6) values computed by the database, independently of the session time zone. Payloads use LONGTEXT to preserve their exact JSON text. Deduplication indexes a SHA-256 hash of the task name and key, compared bytewise, with the same retention as the other stores (subject to SHA-256 collision risk). Queue names and owner tokens are limited to 255 bytes. Use strict SQL mode to reject oversized values. MySQL table names are plain lowercase identifiers of at most 64 characters. Run schema() through migrations before dispatching; MySQL DDL implicitly commits.

When publishing a business change and a task atomically, share the same physical connection and transaction. Otherwise use a transactional application outbox: a dispatch after a business commit can be lost if the process crashes between the two writes.

Setup

Create the table from your migrations:

foreach ($store->schema() as $statement) {
    // execute $statement
}

PostgresTaskStore takes a table name, optionally schema-qualified (queue.tasks). SqliteTaskStore takes a plain table name.

Register task types and bind the required contracts to the same dispatcher instance:

use Kaly\Task\ScheduledTaskDispatcher;
use Kaly\Task\TaskDispatcher;
use Kaly\Tasks\Connection\DoctrineConnection;
use Kaly\Tasks\DatabaseTaskDispatcher;
use Kaly\Tasks\RetryPolicy;
use Kaly\Tasks\Store\PostgresTaskStore;
use Kaly\Tasks\TaskRegistry;
use Kaly\Tasks\TaskSequenceDispatcher;

$app->configure(fn(Definitions $di) => $di
    ->set(TaskRegistry::class, static fn() => (new TaskRegistry())
        ->register('documents.generate-pdf', GeneratePdf::class)
        ->register('support.process-webhook', ProcessWebhook::class,
            queue: 'support',
            retry: new RetryPolicy(maxAttempts: 8, delay: 30),
            deduplicateBy: 'eventId',
        ))
    ->set(ScheduledTaskDispatcher::class, static fn(ContainerInterface $c) => new DatabaseTaskDispatcher(
        new PostgresTaskStore(new DoctrineConnection($c->get(EntityManagerInterface::class)->getConnection())),
        $c->get(TaskRegistry::class),
    ))
    ->alias(TaskDispatcher::class, ScheduledTaskDispatcher::class)
    ->alias(TaskSequenceDispatcher::class, ScheduledTaskDispatcher::class));

A persistable task has only public promoted constructor parameters, typed int, float, string, bool, array (of scalars, null and arrays) or a backed enum. Registration checks it. Payloads are JSON objects, including {} for tasks without constructor parameters; JSON lists such as [] are rejected. Float values must be finite, including inside nested arrays. Decoding checks enum backing types strictly and reports invalid payloads with UnexpectedValueException.

Stored payloads are a public contract in both directions while tasks are stored: see Deploying task changes.

dispatch() follows Kaly's void contract. To observe whether deduplication skipped an insertion, use $store->push($registry->encode($task)): it returns true for a new task and false for an existing key.

All stores reject NUL bytes (\0) in task names, queue names, deduplication keys and owner tokens with InvalidArgumentException before executing SQL. This prevents PostgreSQL text parameters from being silently truncated, changing routing or treating distinct tasks as duplicates. NUL characters in task data remain supported as JSON escapes, unless used as a deduplication key.

Worker

Kaly has no console: a worker is a small script of the application.

// bin/worker.php
$app = App::create(dirname(__DIR__))->boot();
$container = $app->container();

$worker = new Worker(
    new PostgresTaskStore(new PdoConnection(new PDO($queueDsn))),
    $container->get(TaskRegistry::class),
    $container->get(Injector::class)->invoke(...),
    $container->get(LoggerInterface::class),
);
$worker->run(new WorkerOptions(queues: ['default', 'support']));

The third argument is the invoker: it calls each decoded task and provides the services of its __invoke(). With kaly-di, pass $injector->invoke(...). Any other container that can call a callable with its dependencies fits behind a closure; tasks without services only need static fn(object $task) => $task(). The invoker is required on purpose: a worker that silently called tasks without their services would turn a configuration mistake into failed tasks.

Run it under a supervisor (systemd, supervisord, a container restart policy). The worker is crash-only and recycles itself:

  • it exits normally after maxTasks, maxRuntime or memoryLimit, and the supervisor starts a fresh process;
  • a store failure (lost connection) propagates and ends the process;
  • with ext-pcntl, SIGTERM finishes the current task then exits, and a task running beyond timeout ends the process. Its lease expires and the task is retried. Keep timeout above your external call timeouts and below lease, see Long tasks and timeouts.

Without ext-pcntl (Windows), there is no hard timeout: the lease must cover the longest run.

Queue priority

By default the order of queues carries no meaning: each store keeps its own selection policy (oldest available task across queues on PostgreSQL and SQLite, queues in shuffled order on MySQL). This is not a fairness guarantee.

With prioritizeQueues, the order becomes a strict priority: the worker asks each queue in turn and takes the first reservable task.

$worker->run(new WorkerOptions(
    queues: ['delivery', 'async'],
    prioritizeQueues: true,
));
  • A busy earlier queue can starve later ones.
  • Each poll costs one reservation call per queue until a task is found, so an idle worker makes one call per queue per sleepMs.
  • Priority applies when a task is reserved, not to latency: a worker busy with a long async task finishes it before taking urgent work. For a latency target, run a dedicated worker on the urgent queue.
  • stopWhenEmpty stops once no queue has a reservable task, even if some hold tasks scheduled for later.

The worker opens no container scope per task. Shared services must be re-entrant, and stateful resources (EntityManager, unit of work) are opened by the operation that uses them, as for a request. A task never receives an HTTP context: identity and authorization travel in its data and are checked again.

With PostgreSQL, leases and delays use the database clock, so workers on several hosts agree.

Low-latency PostgreSQL workers

An idle worker sleeps for sleepMs (1 s by default), so an isolated task can wait almost a second before it starts. To wake on commit instead, opt in to LISTEN/NOTIFY:

use Kaly\Tasks\Store\PostgresNotifyWaiter;

$store = new PostgresTaskStore(new PdoConnection(new PDO($queueDsn)));
$waiter = PostgresNotifyWaiter::fromDsn($store, $queueDsn);

$worker = new Worker(
    $store,
    $container->get(TaskRegistry::class),
    $container->get(Injector::class)->invoke(...),
    $container->get(LoggerInterface::class),
    waiter: $waiter,
);

Add the trigger to your migrations, after schema():

foreach ($store->notificationSchema() as $statement) {
    // execute $statement
}

notificationSchema() is idempotent and changes no table or index. It installs an AFTER INSERT OR UPDATE trigger and its function; dropNotificationSchema() removes both and restores plain polling. notificationsEnabled() reports whether the trigger is present and enabled. The waiter logs a warning at start when it is missing, then falls back to polling.

pg_notify() cannot run inside a prepared transaction. If you use two-phase commit (XA), installing the trigger makes PREPARE TRANSACTION fail for any transaction that inserts, releases, recovers or manually retries a task. Enqueue outside the prepared transaction, or leave the trigger uninstalled and poll. This affects existing producers as soon as the trigger exists, even if no worker uses a waiter.

The table stays the source of truth. A notification only makes the worker look again, and every wakeup ends in the usual reservation:

  • PostgreSQL delivers the notification at commit: nothing is sent before the commit, on rollback or when deduplication skips the insert.
  • release() (a retry) and recovery from an expired lease notify again; complete() does not.
  • The waiter waits at most until the next available_at of the polled queues, so a task scheduled ahead is not held for the fallback. It also caps the wait by maxRuntime and the next recovery.
  • A dedicated listener connection belongs to each worker. The wait is a real block, not a query loop. Use PostgresNotifyWaiter::fromDsn() so a lost listener reconnects on the next wait. On PHP 8.4+ it opens the connection with PDO::connect() to get Pdo\Pgsql::getNotify(); on PHP 8.3 it uses the not-yet-deprecated pgsqlGetNotify().
  • A listener that cannot connect at startup is not fatal: the waiter logs a warning and polls. A failed reconnect does the same, and the subscription is retried on the next wait. The first wait after a successful (re)subscription forces one reservation, so a task committed while unsubscribed is not delayed by the fallback. A store failure still stops the worker.
  • A five second fallback (fallbackMs) covers a lost notification, a missing trigger or a reconnect. sliceMs (250 ms) bounds the blocking slice, so SIGTERM interrupts an idle wait within that slice. Worker::stop() wakes the waiter directly.
  • sleepMs is ignored while a waiter is present: the waiter owns its fallback. stopWhenEmpty disables the waiter entirely, since it exits instead of waiting.

LISTEN does not work through a transaction-pooling PgBouncer connection: give the waiter a direct or session-pooled connection to the same database. The trigger itself costs no measurable insert time, and an idle worker sends about 0.7 statements per second with the default fallback instead of one reservation per sleepMs. See bench/README.md to reproduce the measurements on your own topology.

Failures and retries

A task that throws is retried with its type's backoff until maxAttempts, then fails. Two exceptions change that:

use Kaly\Tasks\PermanentFailure;
use Kaly\Tasks\RetryLater;

public function __invoke(SmsGateway $gateway): void
{
    try {
        $gateway->send($this->deliveryId);
    } catch (InvalidNumber $e) {
        throw new PermanentFailure($e->getMessage(), previous: $e);
    } catch (RateLimited $e) {
        throw new RetryLater($e->retryAfterSeconds, $e->getMessage(), $e);
    }
}
  • PermanentFailure fails the task at once, whatever attempts remain: retrying invalid data only wastes attempts.
  • RetryLater delays the next attempt by the given seconds, measured with the store clock. The delay replaces the backoff and is not capped by maxDelay, but the attempt still counts: once maxAttempts is reached the task fails, so an API answering 429 forever cannot keep a task alive. A delay outside 0–2147483647 is rejected when the exception is built; convert a Retry-After date to seconds yourself.
  • Only the exception leaving the task counts: previous exceptions are not inspected.
  • They classify execution failures. Thrown by the constructor, while the task is decoded, any exception fails the task at once.
  • Throw them from the task or its adapters: domain code does not need to know about the queue.

Wrapping execution

One optional wrapper runs around each task invocation, to set up and clean a log context, a trace span, an error tracker scope or a tenant:

use Closure;
use Kaly\Tasks\TaskRun;

$worker = new Worker($store, $registry, $injector->invoke(...), $logger,
    around: static function (TaskRun $run, Closure $next) use ($logContext): void {
        $logContext->push(['task_id' => $run->id, 'task' => $run->name, 'attempt' => $run->attempt]);
        try {
            $next();
        } finally {
            $logContext->pop();
        }
    },
);

TaskRun carries the stored id, the registered name, the queue, the attempt (from 1), maxAttempts and the decoded task. It does not expose the owner token.

  • Call $next() exactly once and let its exceptions through. A wrapper that skips the task, or calls it twice, fails the attempt with a LogicException and the retry policy applies. PermanentFailure and RetryLater keep their meaning through the wrapper.
  • Any exception leaving the wrapper is a failure of the task: the worker cannot tell the wrapper's errors from the task's. If a span export fails after the task sent an email, the task runs again and sends it again. Instrumentation must swallow its own errors, and cleanup in finally must not throw, or it replaces the task's exception and its classification.
  • When cleanup cannot restore a clean state, call $worker->stop(): the supervisor starts a fresh process instead of leaking state into the next task.
  • It wraps the invocation only, under the task timeout. Reservation, decoding, settlement and lost leases happen outside it and are reported through the worker logger: the wrapper alone does not observe everything.
  • It is not a transaction boundary; a task opens its own transactions. A tenant context does not replace the authorization checks of the use case.
  • There is a single wrapper, not a middleware stack: compose concerns inside it.

Going to production

Retention

Purging is part of the setup, not optional maintenance. Without it the table grows and every deduplication key stays active forever. Choose a retention explicitly and schedule it:

// bin/tasks-purge.php, daily from cron or a systemd timer
$store->purge(
    olderThanSeconds: 7 * 86400,
    failedOlderThanSeconds: null, // keep failed tasks until reviewed
);
  • Retention is the deduplication window. It counts from the moment a task finished, not from its dispatch, plus the time until the next purge runs.
  • Pending and running tasks always keep their key: a task scheduled months ahead holds it until it finishes and is purged.
  • Purging failed tasks is a separate decision. Keep them while someone reviews failed(); pass failedOlderThanSeconds only when failures are monitored elsewhere, for example by alerting on stats()->failed, so errors are not deleted unseen.

Long tasks and timeouts

Order the limits with a margin at each step: external call timeouts, then the worker timeout, then the lease.

  • Give every external operation its own timeout: SQL statements, HTTP, SMTP. PHP runs the SIGALRM handler only when the engine regains control, so a call blocked inside an extension (a long SQL query, curl without a timeout) delays the hard timeout until it returns.

  • Leases are not renewed while a task runs. For long tasks with a predictable duration, use a dedicated queue served by its own worker with a longer timeout and lease:

    // bin/worker-exports.php
    $worker->run(new WorkerOptions(queues: ['exports'], lease: 3900, timeout: 3600));
  • An expired lease does not stop a running task: see Guarantees for when a late settlement still applies.

Deploying task changes

Stored payloads are a contract in both directions. New code reads payloads stored by the previous version, and during a rolling deploy previous workers read payloads from new producers. Decoding is strict: a payload with a key the worker does not know fails for good, without retry.

  • Adding an optional parameter: deploy the workers first, then the producers.
  • Renaming, retyping or removing a parameter, or an enum case: register the new shape under a new name, deploy workers that know both names before any producer dispatches the new one, and keep the old name until its tasks are drained.
  • Drained includes tasks scheduled for later, retries waiting for their delay, future steps stored in continuations, and failed tasks you may still retryFailed(). A continuation's queue and payload were encoded at submission; changing a registry entry does not rewrite stored steps.
  • When workers and producers cannot be deployed in order, isolate the versions in separate queues: new producers dispatch to a queue only new workers poll.

Unknown keys are rejected on purpose: silently dropping data would be worse than a visible failure. A task failed this way can be retried with retryFailed() once compatible workers run.

Maintenance

$store->failed(limit: 50);        // inspect failed tasks
$store->deleteFailed($id);        // delete a failed task and free its deduplication key
$store->retryFailed($id);         // run a failed task again, with fresh attempts
$store->purge(7 * 24 * 3600, 30 * 24 * 3600); // delete done tasks after a week, failed ones after a month

failed() returns rows with id, queue, name, payload, attempts, error, created_at and finished_at. Both dates are Unix timestamps in whole seconds. retryFailed() preserves the previous error until the task succeeds or another failure replaces it.

Done and failed tasks are kept until purged: their deduplication keys stay active for the retention period. Without the second argument, failed tasks are kept until you retry or delete them. Schedule the purge as part of the setup: see Retention.

$stats = $store->stats();           // whole table
$mailStats = $store->stats('mail'); // one queue

$stats->ready;              // pending, due now
$stats->scheduled;          // pending, due later, retries included
$stats->running;            // reserved, expired leases included
$stats->failed;             // failed for good
$stats->earliestPendingAt;  // ?DateTimeImmutable, UTC: oldest pending availability

Each call uses one aggregate SELECT on the writer. Its five values share the statement's view under the connection's isolation rules; they may be stale as soon as it returns, and separate calls do not share a snapshot. Availability comparisons use the database clock. earliestPendingAt is floored to whole UTC seconds, or null without pending tasks. When work is ready, this date is in the past or now and shows how long the oldest pending work has been waiting. stats(null) covers the whole table; an empty queue name or one containing NUL bytes is rejected.

Statistics use the existing status indexes without a schema change. The global minimum may scan pending entries across queues; the cost grows with pending work, even though completed tasks can be excluded. A queue filter allows an indexed lookup for its oldest pending availability. Measure against your active queue size before polling frequently. These statistics support application dashboards and supervision; they do not provide history, durations, per-type metrics or a console command.

Tests

docker compose up -d   # PostgreSQL on port 55432, MySQL on port 53306
composer test

Every suite runs against all three stores. The SQLite tests use temporary files and always run; set KALY_TASKS_PGSQL_DSN to another database, or empty to skip the PostgreSQL tests. KALY_TASKS_MYSQL_DSN defaults to mysql:host=127.0.0.1;port=53306;dbname=kaly_tasks;user=kaly;password=kaly;charset=utf8mb4; set it empty to skip MySQL. The MySQL test engine reads the user/password fields from this test DSN and passes them to PDO separately. MySQL tests include the store contract through PDO, Doctrine and Cycle, worker concurrency, signals, transaction rollback, locked rows and stale owners.

To run only the local SQLite tests:

KALY_TASKS_PGSQL_DSN="" KALY_TASKS_MYSQL_DSN="" composer test

The default DSNs expect Docker on ports 55432 (PostgreSQL) and 53306 (MySQL). If a database is configured but unreachable, the tests fail rather than silently skipping it.

The PostgreSQL suite also covers the opt-in LISTEN/NOTIFY support: trigger semantics, schema install and drop, deferred wakeups, draining, reconnect and SIGTERM interrupting an idle wait. php bench/run.php reproduces the latency and reservation measurements; see bench/README.md.