Skip to content

About

Distributed C++17 background job and work queue using Redis, REST APIs, retries, and extensible worker handlers

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Distributed WorkQueue in C++

A distributed background-job processing system built with modern C++17 and Redis.

This project demonstrates HTTP API design, Redis-backed queueing, multithreaded worker execution, JSON serialization, retry handling, and modular C++ architecture. It was developed by Kaja Magbool as a portfolio project for learning and demonstrating production-oriented C++ systems design.

Highlights

  • C++17 application with separate API, queue, common, and worker modules
  • Redis-backed pending, processing, and dead-letter queues
  • REST API built with cpp-httplib
  • JSON task serialization using nlohmann-json
  • Redis integration through hiredis and redis-plus-plus
  • Configurable worker polling and retry limits
  • Exponential retry backoff
  • Multiple worker processes for horizontal scaling
  • Modular job-handler interface for extending supported job types
  • CMake build system with clearly separated library targets

Architecture

flowchart LR
    Client -->|HTTP POST /enqueue| API[API Server]
    API -->|Serialize and LPUSH| Redis[(Redis)]
    Redis -->|BRPOP| Worker1[Worker 1]
    Redis -->|BRPOP| Worker2[Worker 2]
    Redis -->|BRPOP| WorkerN[Worker N]
    Worker1 --> Handlers[Job Handlers]
    Worker2 --> Handlers
    WorkerN --> Handlers
    Handlers --> Success[Completed]
    Handlers -->|Retry| RetryQueue[Pending Queue]
    Handlers -->|Retries exhausted| DLQ[Dead-Letter Queue]
Loading

How It Works

  1. A client submits a task to the HTTP API.
  2. The API validates the job type and creates a task with a UUID and initial PENDING status.
  3. The task is serialized to JSON and added to the Redis pending queue.
  4. A worker blocks on Redis for the next task.
  5. The worker moves the task into a processing queue and dispatches it to a registered handler.
  6. Successful work is marked completed.
  7. Retryable failures are re-queued with exponential backoff.
  8. Tasks that exhaust retries are moved to the dead-letter queue.

Project Structure

.
├── CMakeLists.txt
├── include/workqueue
│   ├── api
│   │   └── api_server.hpp
│   ├── common
│   │   ├── job_types.hpp
│   │   └── task.hpp
│   ├── queue
│   │   └── redis_queue.hpp
│   └── worker
│       ├── job_handler.hpp
│       ├── worker.hpp
│       └── handlers
├── src
│   ├── api
│   ├── common
│   ├── queue
│   └── worker
├── .gitignore
└── README.md

API Endpoints

POST /enqueue

Submit a background task.

curl -X POST http://localhost:8080/enqueue \
  -H "Content-Type: application/json" \
  -d '{
    "type": "logging",
    "payload": {
      "message": "Worker system started",
      "level": "INFO",
      "source": "api"
    },
    "max_retries": 3
  }'

Example response:

{
  "success": true,
  "task_id": "d6b3f8c4-6e73-4f12-9c10-3bd3dbf3a0db",
  "type": "logging",
  "status": "queued"
}

Supported types:

Type Purpose
email Simulates email delivery
data_processing Simulates data transformation or ETL work
logging Writes timestamped log messages

GET /health

Checks whether the API process can communicate with Redis.

curl http://localhost:8080/health

GET /stats

Returns the pending queue length, dead-letter queue length, and Redis connection state.

curl http://localhost:8080/stats

Example:

{
  "queue_length": 5,
  "dead_letter_length": 1,
  "connected": true,
  "timestamp": 1705123456789
}

Redis Data Layout

Redis key Purpose
workqueue:tasks Pending jobs
workqueue:tasks:processing Jobs currently being processed
workqueue:tasks:dead_letter Jobs that exhausted retry attempts

Tasks are transferred as JSON documents using Redis list operations.

Task Lifecycle

Status Meaning
PENDING Waiting in the Redis queue
PROCESSING Assigned to a worker
COMPLETED Handler execution succeeded
FAILED Failure state defined by the task model
DEAD Retries exhausted and moved to the dead-letter queue

Retry delays use exponential backoff:

100 ms, 200 ms, 400 ms, 800 ms, ...

The delay depends on the task's retry_count and is reset when the task is re-queued.

Build Requirements

  • C++17-compatible compiler
  • CMake 3.16 or newer
  • Redis server
  • nlohmann-json
  • hiredis
  • redis-plus-plus
  • cpp-httplib
  • Linux, macOS, or Windows toolchain

Build and Run

1. Start Redis

With Docker:

docker run -d --name redis-workqueue -p 6379:6379 redis:latest

Or start a local Redis server:

redis-server

Verify the connection:

redis-cli ping

The result should be PONG.

2. Configure and build

cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build -j

3. Start the API server

./build/workqueue_api_server --port 8080

API configuration:

--port             HTTP port; default 8080
--redis-host       Redis host; default 127.0.0.1
--redis-port       Redis port; default 6379
--redis-password   Optional Redis password

4. Start one or more workers

./build/workqueue_worker_service --worker-id worker-1
./build/workqueue_worker_service --worker-id worker-2
./build/workqueue_worker_service --worker-id worker-3

Worker configuration:

--worker-id        Human-readable worker identifier
--redis-host       Redis host; default 127.0.0.1
--redis-port       Redis port; default 6379
--redis-password   Optional Redis password
--log-file         Optional file used by the logging handler

Scaling

The system can run multiple API and worker processes. Workers share the same Redis instance and each independently blocks for the next available task. Redis distributes tasks among connected workers.

For local development, run separate processes in separate terminals. In deployment, API and worker services can be scaled independently.

Example Job Payloads

Email

{
  "type": "email",
  "payload": {
    "to": "user@example.com",
    "subject": "Welcome",
    "body": "Hello from C++",
    "simulate_failure": false
  }
}

Data processing

{
  "type": "data_processing",
  "payload": {
    "operation": "transform",
    "source": "/data/input.csv",
    "destination": "/data/output.json",
    "batch_size": 1000,
    "simulate_failure": false
  }
}

Logging

{
  "type": "logging",
  "payload": {
    "message": "User signed up",
    "level": "INFO",
    "source": "auth-service",
    "simulate_failure": false
  }
}

Adding a Job Handler

  1. Implement JobHandler in include/workqueue/worker/handlers.
  2. Implement execute(), name(), and jobType().
  3. Register the handler in src/worker/main_worker.cpp.
  4. Add the job type to include/workqueue/common/job_types.hpp.
  5. Submit tasks using the new type through /enqueue.

C++ Concepts Demonstrated

  • C++17 enum class and structured job states
  • Smart pointers and RAII
  • Polymorphism through an abstract handler interface
  • JSON model serialization
  • Thread-safe counters with std::atomic
  • Mutex-protected Redis operations
  • Blocking Redis operations
  • Exception handling
  • Modular static library design
  • CMake target configuration and dependency linking
  • HTTP server route registration
  • UUID-style task identification
  • Retry and dead-letter queue patterns
  • Horizontally scalable process design

Current Scope

This is a learning and portfolio implementation rather than a complete production broker. The email, data-processing, and logging handlers simulate real work. The project currently does not provide authentication, task listing, task lookup, durable completed-task history, scheduling, priorities, TLS, or a web UI.

Planned Improvements

  • Persist completed task status and timestamps
  • Add task list, detail, retry, and cancellation endpoints
  • Add due-date and overdue filtering
  • Replace fixed Redis lists with a persistent task index
  • Integrate structured logging and metrics
  • Add Docker Compose startup for Redis and services
  • Add unit and integration tests
  • Add authentication and HTTPS
  • Integrate real email and data-processing implementations
  • Add graceful shutdown and processing-queue recovery

Author

Kaja Magbool
C++ and systems-learning portfolio project
GitHub: kajamaqbool

License

MIT License. See LICENSE for details.

About

Distributed C++17 background job and work queue using Redis, REST APIs, retries, and extensible worker handlers

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages