The user wants an "async job platform" with specific features:
- Priorities: Jobs need to be processed based on urgency.
- Idempotency: Submitting the same job twice shouldn't result in duplicate processing/work.
- Deduplication: Related to idempotency, preventing duplicate jobs from entering the system.
- DLQs (Dead Letter Queues): Handling jobs that fail permanently.
- Retries: Handling transient failures by retrying jobs.
This is a complex system design question. I need to provide a conceptual architecture, data structures, and code snippets (likely Python with a library like Celery or RQ, or a custom solution using Redis/Postgres) to illustrate how these features are implemented.
Language Choice: Python is the standard for this type of backend work. I'll use asyncio for the asynchronous aspect and Redis as the backing store because it's excellent for queues, dedup sets, and locking.
Architecture Components:
- Producer: Submits jobs.
- Broker (Redis): Stores the queues.
- Consumer (Worker): Processes jobs.
- State Store: Tracks job status (pending, running, success, failed).
Feature Implementation Details:
-
Priorities:
- How to implement? Multiple queues (e.g.,
queue:high, queue:low) or a sorted set (ZSET) using score as priority.
- Let's go with Sorted Sets (ZSETs) or Multiple Lists. ZSETs allow more granular numeric priorities. Multiple lists are simpler for "High/Medium/Low".
- Decision: I'll implement a priority system using multiple named queues (e.g.,
critical, default, low) and have the worker poll the high-priority queues more frequently or strictly sequentially (check high, if empty check medium, etc.).
-
Idempotency & Deduplication:
- These go hand-in-hand.
- Mechanism: Use a unique "Job ID" or "Idempotency Key".
- Flow: When a job is submitted, check a set (e.g.,
known_jobs) or a hash.
- If it exists and is pending/success, return the existing job ID.
- If it exists and is failed/DLQ, maybe allow re-triggering? Or strictly dedup.
- Let's stick to strict deduplication during the "active" lifecycle. Once finished, maybe allow a rerun, or maybe keep it forever.
- Implementation:
SETNX (Set if Not Exists) in Redis.
-
Retries:
- If a job fails, put it back in the queue with a delay.
- Need to track retry counts.
- Implementation: Use a "Delay Queue" (ZSET with execution time as score) or simply
sleep and re-add (bad for workers). ZSET is better.
- Worker logic: Catch exception -> increment count -> if count < max, move to Delay ZSET -> eventually move back to Ready Queue.
-
DLQs (Dead Letter Queues):
- If retry count exceeds max, move to a specific list/key
dlq:default.
- Needs inspection capabilities.
Code Structure:
JobClient: For submitting jobs.
Worker: For processing jobs.
JobStore: Interface to Redis.
Refining the "Async" part:
The prompt asks for an async job platform. In Python, this implies asyncio. The worker should be non-blocking.
Drafting the solution (Mental Model):
-
Redis Keys:
queue:{priority}: List (FIFO) for ready jobs.
delayed: ZSET (score = timestamp) for retries.
job:{id}: Hash (status, payload, retries, idempotency_key).
idempotency:{key}: String (mapping key to job ID).
-
The Worker Loop:
- Check
delayed queue: move ready items to queue:{priority}.
- Pop from
queue:high, then queue:medium, then queue:low (using BLPOP or async equivalent).
- Execute task.
- On success: Update status, remove idempotency key (optional, or keep for history).
- On failure: Update retries. If max retries hit -> Move to
dlq. Else -> Move to delayed with exponential backoff.
Self-Correction/Edge Cases:
- Visibility Timeout: If a worker crashes while processing, the job is lost.
- Solution: Use Redis Streams or a "Reliable Queue" pattern (move to
processing list, then remove on success). To keep the code understandable but robust, I'll implement a basic "processing" state but might skip full reliability handshakes for brevity unless essential.
- Actually, a ZSET for active jobs with a timeout score is a robust way to handle visibility timeouts.
- Let's stick to a simpler model for a "build" prompt: Standard lists + a hash for metadata. I will add a note about "at-least-once" vs "exactly-once" delivery. Redis lists are "at-least-once" generally unless we get fancy.
Plan:
- High-Level Design: Explain the architecture (Producer -> Broker -> Consumer).
- The "Protocol": Define the JSON payload structure.
- Implementation (Python + Redis):
JobQueue class (The logic).
Worker class.
- Idempotency logic.
- Retry/Backoff logic.
- DLQ handling.
Let's write the code. I will use redis-py (async version).
Dependencies: redis[hiredis]
Key Logic - Idempotency:
SET idempotency_key:123 job_id NX
If OK -> Create Job.
If Nil -> Return existing Job ID.
Key Logic - Priorities:
Strict Priority: Always check High queue before Low queue. (Can lead to starvation of Low, but usually desired in strict systems).
Or Round Robin. I'll implement Strict Priority polling for simplicity.
Key Logic - Retries:
Store current_retries in the job hash.
On fail: current_retries += 1. If current_retries < max, calculate delay, add to delayed ZSET.
Key Logic - DLQ:
If current_retries >= max, add to dlq list.
Refining the Scope:
The user asked to build it. A complete production-ready system is thousands of lines. I will build a functional core prototype that demonstrates these specific mechanisms clearly.
Output Structure:
- Architecture Overview: Visualizing the flow.
- Data Model: How Redis stores the state.
- The Implementation: Python code.
- Usage Example: Showing how to run it.
Let's ensure the code is actually runnable or very close to it. I'll use asyncio and aioredis (which is now just redis in python with async support).
-
Priority: I will use BRPOP on multiple lists. Redis BRPOP accepts a list of keys. It checks them in order. So brpop high_queue, low_queue implements strict priority automatically! That's a great simplification.
-
Idempotency: I need to hash the payload or rely on the user passing a key. Relying on the user passing a key is more flexible.
-
Dedup: Same mechanism as Idempotency.
-
Retries: Need a separate coroutine to move items from delayed (ZSET) to ready (List).
Let's assemble.
- Step 1:
enqueue(job, idempotency_key, priority)
- Check
idempotency:{key}.
- If exists, return ID.
- Create job ID. Store payload in
job:{id}.
- Set
idempotency:{key} = job_id.
LPUSH to queue:{priority}.
- Step 2:
worker()
BRPOP queue:high queue:med queue:low.
- Update job status -> RUNNING.
- Run task.
- If Success: Del job? Or mark Success. Remove Idempotency key? (Crucial question: usually idempotency keys expire or stay for a window. I'll let them stay until job is cleaned up).
- If Fail:
- Increment retry count.
- If retries < max:
ZADD delayed <timestamp> <job_id>.
- Else:
LPUSH dlq <job_id>.
- Step 3:
scheduler() (The Delayed Job Mover)
- Loop every second.
ZRANGEBYSCORE delayed 0 <now>.
- For each item,
LMOVE back to appropriate priority queue. (Wait, we need to remember the priority). The payload needs to store the original priority.
This looks solid. I will produce the Python script.
This is a complete design and implementation of an Async Job Platform in Python using asyncio and Redis.
Architecture Overview
- Priorities: Implemented using multiple Redis Lists (one per priority level). The worker checks high-priority queues before low-priority ones.
- Idempotency: Uses a unique
idempotency_key. We check a Redis Set to see if this key is currently processing or completed within a retention window.
- Deduplication: Handled by the Idempotency logic (prevents double processing).
- Retries: Jobs that fail are increment a
retry_count. If under the limit, they are scheduled for a future execution (using a Redis Sorted Set as a delay buffer).
- DLQs (Dead Letter Queues): If a job exceeds its retry limit, it is moved to a specific
dlq list for manual inspection.
Prerequisites
You need a running Redis instance and the python library:
pip install redis
The Implementation
import asyncio
import json
import time
import uuid
import random
from redis.asyncio import Redis
from enum import Enum
# --- Configuration ---
REDIS_URL = "redis://localhost:6379"
MAX_RETRIES = 3
RETRY_DELAY_SECONDS = 5
IDEMPOTENCY_TTL_SECONDS = 3600 # Keep keys for 1 hour
class Priority(Enum):
HIGH = 1
MEDIUM = 2
LOW = 3
class JobStatus(Enum):
PENDING = "pending"
RUNNING = "running"
SUCCESS = "success"
FAILED = "failed"
RETRYING = "retrying"
# --- The Platform Core ---
class AsyncJobPlatform:
def __init__(self, redis_client: Redis):
self.redis = redis_client
# Lua script for atomic idempotency check and enqueue
self.lua_enqueue = """
local idempotency_key = KEYS[1]
local job_data_key = KEYS[2]
local queue_key = KEYS[3]
-- Check if key exists
if redis.call("EXISTS", idempotency_key) == 1 then
return {0, redis.call("GET", idempotency_key)} -- Return existing job ID
end
-- Set idempotency key (Value: Job ID)
redis.call("SET", idempotency_key, ARGV[1], "EX", ARGV[2])
-- Store job payload
redis.call("HSET", job_data_key, ARGV[1], ARGV[3])
-- Push to queue
redis.call("RPUSH", queue_key, ARGV[1])
return {1, ARGV[1]} -- Success, new Job ID
"""
async def submit_job(self, task_name: str, payload: dict, priority: Priority, idempotency_key: str = None):
"""
Submits a job with specific priority and idempotency guarantees.
"""
if not idempotency_key:
idempotency_key = str(uuid.uuid4())
job_id = str(uuid.uuid4())
queue_name = f"queue:{priority.name.lower()}"
idem_redis_key = f"idem:{idempotency_key}"
job_data_key = f"job_data:{job_id}"
job_payload = {
"id": job_id,
"task": task_name,
"params": payload,
"status": JobStatus.PENDING.value,
"retries": 0,
"created_at": time.time()
}
# Execute atomic submission
# KEYS: [idempotency_key, job_data_key, queue_name]
# ARGS: [job_id, ttl, json_payload]
res = await self.redis.eval(
self.lua_enqueue,
3,
idem_redis_key,
job_data_key, # Note: In a real app, job data might be stored in a single hash namespace
queue_name,
job_id,
IDEMPOTENCY_TTL_SECONDS,
json.dumps(job_payload)
)
# The script above was slightly pseudo-code for brevity.
# Let's do the Python-side logic for clarity in this example,
# but note that for strict dedup, Lua is required to avoid race conditions.
# --- Strict Implementation Logic ---
async with self.redis.client() as conn:
# Check Idempotency
existing = await conn.get(f"idem:{idempotency_key}")
if existing:
print(f"[Submit] Job for key {idempotency_key} already exists (ID: {existing.decode()}). Deduplicating.")
return existing.decode()
# Create Job
await conn.set(f"idem:{idempotency_key}", job_id, ex=IDEMPOTENCY_TTL_SECONDS)
await conn.hset("jobs", job_id, json.dumps(job_payload))
await conn.rpush(queue_name, job_id)
print(f"[Submit] New Job {job_id} submitted to {queue_name} with key {idempotency_key}")
return job_id
async def _get_next_job(self):
"""
Priority Queue Logic:
Checks HIGH, then MEDIUM, then LOW using Blocking Pop.
"""
# BLPOP takes a list of keys. It returns (key, value).
# We order keys by priority.
queues = [
f"queue:{Priority.HIGH.name.lower()}",
f"queue:{Priority.MEDIUM.name.lower()}",
f"queue:{Priority.LOW.name.lower()}"
]
# Timeout 0 means wait indefinitely
result = await self.redis.blpop(queues, timeout=5)
if not result:
return None, None
queue_name, job_id = result
return queue_name.decode(), job_id.decode()
async def process_job(self, job_id: str):
"""
Simulates job processing. Handles Retries and DLQ.
"""
job_raw = await self.redis.hget("jobs", job_id)
if not job_raw:
print(f"[Worker] Job {job_id} data missing!")
return
job = json.loads(job_raw)
print(f"[Worker] Processing Job {job_id} (Task: {job['task']}) - Attempt {job['retries'] + 1}")
# Mark as Running
job['status'] = JobStatus.RUNNING.value
await self.redis.hset("jobs", job_id, json.dumps(job))
try:
# --- SIMULATE TASK EXECUTION ---
# 70% chance of success, 30% failure for demo purposes
if random.random() < 0.7:
print(f"[Worker] Job {job_id} SUCCESS")
job['status'] = JobStatus.SUCCESS.value
# Clean up idempotency key if you want to allow re-submission immediately after success,
# or keep it to prevent double submission within the TTL window.
# Here we keep it to honor the TTL dedup.
await self.redis.hset("jobs", job_id, json.dumps(job))
else:
raise ValueError("Simulated processing error")
except Exception as e:
print(f"[Worker] Job {job_id} FAILED: {e}")
job['retries'] += 1
if job['retries'] >= MAX_RETRIES:
# Move to DLQ
print(f"[Worker] Job {job_id} exceeded max retries. Moving to DLQ.")
job['status'] = JobStatus.FAILED.value
await self.redis.hset("jobs", job_id, json.dumps(job))
await self.redis.rpush("queue:dlq", job_id)
else:
# Schedule Retry
print(f"[Worker] Retrying Job {job_id} in {RETRY_DELAY_SECONDS}s...")
job['status'] = JobStatus.RETRYING.value
await self.redis.hset("jobs", job_id, json.dumps(job))
# Add to Delayed Queue (Sorted Set) with score = execution time
execute_at = time.time() + RETRY_DELAY_SECONDS
await self.redis.zadd("queue:delayed", {job_id: execute_at})
async def start_delay_manager(self):
"""
Moves jobs from 'delayed' queue to active queues when time expires.
"""
while True:
now = time.time()
# Get jobs ready to be executed
jobs = await self.redis.zrangebyscore("queue:delayed", 0, now)
for job_id in jobs:
# Determine original priority (In a real app, store this in the job payload or use a default)
# Here we default to MEDIUM for retries for simplicity.
target_queue = f"queue:{Priority.MEDIUM.name.lower()}"
await self.redis.zrem("queue:delayed", job_id)
await self.redis.rpush(target_queue, job_id)
print(f"[DelayMgr] Moved {job_id.decode()} back to active queue.")
await asyncio.sleep(1)
async def start_worker(self):
"""
Main worker loop.
"""
print("[Worker] Started...")
while True:
queue_name, job_id = await self._get_next_job()
if job_id:
# In a real prod app, you might spawn a new task here: asyncio.create_task(self.process_job(job_id))
await self.process_job(job_id)
# --- Usage Demo ---
async def main():
redis = Redis.from_url(REDIS_URL, decode_responses=False)
await redis.flushdb() # Clean slate
platform = AsyncJobPlatform(redis)
# 1. Submit Jobs
print("--- Submitting Jobs ---")
await platform.submit_job("send_email", {"to": "alice@example.com"}, Priority.HIGH, "req-123")
# Idempotency Test: Try submitting the exact same request again
await platform.submit_job("send_email", {"to": "alice@example.com"}, Priority.HIGH, "req-123")
# Low priority job
await platform.submit_job("generate_report", {"type": "pdf"}, Priority.LOW, "req-456")
# Job that will fail and retry (simulated)
# We force the random seed later to ensure failure if needed, or just rely on probability.
# 2. Start Background Services
# In a real app, these would be separate processes.
worker_task = asyncio.create_task(platform.start_worker())
delay_mgr_task = asyncio.create_task(platform.start_delay_manager())
# Let them run for a bit
await asyncio.sleep(10)
worker_task.cancel()
delay_mgr_task.cancel()
await redis.close()
if __name__ == "__main__":
asyncio.run(main())
Key Concepts in the Code
1. Prioritization
We use separate Redis Lists (queue:high, queue:medium, queue:low).
In _get_next_job, we pass the list of queue names to BLPOP in order of priority. Redis guarantees that it will check the first key before the second, effectively implementing a strict priority queue.
2. Idempotency
Before creating a job, we check SET idem:{key}.
- Scenario A (New Job): The key doesn't exist. We set it (with a TTL) and create the job.
- Scenario B (Duplicate): The key exists. We return the existing Job ID immediately without creating a new task or queue entry. This handles network retries safely.
3. Deduplication
This is functionally identical to Idempotency in this context. If the system attempts to process the same logical request twice (e.g., "Pay Invoice #5"), the idempotency key prevents a second job from being queued.
4. Retries & Delayed Execution
When a job fails, we don't put it back into the immediate queue (which would cause a tight loop of failing jobs, blocking other work).
Instead, we add it to a Sorted Set (queue:delayed).
- Score: The Unix timestamp when the job should be retried.
- Delay Manager: A background loop checks if the current time > score. If so, it moves the job ID back to the active list.
5. Dead Letter Queue (DLQ)
If job.retries >= MAX_RETRIES, we give up. We push the Job ID to queue:dlq.
In a production system, you would have a separate monitor reading from queue:dlq to alert developers or allow manual re-triggering.