Engineer a background job scheduler supporting cron, ad-hoc tasks, and saga…
- User
Engineer a background job scheduler supporting cron, ad-hoc tasks, and saga compensations with metrics.
Assistant
Engineer a background job scheduler supporting cron, ad-hoc tasks, and saga compensations with metrics.
The user wants an engineered solution for a background job scheduler. The system needs to support:
I need to decide on a technology stack. Python is a good choice for a clear, readable implementation. I'll use:
prometheus_client: For exposing metrics.Architecture Overview:
Detailed Component Design:
Core Wrapper: I'll create a wrapper around the Celery app to standardize configuration and make it easier to add the metrics middleware.
Metrics:
jobs_total (labels: type, status)job_duration_seconds (labels: type)jobs_in_progresstask_prerun, task_postrun, task_failure) to capture these automatically.Cron:
Ad-hoc:
apply_async.Saga:
SagaOrchestrator class that uses Celery chains and error handling callbacks.step1.s() | step2.s() | step3.s(). If one fails, Celery doesn't automatically run compensations.SagaTask abstract base class or a specific workflow where the task itself knows its compensation. When a task fails, it triggers the compensation chain.Code Structure:
config.py: Redis URL, etc.metrics.py: Prometheus setup.celery_app.py: Celery initialization and signal hooking for metrics.saga.py: The logic for defining and running sagas.tasks.py: The actual job definitions (Cron, Ad-hoc, Saga steps).main.py: Entry point to trigger jobs.Refining the Metrics Integration:
Celery signals are the standard way to do this.
before_task_publish -> task_prerun -> task_postrun / task_failure.
Refining the Saga Implementation:
Let's make the Saga explicit.
saga_steps = [step1, step2, step3]
compensations = [comp1, comp2, comp3]
Logic:
run_saga task.step(i) fails, it calls compensate(i-1), compensate(i-2)...link_error (callbacks).
link_error only attaches to the specific task. We need the context of previous successful steps to know what to compensate.Let's build a simplified "Orchestrator" pattern in code.
The SagaRunner class will manage the flow. It will be a task itself.
saga_runner(saga_id, steps, current_step_index)
current_step_index.saga_runner via apply_async.compensation_runner via apply_async.This is clean and demonstrates the concept well.
Drafting the Code:
celery, redis, prometheus-client.scheduler.py (The core app + metrics)saga_system.py (The Saga logic)jobs.py (Definitions of tasks)usage.py (How to run it)Self-Correction/Review during thought process:
Issue: Prometheus metrics in a multiprocessing worker (Celery).
Fix: Standard Prometheus client has issues with multiprocess models (like Gunicorn or Celery).
Workaround: For this architectural example, I will use the standard prometheus_client with PROMETHEUS_MULTIPROC_DIR environment variable handling, or simply stick to the logic of how to instrument it, noting that in a real prod environment, you'd need a statsd exporter or pushgateway. I will stick to the Signal handling implementation as it's the most "engineering" focused part of the request.
Saga Logic:
Cron: I'll define the schedule within the celery_app.conf.
Let's write the code. I will structure it as a Python project skeleton.
Key Components to Write:
connect_metrics function that attaches to Celery signals.SagaOrchestrator that manages steps and rollback.Saga Detail: A Saga needs to persist state if it's truly robust (e.g., in Redis/DB). For this code, I will pass the state (the list of executed steps) along the chain to avoid needing a complex DB setup in the example code.
Plan:
metrics.py: Setup counters/histograms.scheduler.py: Celery app + Signal listeners.saga.py: A define_saga helper that builds a chain of tasks with error handling callbacks.jobs.py: The actual tasks.Let's refine the Saga part.
Method A: step1.apply_async(link=step2.s(), link_error=compensate1.s())
This is hard because compensate1 needs to know about step2's failure? No, link_error handles the current task failure.
If Step 2 fails, link_error on Step 2 runs.
But we need to run Compensate 1 AND Compensate 2.
So, link_error on Step 2 should trigger compensate_2, which triggers compensate_1 (chained). Or link_error triggers a rollback_all task.
I'll use a helper that constructs a Celery Canvas chain for the happy path and a chain for the sad path (compensations) attached via link_error.
Final Output Structure: A complete Python module setup.
Saga helper.Let's go. This solution implements a robust background job scheduler in Python. It uses Celery for the distributed task queue (handling Ad-hoc and Cron jobs) and implements a Saga Orchestrator pattern for managing distributed transactions with compensation logic.
It also includes a Prometheus metrics integration to monitor job throughput, latency, and failures.
You will need the following Python libraries:
pip install celery redis prometheus-client
Assumes a Redis instance running at localhost:6379.
prometheus-client exposing an HTTP endpoint.Create a file named scheduler.py.
You need three separate terminal windows to run the components.
Terminal 1: The Worker (Consumes Jobs) This process executes the tasks, handles the Saga logic, and records metrics.
python scheduler.py worker
Terminal 2: The Beat Scheduler (Cron) This process triggers time-based tasks (e.g., the cleanup job).
# Note: To run beat programmatically, celery requires a bit of setup,
# so usually it is safer to run the command directly:
celery -A scheduler beat --loglevel=info
Terminal 3: The Client (Trigger Tasks) This script triggers the Ad-hoc and Saga jobs.
python scheduler.py trigger
While the worker is running, navigate to:
http://localhost:8001/metrics
You will see output similar to:
# HELP background_job_duration_seconds Duration of jobs
# TYPE background_job_duration_seconds histogram
background_job_duration_seconds_bucket{job_type="cleanup_logs",le="0.05"} 1
...
# HELP background_jobs_total Total count of jobs
# TYPE background_jobs_total counter
background_jobs_total{job_type="adhoc_email",status="SUCCESS"} 1
...
# HELP saga_transactions_total Total count of Saga transactions
# TYPE saga_transactions_total counter
saga_transactions_total{status="failed"} 1
Saga Orchestrator Pattern:
SagaOrchestrator class. It takes a list of steps (Action + Compensation).book_flight succeeds but book_hotel fails, the try/except block catches the exception and iterates over executed_steps in reverse to run cancel_flight.Metrics with Prometheus:
signals provided by Celery (task_prerun, task_postrun). This is a cross-cutting concern approach, meaning you don't have to add metric code inside every single job function.Ad-Hoc vs. Cron:
.delay() (asynchronous dispatch).app.conf.beat_schedule.Resilience:
import time
import random
from celery import Celery, signals
from celery.schedules import crontab
from prometheus_client import Counter, Histogram, start_http_server
# ==========================================
# 1. Configuration & Metrics Setup
# ==========================================
# Start Prometheus HTTP server on port 8001
# Metrics will be available at http://localhost:8001/metrics
start_http_server(8001)
# Define Prometheus Metrics
TASK_COUNTER = Counter('background_jobs_total', 'Total count of jobs', ['job_type', 'status'])
TASK_LATENCY = Histogram('background_job_duration_seconds', 'Duration of jobs', ['job_type'])
SAGA_COUNTER = Counter('saga_transactions_total', 'Total count of Saga transactions', ['status'])
# Celery App Initialization
app = Celery('scheduler',
broker='redis://localhost:6379/0',
backend='redis://localhost:6379/0')
app.conf.update(
task_serializer='json',
accept_content=['json'],
result_serializer='json',
timezone='UTC',
enable_utc=True,
)
# ==========================================
# 2. Metrics Middleware (Signals)
# ==========================================
@signals.task_prerun.connect
def task_prerun_handler(sender=None, task_id=None, task=None, **kwargs):
"""Mark start time for latency tracking."""
task.request.start_time = time.time()
@signals.task_postrun.connect
def task_postrun_handler(sender=None, task_id=None, task=None, retval=None, state=None, **kwargs):
"""Record metrics after task execution."""
duration = time.time() - getattr(task.request, 'start_time', time.time())
# 'job_type' can be determined by task name or tags
job_type = task.name.split('.')[-1]
TASK_LATENCY.labels(job_type=job_type).observe(duration)
TASK_COUNTER.labels(job_type=job_type, status=state).inc()
# ==========================================
# 3. Job Definitions
# ==========================================
@app.task(bind=True, name='jobs.adhoc_email')
def send_adhoc_email(self, user_id):
"""An Ad-hoc task example."""
print(f"[Ad-hoc] Sending email to user {user_id}...")
time.sleep(1) # Simulate work
if random.random() < 0.1: # 10% chance of random failure
raise ValueError("SMTP Connection Failed")
print(f"[Ad-hoc] Email sent to {user_id}")
return f"Email sent to {user_id}"
@app.task(bind=True, name='jobs.cleanup_logs')
def cleanup_logs(self):
"""A Cron job example."""
print("[Cron] Cleaning up logs...")
time.sleep(0.5)
print("[Cron] Logs cleaned.")
return "Cleaned"
# ==========================================
# 4. Saga Pattern Implementation
# ==========================================
class SagaOrchestrator:
"""
Manages distributed transactions using the Saga pattern.
Executes steps sequentially. If a step fails, it executes compensations
for completed steps in reverse order.
"""
def __init__(self, steps):
"""
steps: List of dicts {'name': str, 'task': callable, 'compensation': callable}
"""
self.steps = steps
def execute(self, *args, **kwargs):
executed_steps = []
payload = {'data': kwargs, 'log': []}
print(f"\n--- Starting Saga Transaction ---")
try:
# 1. Execute Forward Path
for i, step in enumerate(self.steps):
task_func = step['task']
step_name = step['name']
print(f"[Saga] Executing Step {i+1}: {step_name}")
try:
# Assuming tasks are Celery tasks, we call them synchronously
# for the orchestrator logic, or use .delay() and get() results.
# For robustness in this example, we run them synchronously
# to catch exceptions easily within the orchestrator flow.
result = task_func(**payload)
payload['log'].append(f"Step {step_name} success")
executed_steps.append(step)
except Exception as e:
print(f"[Saga] Step {step_name} FAILED: {e}")
raise e # Trigger compensation
print("[Saga] Transaction Completed Successfully.")
SAGA_COUNTER.labels(status='success').inc()
return payload
except Exception as e:
# 2. Execute Compensation (Rollback)
print(f"[Saga] Initiating Rollback due to failure...")
SAGA_COUNTER.labels(status='failed').inc()
# Reverse the list of executed steps
for step in reversed(executed_steps):
comp_func = step['compensation']
step_name = step['name']
print(f"[Saga] Compensating Step: {step_name}")
try:
comp_func(**payload)
except Exception as comp_e:
print(f"[Saga] CRITICAL: Compensation failed for {step_name}: {comp_e}")
print("[Saga] Rollback Completed.")
raise e
# ==========================================
# 5. Saga Tasks & Compensations
# ==========================================
@app.task(name='saga.book_flight')
def book_flight(**context):
print(" > Booking Flight...")
if random.random() < 0.3: # Simulate failure
raise Exception("Flight booking API down")
context['flight_id'] = "FL-123"
return context
@app.task(name='saga.cancel_flight')
def cancel_flight(**context):
print(" > Canceling Flight (Refund)...")
# Logic to revert flight booking
return True
@app.task(name='saga.book_hotel')
def book_hotel(**context):
print(" > Booking Hotel...")
context['hotel_id'] = "HT-456"
return context
@app.task(name='saga.cancel_hotel')
def cancel_hotel(**context):
print(" > Canceling Hotel (Refund)...")
return True
# ==========================================
# 6. Scheduling Configuration (Cron)
# ==========================================
app.conf.beat_schedule = {
'cleanup-every-minute': {
'task': 'jobs.cleanup_logs',
'schedule': 60.0, # Every 60 seconds
},
}
# ==========================================
# 7. Main Execution Block
# ==========================================
if __name__ == '__main__':
import sys
if len(sys.argv) < 2:
print("Usage: python scheduler.py [worker | beat | trigger]")
sys.exit(1)
mode = sys.argv[1]
if mode == 'worker':
# Start the Celery Worker
# In prod, use CLI: celery -A scheduler worker --loglevel=info
app.worker_main(['worker', '--loglevel=info'])
elif mode == 'beat':
# Start the Celery Beat Scheduler
# In prod, use CLI: celery -A scheduler beat --loglevel=info
app.start()
elif mode == 'trigger':
# Simulation Client: Trigger Ad-hoc and Saga
# 1. Trigger Ad-hoc Task
print("\nTriggering Ad-hoc Task...")
send_adhoc_email.delay(user_id=99)
# 2. Trigger Saga Transaction
# Note: In a real system, the orchestrator might run inside a Celery task.
# Here we run it in the main process to demonstrate the logic flow.
print("\nTriggering Saga Transaction...")
travel_saga = SagaOrchestrator(steps=[
{'name': 'Book Flight', 'task': book_flight, 'compensation': cancel_flight},
{'name': 'Book Hotel', 'task': book_hotel, 'compensation': cancel_hotel},
])
try:
# We use .apply() to run synchronously for this demo
# In production, this orchestrator logic would likely be inside a task
# dispatched via orchestrator_task.delay()
travel_saga.execute(trip_id="TRIP-001")
except Exception:
pass # Handled inside saga