Skip to main content

Ray-based backend for Django Tasks with distributed execution and database-backed reliability

Project description

django-ray logo

django-ray

A Ray-based backend for Django Tasks that enables distributed task execution with database-backed reliability.

CI Docs Python versions License

Why django-ray?

Django projects often need background task execution. While Celery has been the go-to solution for years, Ray offers a more powerful and flexible approach to distributed computing:

  • True distributed computing: Ray was built for distributed workloads from the ground up, not just task queues
  • Horizontal scaling: Scale from a single machine to thousands of nodes without changing your code
  • Resource-aware scheduling: Request specific CPU, GPU, or memory for tasks
  • Actor model support: Maintain stateful workers when needed
  • Rich ecosystem: Access to Ray's ML libraries, data processing, and more

Despite Ray's capabilities, there was no straightforward way to use it with Django's built-in Tasks framework. django-ray bridges this gap, letting you leverage Ray's distributed computing power while keeping Django's familiar patterns and database-backed reliability.

Overview

django-ray bridges Django's built-in Tasks framework with Ray's distributed computing capabilities, providing:

  • Database-backed reliability: Task state is tracked in your Django database, ensuring no tasks are lost
  • Multiple execution modes: Sync, local Ray, Ray cluster, or Ray Job API
  • Automatic retries: Failed tasks are retried with exponential backoff
  • Admin visibility: Monitor and manage tasks through Django admin
  • Graceful shutdown: Workers handle signals properly for clean shutdown
  • Ray-native workflows: Chain, group, and dynamically fan out low-overhead internal steps behind one durable Django task
  • RuntimeEnv profiles: Run versioned or lightweight Python environments on a generic Ray cluster, with immutable environment identity per durable task
  • Observable workflow graphs: Track dependency edges, node progress, Ray execution identifiers, and correlated logs for custom monitoring UIs

The repository includes a sample testproject/ with a small landing page for exploring the bundled API, task stats, project links, and smoke-task trigger:

django-ray testproject landing page

Requirements

  • Python 3.12, 3.13, or 3.14
  • Django 6.0+
  • Ray 2.53.0+

Installation

pip install django-ray

Or with uv:

uv add django-ray

Quick Start

  1. Add django_ray to your INSTALLED_APPS:
INSTALLED_APPS = [
    # ...
    "django_ray",
]
  1. Configure Django Tasks and django-ray:
TASKS = {
    "default": {
        "BACKEND": "django_ray.backends.RayTaskBackend",
        "QUEUES": ["default"],
    },
}

DJANGO_RAY = {
    "RAY_ADDRESS": "auto",  # Use "ray://host:port" for a remote cluster
    "RUNNER": "ray_core",
    "DEFAULT_CONCURRENCY": 10,
    "MAX_TASK_ATTEMPTS": 3,
}
  1. Run migrations:
python manage.py migrate django_ray
  1. Start the worker:
# Local Ray (recommended for development)
python manage.py django_ray_worker --queue=default --local

# Connect to Ray cluster
python manage.py django_ray_worker --queue=default --cluster=ray://localhost:10001

# Sync mode (no Ray, for testing)
python manage.py django_ray_worker --queue=default --sync

Worker Execution Modes

Mode Flag Description
sync --sync Direct execution, no Ray (testing)
local --local Local Ray cluster, tasks via @ray.remote
cluster --cluster=<addr> Remote Ray cluster, tasks via @ray.remote
ray-job (default) Ray Job Submission API (process isolation)

Configuration

Setting Default Description
RAY_ADDRESS None Must be set at runtime; use "auto" locally or "ray://host:port" for a cluster
DEFAULT_CONCURRENCY 10 Max concurrent tasks per worker
MAX_TASK_ATTEMPTS 3 Max retry attempts
RETRY_BACKOFF_SECONDS 60 Base backoff for retries
RETRY_EXCEPTION_DENYLIST [] Exception types that skip auto-retry
STUCK_TASK_TIMEOUT_SECONDS 300 Timeout before marking tasks as LOST
TASK_MONITOR_HEARTBEAT_SECONDS 15 Database heartbeat interval for in-flight Ray Core tasks
RUNTIME_ENV_PROFILES {} Named Ray environments for code and dependencies
DEFAULT_RUNTIME_ENV_PROFILE None Default named environment

See Ray-Native Workflows for low-latency chain, group, and map_step execution. See Runtime Environments for per-task profiles, workflow overrides, and generic KubeRay images. See Performance for choosing durable task boundaries, execution modes, and useful fan-out granularity.

Development Setup

Prerequisites

  • Python 3.12, 3.13, or 3.14
  • uv package manager

Installation

git clone <repository-url>
cd django-ray
uv sync

Development Commands

make install     # Install dependencies
make format      # Format code with Ruff
make lint        # Lint code with Ruff
make typecheck   # Type check with ty
make test        # Run tests
make check       # Run lint + typecheck
make ci          # Run all CI checks
make docs-build  # Build docs (Zensical)
make docs-build-strict # Build docs in strict mode
make docs-serve  # Serve docs locally

