Skip to content

[Feature]: Background job queue for long-running tasks #3833

Description

@objecttothis

Overview

There are times in OSPOS where it would be helpful for a task to run asynchronously to prevent timeout and out-of-memory errors. One such moment is in processing large CSV import files. Once Third Party integrations are implemented, it's likely that many would benefit from running asynchronously.

The implementation uses CodeIgniter Queue (https://queue.codeigniter.com/) as the job execution backend and CodeIgniter Tasks (https://tasks.codeigniter.com/) for scheduled triggering. Core CSV imports (Items, Customers) are the initial use case; the plugin system is designed around the same infrastructure from the start.


Phase 1: Job Manager — Task Processing Design

Operating Modes

Configured in Config/Jobs.php via $mode:

Mode Use Case Trigger
auto VPS/dedicated with cron or supervisor php spark tasks:run via cron/Task Scheduler
web Shared hosting, no cron access CI4 After Filter on page requests
manual All environments Admin button in config panel

Default $mode is web — works on all environments including Docker without any additional setup.

Mode: auto

Uses the CodeIgniter Tasks library. A single cron entry (Linux) or Task Scheduler entry (Windows) triggers processing:

cd /var/www/ospos && php spark tasks:run >> /dev/null 2>&1

Alternatively: php spark queue:work kept alive via supervisor or systemd.

Mode: web (No Cron)

Uses a CI4 After Filter attached to page requests. Jobs are processed after the response is delivered — zero UX impact.

Flow:

  1. After filter fires on each page request
  2. Throttle check: skip if processed within the last N seconds (cached flag)
  3. Pending check: SELECT 1 FROM jobs WHERE status='pending' LIMIT 1
  4. If pending jobs exist:
    • Primary: call fastcgi_finish_request() — sends response to browser, PHP continues running and processes jobs up to $webMaxSeconds
    • Fallback: fire a non-blocking async self-request to an internal /jobs/process-async endpoint (fire-and-forget curl, timeout = 1s)

Note: $webMaxSeconds limits starting new jobs (especially API tasks), not how long they can run. This allows API calls to return values without being cut off.

Key Config Options:

public string $mode            = 'web';
public int    $webMaxSeconds   = 5;    // max time for starting new jobs per trigger
public int    $throttleSeconds = 10;   // min seconds between processing runs
public int    $webProbability  = 100;  // % of requests that check for jobs (0–100)

Notes:

  • fastcgi_finish_request() works on PHP-FPM (essentially all modern shared hosting)
  • Throttle uses CI4 cache: cache()->save('jobs_last_run', true, $throttleSeconds)
  • Pending check must be a cheap single-row query — no aggregates
  • Processor loop must track wall clock via microtime() and respect $webMaxSeconds

Mode: manual

Admin panel button in the Jobs config section. Calls a controller action that runs the processor synchronously. Always available regardless of $mode setting. Useful for debugging and on-demand processing.

Job Processing Logic (shared across all modes)

  1. Fetch next pending job: SELECT ... WHERE status='pending' ORDER BY created_at ASC LIMIT 1
  2. Mark job as processing (prevent duplicate pickup)
  3. Dispatch to the appropriate job handler class
  4. On success: mark completed, store result/timestamp
  5. On failure: increment attempts, mark failed if max attempts reached; otherwise return to pending for retry (with updated available_at for retry delay)
  6. Loop until queue empty or time limit reached (web mode only)

Libraries Used

Library Purpose
CI4 Tasks Cron scheduling (auto mode)
CI4 Queue Optional: worker/daemon model for auto mode
CI4 After Filter Request hook for web mode
CI4 Cache Throttle flag for web mode

Note: CI4 Queue is optional in Phase 1. If using auto mode with Tasks only, Queue is not required — the Task can call the processor directly. Queue adds value when parallel workers or retry infrastructure is needed.


Phase 2: CI4 Queue Integration

Overview

Integrate CodeIgniter Queue as the job execution backend. Phase 1's trigger mechanism (auto/web/manual) remains unchanged — Phase 2 replaces what happens when the trigger fires.

Queue Table Schema

CI4 Queue manages its own queue_jobs and queue_failed_jobs tables.

Column Type Notes
id int Primary key
queue string Queue name
payload text Serialized job data
priority string high, normal, low
status enum pending, reserved, done, failed
attempts int Retry counter
available_at int Unix timestamp for delayed execution
created_at datetime

Completed jobs are deleted on completion — they do not accumulate. Failed jobs move to queue_failed_jobs.

Queue Naming Convention

Queue Purpose
default Core miscellaneous jobs
imports CSV / bulk import jobs
api External API calls
plugin.{plugin_id} One queue per plugin, keyed by getPluginId()

Separate queues per plugin provide structural blocking prevention — a slow plugin job cannot stall core queues or another plugin's queue.

Plugin Queue Discovery

No separate queue registration is needed. The worker derives plugin queues at startup by querying the existing plugin config table:

SELECT DISTINCT plugin_id FROM ospos_plugin_config
WHERE key = 'installed' AND value = 1

Queue name is derived as 'plugin.' . $plugin_id. A getPluginQueues() service method owns this query and returns the full list of queue names for the worker to listen on.

Job Priority

CI4 Queue supports priority via a fluent setter:

service('queue')->setPriority('high')->push('imports', ItemImportJob::class, $data);

One queue per plugin is the enforced convention. Priority separation within a plugin is handled via setPriority() — not separate queues.

Priority convention for all job authors:

  • normal — default for all jobs
  • high — user-facing or time-sensitive work
  • low — bulk background processing, large imports

pushJob() Wrapper

Plugin authors never call CI4 Queue directly. BasePlugin provides a wrapper that enforces the naming convention and provides separation from the underlying library:

protected function pushJob(string $jobClass, array $data, string $priority = 'normal'): bool
{
    return service('queue')
        ->setPriority($priority)
        ->push('plugin.' . $this->getPluginId(), $jobClass, $data);
}

Job Class Location

  • Core jobs: app/Jobs/
  • Plugin jobs: app/Plugins/{PluginName}/Jobs/ — consistent with existing plugin directory structure

BasePluginJob

All plugin job classes extend BasePluginJob, which enforces the plugin-enabled check before executing. RESERVED jobs (already in-flight when a plugin is disabled) are allowed to complete and discarded cleanly without landing in queue_failed_jobs:

abstract class BasePluginJob implements JobInterface
{
    abstract protected function pluginId(): string; // matches getPluginId()

    public function process(array $data): bool
    {
        $plugin = service('pluginManager')->getPlugin($this->pluginId());

        if ($plugin === null || ! $plugin->isEnabled()) {
            return true; // discard silently — do not send to failed_jobs
        }

        return $this->handle($data);
    }

    abstract protected function handle(array $data): bool;
}

Plugin Lifecycle Integration

Queue registration hooks into the existing install() / uninstall() methods:

public function install(): bool
{
    service('jobManager')->registerPluginQueue($this->getPluginId());
    // ...
}

public function uninstall(): bool
{
    service('jobManager')->deregisterPluginQueue($this->getPluginId());
    // Also purges pending jobs for this plugin from the queue
}

Event System Integration

Plugins push jobs to their queue inside the existing registerEvents() method. No new API required. Thin-payload philosophy is preserved — jobs receive only an ID and query what they need at execution time:

public function registerEvents(): void
{
    Events::on('item_saved', function(int $itemId) {
        service('queue')->push(
            'plugin.' . $this->getPluginId(),
            SyncJob::class,
            ['item_id' => $itemId]
        );
    });
}

Periodic Plugin Jobs (registerSchedule())

PluginInterface gains one new method: registerSchedule(). This is called by PluginManager during Tasks setup, giving plugins a clean way to declare time-based jobs without requiring core changes per plugin:

// Added to PluginInterface
public function registerSchedule(TasksScheduler $scheduler): void;

// Default no-op in BasePlugin — plugins override only if needed
public function registerSchedule(TasksScheduler $scheduler): void {}

// Example plugin implementation
public function registerSchedule(TasksScheduler $scheduler): void
{
    $scheduler->command('queue:work plugin.' . $this->getPluginId())
              ->hourly();
}

Note: This is a breaking change for any plugin that does not extend BasePlugin — note in the upgrade guide.

Phase 1 Mode Compatibility

The worker must exit after processing to remain compatible with web and manual modes. Use --stop-when-empty or --max-jobs:

Mode Worker invocation
auto (cron) spark queue:work default,imports,api,plugin.* — or supervisor keeps it alive permanently
web After filter → fastcgi_finish_request() → worker with --stop-when-empty
manual Admin button → worker with --max-jobs=50 or a time-bounded loop

Phase 2 Design Decisions Summary

Decision Choice Reason
Table Single CI Queue-managed table Library owns schema; queue name provides isolation
Plugin identity plugin.{getPluginId()} queue + class namespace No extra columns, queryable, human-readable
Blocking prevention Separate queue per plugin Structural, not conditional logic
Plugin-enabled check BasePluginJob guard via PluginManager Centralised; plugins cannot bypass it
Plugin queue registration install() / uninstall() Consistent with existing plugin lifecycle
Periodic plugin jobs registerSchedule() on PluginInterface Declarative, no core changes per plugin
Phase 1 compatibility --stop-when-empty / --max-jobs on worker Makes Queue work in all three modes

Phase 3: CSV Import Queue Integration & Admin UI

Import Flow

Before (synchronous): Upload CSV → parse row → save item → fire item_saved

After (queued): Upload CSV → parse rows → push one job per row → worker runs → job handler saves row → fires item_saved → last job fires import_completed

The upload controller fires no events. All events originate from the job handler where the actual data change occurs.

One Job Per Row

Each CSV row becomes an independent job on the imports queue:

$batchId   = uniqid('import_', true);
$totalRows = count($rows);
service('importBatch')->create($batchId, 'items', $totalRows);
foreach ($rows as $row) {
    service('queue')->push('imports', ItemImportJob::class, [
        'batch_id' => $batchId,
        'row'      => $row,
    ]);
}

Batch Tracking

With independent per-row jobs, no single job knows it is the last. A batch tracker resolves this with an atomic counter.

Table: ospos_import_batches

Column Type Notes
id string Generated batch UUID
type string items, customers, plugin.{slug}
total int Total rows pushed
completed int Rows successfully processed
failed int Rows failed after max retries
status enum pending, processing, completed, partial
created_at datetime
updated_at datetime

In the job handler, after saving the row, increment the batch counter atomically. Only one job will ever see isComplete() return true, so import_completed fires exactly once:

// ItemImportJob::handle()
$this->itemModel->save($data['row']);
Events::trigger('item_saved', $itemId);
$batch = service('importBatch')->increment($data['batch_id']);
if ($batch->isComplete()) {
    Events::trigger('import_completed', $data['batch_id']);
}

Events

Event Fired by When
item_saved Job handler Each row, after DB save
customer_saved Job handler Each row, after DB save
import_completed Job handler (last row) When completed + failed = total
import_row_failed Job handler When a row fails after max retries

Plugins subscribe via registerEvents() as normal. The event contract is identical to synchronous imports from a plugin's perspective.

Retention Policy

Configured in Config/Jobs.php:

public int  $retentionDays       = 7;    // completed jobs; 0 = keep until manual purge
public int  $failedRetentionDays = 30;   // failed jobs kept longer for debugging
public bool $autoPurge           = true; // purge runs at end of each worker cycle

Auto-purge runs at the end of each worker execution — no separate scheduled task needed. Works in all three modes (auto/web/manual). Batch records are purged when their associated jobs are purged.

Retry Configuration

Retry limit and retry delay are both configurable:

  • Retry delay is implemented by updating available_at to the desired retry time
  • Retry limit is configurable app-wide and also overridable per queue at the plugin framework level (plugin-level setting falls back to the core app limit)

Batch Management

Batch management must support pausing or deleting an entire batch's worth of tasks even if tasks are mid-run.

Admin UI: Job Viewer

Displays the CI Queue jobs table.

Columns: Job ID · Queue · Job class · Status · Attempts · Created · Updated

Filters: Queue name · Status · Date range

Tabs: Active Jobs (queue_jobs) · Paused Jobs (ospos_queue_paused_jobs)

Actions on Active Jobs: Pause individual job · Retry failed job · Delete job · Purge completed jobs (confirm dialog) · Purge failed jobs (confirm dialog)

Actions on Paused Jobs: Unpause individual job · Unpause all for a queue · Delete job

Info row: Current retention policy with link to config.

Admin UI: Batch Viewer

Displays ospos_import_batches with progress per import.

Columns: Batch ID · Type · Total · Completed · Failed · Status · Created

Progress indicator: completed / total with visual bar

Filters: Type · Status · Date range

Actions: Drill down to individual jobs for that batch · Pause/delete entire batch · Purge completed batch and its jobs

Plugin Imports

Plugins follow the same pattern using their own queue and batch type:

service('importBatch')->create($batchId, 'plugin.inventory_pro', $totalRows);
service('queue')->push('plugin.inventory_pro', MyPluginImportJob::class, [
    'batch_id' => $batchId,
    'row'      => $row,
]);

Plugin job handlers extend BasePluginJob, which checks isEnabled() before executing. If the plugin is disabled after jobs are queued, jobs are discarded silently and do not go to failed_jobs.


Plugin Queue Management: Pause, Resume, and Uninstall

Paused Jobs Table

ospos_queue_paused_jobs mirrors the CI Queue queue_jobs schema exactly so rows move back without transformation:

Column Notes
id Original job id
queue Queue name
payload Unchanged
priority Unchanged
attempts Unchanged
available_at Unchanged
created_at Unchanged
paused_at Timestamp when the job was paused
paused_by plugin_disabled or manual

Operations

Pause (plugin disabled or manual UI action)

Move all pending jobs for the queue to the paused table. Jobs with status reserved (currently in-flight) are left alone and allowed to complete.

INSERT INTO ospos_queue_paused_jobs
    SELECT *, NOW(), 'plugin_disabled'
    FROM queue_jobs
    WHERE queue = ? AND status = 'pending';

DELETE FROM queue_jobs
    WHERE queue = ? AND status = 'pending';

Unpause (plugin enabled or manual UI action)

INSERT INTO queue_jobs
    SELECT id, queue, payload, priority, attempts, available_at, created_at
    FROM ospos_queue_paused_jobs
    WHERE queue = ?;

DELETE FROM ospos_queue_paused_jobs WHERE queue = ?;

Uninstall

Delete from both tables immediately. No restore.

DELETE FROM queue_jobs WHERE queue = ?;
DELETE FROM ospos_queue_paused_jobs WHERE queue = ?;

paused_by Drives Unpause Behaviour

Value Unpaused by
plugin_disabled Automatically when the plugin is re-enabled
manual Manual admin action only — plugin state changes do not unpause these

Plugin Lifecycle Summary

Plugin action pending jobs reserved jobs
Disable Moved to paused table (plugin_disabled) Left to complete
Enable Restored to queue N/A
Uninstall Deleted from both tables Left to complete, result discarded by BasePluginJob guard

Rate Limiting & Batching (Plugin API Jobs)

Plugins must be able to specify a rateLimit configuration. Many APIs have specific rate limits. The implementation must be flexible and support multiple limit dimensions simultaneously. For example:

  • 2000 API calls per day
  • Maximum batch size per call

Job Batching

When one job is called, the job handler checks the current batch size and combines multiple pending jobs of the same type into a single API call if the batch size threshold is not met. This will significantly speed up jobs that can be batched into a single API call, rather than one job = one API call.

Plugins must be able to declare:

  1. The maximum batch size for a given job class
  2. Rate limit rules (calls per time window)

Docker Considerations

Cron Does Not Run in Docker by Default

Docker containers are single-process by design. The auto mode cron approach does not work out of the box in a containerised OSPOS install without extra configuration. This makes web mode the correct default for Docker users — fastcgi_finish_request() works in PHP-FPM containers (which the OSPOS Docker image uses) with zero extra setup.

auto Mode Options for Docker Users

Option 1: Separate worker container (recommended)

Add a second service to docker-compose.yml targeting the same database:

worker:
  image: opensourcepos
  command: php spark queue:work imports,default --stop-when-empty
  depends_on:
    - db
  restart: unless-stopped

Clean separation of concerns and the proper Docker idiom.

Option 2: Supervisor inside the container

Add supervisor to the Docker image and configure it to run both the web server and queue:work. Works but violates the one-process-per-container principle. Acceptable for simple single-container deployments.

Option 3: Cron sidecar container

A minimal sidecar container that runs spark tasks:run every minute via cron, sharing the same network and database. Uncommon but valid.

Risk: fastcgi_finish_request() in Docker

Some Docker PHP-FPM configurations buffer output in ways that delay fastcgi_finish_request() from flushing to the client before continuing execution. This must be tested explicitly in the OSPOS Docker image during Phase 1. If it does not flush as expected, the async self-request fallback becomes the primary path for Docker users.

Impact on Design

No structural changes to the job manager design are required, but the following must be addressed during implementation:

  • Default $mode in Config/Jobs.php should be web
  • The worker container approach should be documented as the recommended auto mode setup for Docker users
  • fastcgi_finish_request() behaviour must be verified in the OSPOS Docker image during Phase 1 testing

System Requirements

This feature requires:

  • PHP 8.1+
  • MySQL 8.0.1+ or MariaDB 10.6+ (CI4 Queue requirement)

Activity

  1. jekkos commented on Sep 25, 2023

    @jekkos
    Member

    Hi @objecttothis this one looks interesting: https://github.com/amphp/amp, it can be installed using composer but it does require PHP 8.1 minimum.

  2. jekkos commented on Sep 25, 2023

    @jekkos
    Member

    The CI thingy seems to be more focused on schedules and migjht not be directly usable for running background jobs?

  3. added this to the 4.0.0 milestone on Dec 12, 2023
  4. added a commit that references this issue on Feb 6, 2024
  5. added 2 commits that reference this issue on Jun 10, 2024
  6. self-assigned this
    on Mar 31, 2025
  7. jekkos commented on Mar 31, 2025

    @jekkos
    Member

    It seems you can even choose to back it with a regular db or Redis. I have seen that plenty of webapps use the latter to offload tasks or they use it as a cache.

    To me it sounds like the most logical option but it will make the application setup a more complex. Often you find that installation procedures do have some kind of non optimal working default. In our case that might just be the current situation. It will be fine for small CSV imports, they can just run in the foreground.

    Once you have a huge dataset then indeed then this needs to be offloaded. Then it's up to the user to decide that he has to upgrade his setup by configuring a job queue through DB or Redis. Or if we can just use this queue through the standard DB transparantly, then that would be even better.

  8. changed the title [-]Asynchronous task scheduler[/-] [+][Feature]: Background job queue for long-running tasks[/+] on Apr 1, 2026
  9. objecttothis commented on Sep 15, 2026

    @objecttothis
    MemberAuthor

    @jekkos I reworked all my comments together into an updated description which should be a much more cohesive design. Take a look when you get a chance and tell me if you think this is a good direction or if some modifications should be made. I chose the native CodeIgniter solutions of Tasks and Queue because it seemed to check the boxes off while also being native to the CodeIgniter framework. I chose database as the handler over redis, predis or rabbitmq because it would add the least extra setup. That said, I don't think it needs to be strongly coupled, so if someone wants to use one of the others down the road, a picker could be added to specify which handler to use for the queue. You expressed concern over those who can't use cron or task scheduler, so the design would implement alternatives which will still get the job done. If you feel strongly, we could potentially leave in a method to completely bypass scheduling for item and customer csv imports for those that don't want to use it at all.

  10. objecttothis commented on Sep 24, 2026

    @objecttothis
    MemberAuthor

    Things to add:

    • Job Queue manage_table view to show, edit, delete, search jobs in one or more queues a la items manage table.
    • Per Queue logging.
  11. objecttothis commented on Oct 2, 2026

    @objecttothis
    MemberAuthor

    Left to do on Phase 2a

    • Get live update of the table working for queue management view. Currently the page isn't refreshing. It should be refreshing only the rows which have changes similar to what happens when you delete a row. Before it was refreshing the whole table but we don't want that.
    • Add ability to filter jobs by status (failed, inprocess, paused, active) multiselect.
    • The Task Manager Task is set to run in the background every minute and it does, but there is a problem. If I set a job throttle of 5/second then this cadence is only kicked off once then the process shuts down and isn't started up until 1 minute later. I think we need to change our approach. Is it possible that the cron/task manager task is just responsible for starting the queue manager or restarting it if it stops, but for the queue manager just runs in the background and when it hits a throttle limit it sleeps rather than closes down?
  12. objecttothis commented on Nov 6, 2026

    @objecttothis
    MemberAuthor

    Claude Issue Checker Agent (cc @objecttothis)

    Investigated against current master.

    Status: Still present (not implemented) — this is a detailed design doc, milestone 4.0.0.

    A repo-wide search finds no app/Jobs/, Config/Jobs.php, queue_jobs/ospos_import_batches/ospos_queue_paused_jobs tables/migrations, and no codeigniter4/queue or codeigniter4/tasks packages in composer.json. CSV imports for Items and Customers (Items::postImportCsvFile(), Customers::postImportCsvFile()) still run entirely synchronously within the request/response cycle, with no job dispatch, batch tracking, or async processing mode (auto/web/manual) of any kind. This remains an open, unimplemented design proposal targeted at the 4.0.0 milestone, with no linked PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions