A Fair, Adaptive Task Processor for Java

Overview

A task processor should make it straightforward to accept work, queue it safely, and execute it efficiently across machines with different CPU and I/O capacity. This library provides a backend API for submitting and managing tasks, with priority-aware scheduling, fairness, adaptive polling, retries, and operational statistics.

Github: https://github.com/gitorko/project18

What it provides

The library exposes a REST API for submitting tasks and inspecting their state. Tasks are persisted in PostgreSQL, so accepted work survives process restarts. Workers claim work from the database and execute it asynchronously.

The design targets both short and long running tasks. Worker concurrency and polling settings can be tuned for the hardware and workload, while task state and aggregate metrics help operators understand what is happening.

Priority with fairness

Priority helps urgent tasks move ahead of ordinary work. A strict priority queue, however, can leave low-priority tasks waiting indefinitely when high-priority traffic is constant.

The processor combines priority ordering with fairness controls so that lower-priority work continues to make progress. This gives callers a way to express importance without making the queue permanently unfair.

Adaptive polling

Workers poll for available tasks rather than continuously spinning. The polling interval adapts to queue activity: workers can check more frequently when work is available and back off when the queue is idle. This reduces unnecessary database traffic while keeping task pickup responsive under load.

Running on different hardware

A worker pool that is effective on a large server can overwhelm a small instance. The processor allows concurrency and polling to be configured to match available resources and the task mix.

CPU-bound work generally benefits from concurrency close to the number of available cores. I/O-bound work can use more concurrent workers because tasks spend time waiting. Operators can tune the worker capacity and observe queue depth, active work, and execution duration to find a suitable setting for each deployment.

Retry on failure

Transient failures should not always mean lost work. The processor supports retrying failed tasks, with attempts tracked so that work can be retried according to the configured policy. Retry behavior is useful for temporary downstream errors and other recoverable failures.

Retries should be configured with care: tasks with external side effects should be idempotent, or otherwise guard against the same operation being performed more than once.

Task and queue statistics

The API provides operational information about task execution and queue state, including:

  • How many tasks are running and waiting.
  • Task counts grouped by type and status.
  • Average execution time for completed tasks.
  • Queue backlog and an estimated time to completion based on observed processing rates.

These statistics give applications and operators a view into throughput and backlog without requiring a separate UI.

How it compares with JobRunr

JobRunr is a mature Java background-job framework with persistent storage, background servers, retries, and a dashboard. This library focuses on a smaller backend task-processing API and does not include a UI. It emphasizes priority and fair queue behavior, adaptive polling, and queue/runtime statistics.

CapabilityThis task processorJobRunr OSS
Java background executionYesYes
Persistent storagePostgreSQLMultiple supported storage providers
Retry on failureSupportedSupported, with automatic retries and backoff
Priority and fairnessPriority-aware scheduling with fairness controlsPriority queues are a Pro feature
Adaptive pollingAdaptive worker pollingBackground server configuration and worker management
Queue and runtime statisticsTask counts, averages, backlog ETAMetrics and job/server monitoring
Built-in UINoDashboard available
Scheduled jobsNot a focusSupported

JobRunr offers a broader feature set, including scheduling and a dashboard, as well as a choice of persistence backends. Its OSS edition is a strong option when those capabilities are important. This library is aimed at applications that want an embeddable backend task API with explicit control over queueing, fairness, and worker behavior.

Current scope

This library is focused on accepting, queuing, and executing tasks. Scheduled job promotion is not currently part of the implementation, and runtime statistics and backlog estimates are based on the processor's observed state and execution history. Deployments should tune worker capacity for their task types and hardware.

Setup

See the project README for build and configuration instructions:

  1# Task Processor
  2
  3A distributed task queue implementation using Spring Boot and PostgreSQL. Similar to JobRunr but without license restrictions.
  4
  5## Features
  6
  7- **Distributed Queue**: Multiple pods/nodes can process tasks without duplicates using PostgreSQL's `SELECT ... FOR UPDATE SKIP LOCKED`
  8- **Configurable Thread Pool**: Dynamically adjust processing capacity at runtime
  9- **Adaptive Polling**: Reduces DB load when queue is empty
 10- **Heartbeat Mechanism**: Detects and recovers stuck tasks from crashed workers
 11- **Retry Support**: Configurable retry attempts for failed tasks
 12- **Priority Queue**: Higher priority tasks are processed first
 13- **Scheduled Tasks**: Support for delayed task execution
 14- **Metrics**: Spring Actuator metrics for monitoring processing rate and performance
 15- **REST API**: Full API for task management and configuration
 16
 17## Quick Start
 18
 19### Prerequisites
 20
 21- Java 17+
 22- PostgreSQL 12+
 23- Gradle 8+
 24
 25### Setup
 26
 271. Start PostgreSQL (using Docker Compose):
 28
 29```bash
 30docker-compose up -d postgres
 31```
 32
 332. Build and run the application:
 34
 35```bash
 36./gradlew bootRun
 37```
 38
 393. The application will be available at `http://localhost:8080`
 40
 41## API Reference
 42
 43### Task Management
 44
 45#### Create a Task
 46
 47```bash
 48POST /api/v1/tasks
 49Content-Type: application/json
 50
 51{
 52  "taskType": "sample",
 53  "payload": "{\"key\": \"value\"}",
 54  "priority": 0,
 55  "maxAttempts": 3
 56}
 57```
 58
 59#### Create Tasks in Bulk
 60
 61```bash
 62POST /api/v1/tasks/bulk
 63Content-Type: application/json
 64
 65{
 66  "tasks": [
 67    {"taskType": "sample", "payload": "{\"id\": 1}"},
 68    {"taskType": "sample", "payload": "{\"id\": 2}"}
 69  ]
 70}
 71```
 72
 73#### Get Task by ID
 74
 75```bash
 76GET /api/v1/tasks/{taskId}
 77```
 78
 79#### Get Tasks (Paginated)
 80
 81```bash
 82GET /api/v1/tasks?status=PENDING&page=0&size=20
 83```
 84
 85#### Get Task Summary
 86
 87```bash
 88GET /api/v1/tasks/summary
 89```
 90
 91Response:
 92```json
 93{
 94  "totalTasks": 1000,
 95  "pendingTasks": 500,
 96  "processingTasks": 10,
 97  "completedTasks": 480,
 98  "failedTasks": 10,
 99  "processingRatePerMinute": 120.5,
100  "avgProcessingTimeMs": 450.2,
101  "estimatedBacklogCompletionSeconds": 187,
102  "activeWorkers": 5,
103  "currentPoolSize": 10,
104  "byTaskType": {
105    "sample": {
106      "pendingTasks": 490,
107      "scheduledTasks": 0,
108      "processingTasks": 10,
109      "completedTasks": 480,
110      "failedTasks": 10,
111      "cancelledTasks": 0,
112      "avgProcessingTimeMs": 450.2
113    }
114  }
115}
116```
117
118`estimatedBacklogCompletionSeconds` is an approximate drain time calculated
119from pending plus running tasks, the average successful runtime observed by
120this process, and the current worker pool size. It is `null` until the process
121has completed tasks and collected runtime samples. Scheduled tasks are excluded
122until they become runnable; estimates do not account for future submissions,
123priority tiers, or differences in the remaining runtime of active tasks.
124
125#### Cancel a Task
126
127```bash
128DELETE /api/v1/tasks/{taskId}
129```
130
131### Poller Configuration
132
133#### Get Current Configuration
134
135```bash
136GET /api/v1/poller/config
137```
138
139#### Update Configuration (Scale Processing)
140
141```bash
142PUT /api/v1/poller/config
143Content-Type: application/json
144
145{
146  "poolSize": 20,
147  "batchSize": 50,
148  "pollIntervalMs": 500,
149  "enabled": true
150}
151```
152
153#### Get Poller Status
154
155```bash
156GET /api/v1/poller/status
157```
158
159### Metrics
160
161Prometheus metrics available at:
162```bash
163GET /actuator/prometheus
164```
165
166Key metrics:
167- `tasks.enqueued` - Total tasks enqueued
168- `tasks.completed` - Total tasks completed
169- `tasks.failed` - Total tasks failed
170- `tasks.processing.active` - Currently processing tasks
171- `tasks.processing.duration` - Processing time histogram
172- `tasks.processing.rate` - Tasks per minute
173
174## Configuration
175
176### Application Properties
177
178```yaml
179task-processor:
180  # Unique worker ID (auto-generated if not set)
181  worker-id: ${HOSTNAME:${random.uuid}}
182  
183  poller:
184    enabled: true
185    pool-size: 5           # Initial thread pool size
186    max-pool-size: 20      # Maximum threads
187    batch-size: 10         # Tasks per poll
188    poll-interval-ms: 1000 # Base poll interval
189    adaptive-polling: true # Reduce polling when queue empty
190  
191  heartbeat:
192    interval-ms: 5000      # Heartbeat frequency
193    stale-threshold-ms: 30000  # When to consider task stuck
194    recovery-interval-ms: 10000 # Stale task check frequency
195```
196
197### Environment Variables
198
199For Kubernetes/Docker deployments:
200
201```bash
202TASK_PROCESSOR_WORKER_ID=pod-name
203TASK_PROCESSOR_POLLER_POOL_SIZE=20
204TASK_PROCESSOR_POLLER_BATCH_SIZE=50
205SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/taskprocessor
206```
207
208## Scaling for High Throughput
209
210When you have millions of tasks to process:
211
2121. **Increase Thread Pool Size**:
213```bash
214curl -X PUT http://localhost:8080/api/v1/poller/config \
215  -H "Content-Type: application/json" \
216  -d '{"poolSize": 50}'
217```
218
2192. **Increase Batch Size**:
220```bash
221curl -X PUT http://localhost:8080/api/v1/poller/config \
222  -H "Content-Type: application/json" \
223  -d '{"batchSize": 100}'
224```
225
2263. **Reduce Poll Interval**:
227```bash
228curl -X PUT http://localhost:8080/api/v1/poller/config \
229  -H "Content-Type: application/json" \
230  -d '{"pollIntervalMs": 100}'
231```
232
2334. **Deploy Multiple Pods**: Each pod will independently process tasks without conflicts.
234
235## How It Works
236
237### Distributed Locking with SKIP LOCKED
238
239The key to preventing duplicate processing is PostgreSQL's `SKIP LOCKED`:
240
241```sql
242SELECT * FROM tasks 
243WHERE status = 'PENDING' 
244ORDER BY priority DESC, created_at ASC 
245LIMIT 10 
246FOR UPDATE SKIP LOCKED
247```
248
249This query:
2501. Locks rows that are returned
2512. Skips rows already locked by other transactions
2523. Ensures no two workers get the same task
253
254### Heartbeat and Recovery
255
2561. Workers send heartbeats every 5 seconds for tasks they're processing
2572. A background job checks for tasks with stale heartbeats (>30 seconds)
2583. Stale tasks are either:
259   - Reset to PENDING for retry (if attempts remain)
260   - Marked as FAILED (if max attempts exceeded)
261
262### Adaptive Polling
263
264To reduce database load:
2651. When tasks are found, poll interval is minimized (100ms)
2662. When queue is empty, interval doubles up to max (5000ms)
2673. This reduces unnecessary DB queries during idle periods
268
269## Creating Custom Task Handlers
270
271```java
272@Component
273public class EmailTaskHandler implements TaskHandler {
274
275    @Override
276    public String getTaskType() {
277        return "send-email";
278    }
279
280    @Override
281    public void handle(Task task) throws Exception {
282        // Parse payload
283        EmailPayload payload = objectMapper.readValue(
284            task.getPayload(), 
285            EmailPayload.class
286        );
287        
288        // Send email
289        emailService.send(payload);
290    }
291}
292```
293
294Then enqueue tasks with that type:
295```bash
296POST /api/v1/tasks
297{
298  "taskType": "send-email",
299  "payload": "{\"to\": \"user@example.com\", \"subject\": \"Hello\"}"
300}
301```
302
303```
304locust -f locustfile.py
305```

References

comments powered by Disqus