Django Commands

make migrate          # Run migrations
make runserver        # Start dev server
make shell            # Django shell
make createsuperuser  # Create admin user

Worker Commands

make worker           # Ray Job API mode
make worker-local     # Local Ray (recommended)
make worker-sync      # Sync mode (no Ray)
make worker-all       # All queues, local Ray
make worker-cluster   # Connect to cluster

Quick Start (End-to-End Testing)

Terminal 1 - Start Django server:

make runserver

Terminal 2 - Start worker:

make worker-all

Browser - Test via API:

  1. Open http://127.0.0.1:8000/api/docs (Swagger UI)
  2. Try POST /api/enqueue/add/100/200
  3. Check GET /api/executions - see task completed with result 300
  4. View in Admin: http://127.0.0.1:8000/admin/django_ray/raytaskexecution/

Queue Configuration

# Single queue
python manage.py django_ray_worker --queue=default

# Multiple queues
python manage.py django_ray_worker --queue=default,high-priority,low-priority

# All configured queues
python manage.py django_ray_worker --all-queues

Docker

make docker-build

# Run modes:
docker run -p 8000:8000 django-ray:latest web          # Production
docker run -p 8000:8000 django-ray:latest web-dev      # Development
docker run django-ray:latest worker                     # Worker (local Ray)
docker run django-ray:latest worker-cluster             # Worker (cluster)

Kubernetes Deployment

Deploy using Kustomize manifests in k8s/:

# Build images
make k8s-build

# Deploy
make k8s-deploy

# Check status
make k8s-status

# With TLS enabled
make k8s-gen-tls-certs
make k8s-deploy-tls

See k8s/README.md for detailed deployment documentation.

Project Structure

django-ray/
├── src/django_ray/          # Library source code
│   ├── models.py            # RayTaskExecution, TaskWorkerLease
│   ├── admin.py             # Admin interface
│   ├── backends.py          # Django Task Backend
│   ├── conf/                # Settings
│   ├── runner/              # Task runners
│   │   ├── ray_job.py       # Ray Job Submission API
│   │   ├── ray_core.py      # Ray Core (@ray.remote)
│   │   ├── leasing.py       # Worker coordination
│   │   └── retry.py         # Retry logic
│   ├── runtime/             # Task execution
│   │   ├── entrypoint.py    # Execution entry point
│   │   ├── distributed.py   # parallel_map, scatter_gather
│   │   └── serialization.py
│   └── management/commands/
│       └── django_ray_worker.py
│
├── testproject/             # Example project (development only)
│   ├── api.py               # Example REST API
│   ├── tasks.py             # Example tasks
│   └── apps/                # Example apps
│
├── tests/                   # Test suite
├── docs/                    # Documentation
└── k8s/                     # Kubernetes manifests

Documentation

Published docs are served with Zensical at:

Agents and documentation tools can start with llms.txt. The published documentation also serves /llms.txt.

Read the Docs builds are configured in .readthedocs.yaml. The build installs uv, runs the strict Zensical build, and copies the generated site/ output into Read the Docs' HTML output directory.

Source docs remain in the docs/ directory:

Deployment

  • Kubernetes - Deploy to Kubernetes
  • Docker - Running with Docker
  • TLS - Securing Ray communication

Reference

License

This project is licensed under the BSD 3-Clause License - see the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_ray-0.3.0.tar.gz (885.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_ray-0.3.0-py3-none-any.whl (71.0 kB view details)

Uploaded Python 3

File details

Details for the file django_ray-0.3.0.tar.gz.

File metadata

  • Download URL: django_ray-0.3.0.tar.gz
  • Upload date:
  • Size: 885.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.13

File hashes

Hashes for django_ray-0.3.0.tar.gz
Algorithm Hash digest
SHA256 e9479545319df5ce7cf563d90fcc5e9214501fb4742f527a7f1c3ca4b31dc90a
MD5 0b1e16876017058ec6e733f9592fd7cd
BLAKE2b-256 77f5443eb100c79d4a1285c85828336ed396da9c06cf292dd4250b5ef888afed

See more details on using hashes here.

Provenance

The following attestation bundles were made for django_ray-0.3.0.tar.gz:

Publisher: release.yml on dariuszpanas/django-ray

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file django_ray-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: django_ray-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 71.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.13

File hashes

Hashes for django_ray-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f8ec390c034f9758cb5977549a4d98cb714de73758e214db224ace9a2288c665
MD5 6be98060d79f9841a4c6f80b94ae894d
BLAKE2b-256 ee30624d7ef6dccd98bf058ae1993117cec20db2c1ef791be67b9afdb6710bd2

See more details on using hashes here.

Provenance

The following attestation bundles were made for django_ray-0.3.0-py3-none-any.whl:

Publisher: release.yml on dariuszpanas/django-ray

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page