
Priority queues for AI automation without starving background work
Design priority queues for AI automation that protect interactive work while guaranteeing progress for background jobs, tenants and recovery tasks.
Priority queues for AI automation should make urgent work start sooner without allowing background work to wait forever. That sounds like a simple sorting problem: put interactive requests before batch jobs and let workers take the most important item first. Under sustained load, that design quietly becomes a starvation machine.
AI workloads make the trade-off sharper. A user may be waiting for a model response, while the same worker pool also handles document enrichment, evaluations, retries, indexing and recovery. Some jobs take seconds; others occupy a browser or model connection for minutes. A strict “high first” rule can keep the interface responsive today by creating an invisible operational backlog for tomorrow.
I treat priority as one input to scheduling, not permission to ignore a class of work. A production policy needs four parts: a small number of service classes, bounded capacity for each class, aging or weighted fairness to guarantee progress, and deadlines that remove work after it stops being useful.
What priority means in an AI queue
Priority answers a narrow question: when more than one runnable job is waiting for the same capacity, which one should be considered first? It does not decide whether the job is still valid, how much capacity one tenant may consume or whether a long task should share workers with short tasks.
Those decisions belong to separate controls:
| Control | Question it answers | Typical signal |
|---|---|---|
| Priority | Which eligible job should start first? | Interactive, normal, background, recovery |
| Admission | Should this work enter the system? | Deadline, quota, cost and queue capacity |
| Concurrency | How much work may occupy a resource now? | Model, browser, database or tenant permits |
| Fairness | How is service shared during contention? | Weights, reservations or round-robin keys |
| Expiry | When is the result no longer worth starting? | Latest useful start time |
A useful scheduler composes these controls. It first rejects expired or unauthorized work. It then checks the relevant capacity pool. Among eligible jobs, it applies service-class priority and fairness. A model should not invent or override this policy from a prompt; deterministic application code should own it.
This extends the backpressure policy I described in what should wait, degrade or fail fast. Backpressure decides what the system promises when capacity is full. Priority decides which accepted promise receives the next available slot.
Why strict priority causes starvation
Strict priority always drains the highest non-empty queue before considering the next one. It is predictable and easy to explain. It is also unsafe when high-priority arrivals can equal or exceed available throughput.
Imagine eight workers. Interactive AI requests arrive fast enough to keep all eight busy. A nightly enrichment job is already waiting. Every time a worker finishes, another interactive request is present, so the scheduler never selects enrichment. The background queue can have stable depth if old jobs expire while new ones arrive, yet an individual job may never run.
That is starvation: a job remains eligible but receives no service because other classes continually overtake it. Adding more workers may hide the problem until the next traffic increase or provider slowdown. Raising the background priority moves the starvation boundary rather than removing it.
If a scheduler cannot state the maximum time an accepted class may wait, it does not provide a service guarantee. It provides hope.
Priority inversion is a related but different problem. A high-priority workflow can depend on a low-priority job, lock or shared resource. The scheduler keeps favoring the blocked high-priority work while the dependency needed to unblock it sits behind other jobs. Trace dependencies and propagate priority only where the relationship is real; blindly upgrading every child task lets ordinary workflows label their entire fan-out as urgent.
Define service classes, not arbitrary numbers
I prefer three or four named service classes. Twenty numeric levels create false precision and make it easy for every team to choose “almost critical.” Names force a business definition.
| Class | Examples | Target behavior | Promotion rule |
|---|---|---|---|
| Interactive | User-blocking inference or tool call | Low queue wait, bounded execution | Never automatic |
| Normal | Accepted asynchronous workflow | Predictable completion window | Age into protected share |
| Background | Indexing, enrichment and evaluation | Guaranteed progress without latency promise | Age or consume reserved capacity |
| Recovery | Reconciliation and compensating work | Protected path to restore correctness | Explicit incident policy |
Recovery deserves attention. A failed payment reconciliation or ambiguous tool outcome may be operationally more important than a new interactive request, even though it is not user-facing. Putting recovery in the background queue can leave the system incorrect while it continues accepting more work. Give it an explicit class and limit, not an unlimited “critical” bypass.
Store the reason for priority alongside the value: service_class=interactive, priority_reason=user_waiting and latest_start_at=.... The reason makes audits and misuse detection possible. A naked integer such as priority=97 says nothing about the promise the system is trying to keep.
Four ways to guarantee background progress
There is no single scheduling algorithm for every workload. The important property is explicit progress under sustained contention. Four patterns are practical for AI automation.
1. Reserved capacity
Reserve part of the worker or resource pool for background work. For example, six model permits may be shared while two are available to background and recovery classes. When background is empty, the implementation may lend those permits to interactive work, but it must reclaim them as leases finish.
Reservations provide the clearest minimum guarantee. They can also leave capacity underused if implemented as rigid, permanently isolated workers. Borrowing unused capacity preserves utilization while keeping a floor during contention.
2. Weighted round-robin
Give each class a service weight, such as eight interactive jobs, three normal jobs and one background job per scheduling cycle. The ratio expresses preference without requiring lower classes to wait for higher queues to become empty.
Count resource cost when job sizes differ. Dispatching eight ten-second jobs and one ten-minute job is not an 8:1 capacity split. A deficit-based scheduler can spend estimated cost units rather than job counts, then correct estimates with observed duration or token usage.
3. Aging
Increase effective priority as waiting time grows. One simple model is:
effective_priority = base_priority + floor(wait_seconds / aging_interval)
Aging is useful when separate reservations are expensive or queues are bursty. Cap promotion so a large batch does not suddenly become interactive. Aging should earn a chance to run, not erase the original latency and risk class.
4. Deadline-aware scheduling
A deadline says when work must start or finish to remain valuable. A job approaching a real deadline can move ahead of less urgent work. A job past its latest useful start should expire instead of consuming model tokens to produce a result nobody needs.
Deadlines must come from product semantics, not from clients choosing an arbitrary timestamp. Otherwise every caller submits an immediate deadline and recreates one highest-priority queue.
These patterns can be combined. A small background reservation provides a hard floor, weighted scheduling handles normal contention, aging protects unusually old jobs and expiry removes stale work. Keep the combination understandable enough that operators can predict it during an incident.
Separate job priority from tenant fairness
Priority compares types of work. Fairness compares who is consuming service. Mixing them lets a large tenant dominate every class or lets a premium tenant turn all work into “urgent.”
Use two dimensions:
- service class for business latency and recovery needs;
- fairness key for tenant, team, customer or workflow owner.
Temporal's task-queue documentation uses the same separation: priority selects important tasks first, while fairness keys and weights distribute work among groups. The exact platform is less important than preserving both dimensions.
Within a class, rotate between tenant keys with a bounded burst. If Tenant A has 10,000 jobs and Tenant B has two, B should not wait behind A's entire backlog. Per-tenant concurrency limits add another boundary: fair dispatch is not enough if one tenant's long jobs already occupy every worker.
Do not confuse fairness with equality. A paid service tier or safety-critical workflow may receive a larger weight. Fairness means the allocation is deliberate, bounded and observable—and that a smaller weight is not zero.
Account for job duration and resource type
Queue order controls starts, not preemption. Once a worker begins a 20-minute browser task, a newly arrived interactive task cannot use that worker unless the running task supports safe checkpointing and preemption. Too many long background jobs can therefore block urgent work even with perfect queue ordering.
I separate workloads along two axes:
- resource type: model calls, browsers, search, document conversion and database-heavy work use different capacity pools;
- duration class: short and long jobs should not share every worker if long jobs create head-of-line blocking.
This does not require a queue for every combination. Start with the bottlenecks visible in production. A browser pool might reserve one slot for interactive use, while model calls use weighted permits based on estimated tokens. A document conversion queue may need only FIFO plus expiry.
Concurrency remains a separate safeguard. As explained in AI workflow concurrency limits, rate limits cannot bound in-flight occupancy. The scheduler chooses the next job; permits decide whether the required resource can safely accept it.
Implement the policy with Laravel queues
Laravel workers can poll multiple named queues in order, for example php artisan queue:work --queue=interactive,normal,background. That is strict priority: the worker checks the first queue before the next. It is useful for preference, but by itself it provides no background progress guarantee.
A simple deployment can combine ordered polling with separate worker groups:
[program:ai-shared-workers]
command=php artisan queue:work redis --queue=interactive,normal,background
numprocs=6
[program:ai-background-floor]
command=php artisan queue:work redis --queue=recovery,background,normal
numprocs=2
The shared pool favors interactive work. The second group guarantees that recovery and background jobs continue. In Horizon, define separate supervisors with distinct queue lists and balancing rules, then monitor wait time by queue. Worker counts are only the outer layer; acquire model, browser and tenant permits inside the job before the scarce operation.
Jobs should carry scheduling metadata in durable application state rather than only in a transient queue payload:
final readonly class SchedulingPolicy
{
public function decide(AgentRun $run, CapacitySnapshot $capacity): Decision
{
if ($run->latest_start_at->isPast()) {
return Decision::expire('latest_useful_start_passed');
}
if (! $capacity->tenantMayRun($run->tenant_id)) {
return Decision::defer(random_int(5, 15), 'tenant_limit');
}
return Decision::dispatch(
queue: $run->service_class->queueName(),
fairnessKey: $run->tenant_id,
);
}
}
Deferral because capacity is unavailable is not a failed model attempt. Track dispatches, capacity deferrals, provider attempts and business retries independently. Otherwise a job can exhaust the retry budget while behaving correctly under load.
If the scheduling decision and durable run state must change together, use the same transactional discipline as other workflow transitions. A transactional outbox can record the state change and dispatch intent atomically so a crash does not lose or duplicate the transition.
Measure starvation directly
Queue depth is not enough. A queue can remain at 100 items while the same oldest job waits all day. Measure age and service share for every class and fairness key.
- oldest eligible job age by class and tenant;
- queue-wait percentiles, especially p95 and p99;
- dispatch share and occupied-capacity share by class;
- deadline misses and expirations with reason codes;
- promotion count from aging or incident overrides;
- borrowed versus reserved capacity over time;
- completion rate, not only start rate, for long work;
- priority inversion time when urgent work waits on lower-class dependencies.
Define an SLO for background progress even if the product makes no user-facing latency promise. “During sustained load, at least 10% of model capacity serves accepted background work and no eligible background job waits more than 30 minutes” is testable. “Background runs when possible” is not.
Emit scheduling events such as job_admitted, job_deferred, priority_aged, capacity_borrowed, job_started and job_expired. Event history lets an operator explain why one run overtook another, which is more useful than a dashboard that only shows the current queue size. This follows the event-first approach in AI agent observability.
Test the scheduler under hostile load
Priority behavior is easiest to validate when the system is overloaded. A quiet staging environment proves almost nothing because every queue drains immediately.
- Saturate the interactive class. Keep arrivals above available throughput for longer than the intended background wait bound.
- Submit background and recovery jobs. Verify they receive the configured share and do not wait for the interactive queue to empty.
- Add a noisy tenant. Confirm a small tenant still receives service within its bound.
- Mix durations. Run short model calls beside long browser tasks and look for occupied-capacity starvation.
- Slow a provider. Verify concurrency limits and backpressure prevent queue preference from becoming overload.
- Cross a deadline. Confirm stale work expires before acquiring expensive capacity.
- Restart workers. Ensure reservations, leases and aged priority recover from durable state.
Assert invariants instead of a single exact order. Useful invariants include “interactive p95 queue wait stays below the target,” “every eligible class receives service in each fairness window,” “one tenant cannot occupy more than its limit” and “expired jobs never call the model.” Exact interleaving will vary with job duration and worker timing.
Production checklist
- Use three to four named service classes with written admission criteria.
- Store priority reason, fairness key and latest useful start in durable state.
- Guarantee lower-class progress through reservations, weights, aging or a combination.
- Protect recovery work explicitly instead of treating it as ordinary background traffic.
- Apply per-resource and per-tenant concurrency limits after scheduling.
- Separate long and short jobs where non-preemptive execution causes blocking.
- Expire stale jobs before model or tool capacity is acquired.
- Measure oldest-job age, service share, deadline misses and completion rate per class.
- Load-test continuous high-priority arrivals and noisy tenants.
- Require explicit, audited overrides for emergency priority.
Priority queues are valuable because not all work has the same latency requirement. They become reliable only when lower priority still means “later within a defined bound,” not “perhaps never.” For AI automation, that requires scheduling policy outside the model, protected capacity at scarce resources and evidence that every accepted class continues to make progress.
Sources and methodology: sources checked November 20, 2026: Temporal documentation and product guidance on task-queue priority and fairness, and Laravel 13.x documentation on queue workers, queue priority and Horizon. The service-class model, progress guarantees, Laravel deployment example and testing invariants are original synthesis based on production-oriented PHP, queue and AI-agent engineering. Exact weights and wait bounds must be validated against each workload. This article was prepared with AI assistance and reviewed for technical accuracy and practical usefulness. Cover: server-room photograph by akela999 on Pixabay.
