Idempotent Job Processing Implementation
I'll guide you through a robust, production-ready implementation of idempotent job processing. This covers:
- Deduplication (dedup keys): Unique keys per job to skip duplicates.
- Outbox pattern: Reliable event publishing from producers (transactional with DB).
- Inbox pattern: Reliable, idempotent consumption.
- Retry policies with jitter: Exponential backoff + full jitter.
- Poison-message handling: Dead Letter Queue (DLQ) after max retries.
Architecture Overview
Producer App (e.g., Web API)
├── DB Transaction
│ ├── Business logic (e.g., update Order)
│ └── Insert into outbox table (job payload + dedup_key)
└── Relay Service (polls outbox, publishes to Queue, marks sent)
Queue (e.g., RabbitMQ, Kafka, SQS)
├── Main Queue
└── DLQ
Worker (Consumer)
├── Receive from Queue
├── Inbox: Insert to inbox table (dedup)
├── If duplicate: ACK & skip
├── Process job (idempotent handler)
├── On success: Mark inbox done
├── On fail: Retry (backoff + jitter) or DLQ
└── Cleanup inbox (TTL or cron)
Key Assumptions/Tools:
- DB: PostgreSQL (for outbox/inbox tables).
- Queue: RabbitMQ (durable queues, TTL, retries).
- Dedup/Locks: Redis (fast sets, TTL).
- Language: Python 3 (using
pika for RabbitMQ, redis, psycopg2 for DB).
- Jobs are idempotent by design (e.g., use
UPSERT in handlers).
Tables (SQL schema):
-- Outbox (Producer)
CREATE TABLE outbox (
id SERIAL PRIMARY KEY,
dedup_key VARCHAR(255) UNIQUE NOT NULL,
payload JSONB NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
sent_at TIMESTAMP,
attempts INTEGER DEFAULT 0
);
-- Inbox (Consumer)
CREATE TABLE inbox (
id SERIAL PRIMARY KEY,
dedup_key VARCHAR(255) PRIMARY KEY,
payload JSONB NOT NULL,
status VARCHAR(20) DEFAULT 'received', -- received/processing/success/failed
retry_count INTEGER DEFAULT 0,
max_retries INTEGER DEFAULT 5,
next_retry_at TIMESTAMP,
created_at TIMESTAMP DEFAULT NOW()
);
1. Producer: Outbox Pattern
In your app, wrap business logic in a DB tx that inserts to outbox.
import psycopg2
import json
import uuid
from datetime import datetime
def process_order(order_id: int, conn):
dedup_key = f"order:{order_id}:{datetime.utcnow().isoformat()}" # Unique per intent
payload = {"action": "ship_order", "order_id": order_id}
with conn.cursor() as cur:
# Business tx
cur.execute("UPDATE orders SET status='processing' WHERE id=%s", (order_id,))
# Outbox insert (idempotent via UNIQUE constraint)
try:
cur.execute("""
INSERT INTO outbox (dedup_key, payload)
VALUES (%s, %s)
""", (dedup_key, json.dumps(payload)))
except psycopg2.errors.UniqueViolation:
pass # Already queued, idempotent
conn.commit()
Relay Service (separate process, polls outbox every 5s):
import pika
import time
import json
def relay_outbox():
conn = psycopg2.connect(...) # Your DB conn
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='jobs', durable=True)
while True:
with conn.cursor() as cur:
cur.execute("""
UPDATE outbox
SET sent_at=NOW(), attempts=attempts+1
WHERE sent_at IS NULL AND attempts < 3
RETURNING id, dedup_key, payload
""")
rows = cur.fetchall()
for row in rows:
_, dedup_key, payload = row
channel.basic_publish(
exchange='',
routing_key='jobs',
body=json.dumps({"dedup_key": dedup_key, **payload}).encode(),
properties=pika.BasicProperties(
delivery_mode=2, # Persistent
headers={'dedup_key': dedup_key}
)
)
conn.commit()
time.sleep(5)
2. Consumer: Worker with Inbox, Dedup, Retries, Poison
Main worker logic:
import pika
import redis
import psycopg2
import json
import time
import random
from datetime import datetime, timedelta
r = redis.Redis(host='localhost', port=6379, db=0)
conn = psycopg2.connect(...) # DB conn
# Retry policy: Exponential backoff + full jitter
# delay = min(base * 2 ** retry_count + random.uniform(0, base * 2 ** retry_count), max_delay)
MAX_RETRIES = 5
BASE_DELAY = 1 # seconds
MAX_DELAY = 300 # 5min
def calculate_next_retry(retry_count):
backoff = BASE_DELAY * (2 ** retry_count)
jitter = random.uniform(0, backoff)
return backoff + jitter
def process_job(payload: dict):
"""Your idempotent handler (e.g., UPSERT to DB, no side-effects on dup)."""
order_id = payload['order_id']
with conn.cursor() as cur:
# Idempotent: UPSERT
cur.execute("""
INSERT INTO shipments (order_id, status)
VALUES (%s, 'shipped')
ON CONFLICT (order_id) DO UPDATE SET status='shipped'
""", (order_id,))
conn.commit()
print(f"Processed order {order_id}")
def worker():
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='jobs', durable=True)
channel.queue_declare(queue='dlq', durable=True) # Poison queue
channel.queue_bind(queue='jobs', exchange='dlq_x', routing_key='poison') # Auto-DLQ setup below
def callback(ch, method, properties, body):
payload = json.loads(body)
dedup_key = payload.pop('dedup_key')
# FAST DEDUP CHECK (Redis, TTL=1hr)
if r.sismember('processed_jobs', dedup_key):
ch.basic_ack(delivery_tag=method.delivery_tag)
return
# Inbox: Atomic insert (dedup via PK)
try:
with conn.cursor() as cur:
cur.execute("""
INSERT INTO inbox (dedup_key, payload)
VALUES (%s, %s)
ON CONFLICT (dedup_key) DO NOTHING
RETURNING retry_count, status
""", (dedup_key, json.dumps(payload)))
row = cur.fetchone()
if not row: # Already processed
r.sadd('processed_jobs', dedup_key)
r.expire(dedup_key, 3600) # TTL
ch.basic_ack(delivery_tag=method.delivery_tag)
return
retry_count, status = row
conn.commit()
except Exception:
conn.rollback()
raise
# Process
try:
process_job(payload)
with conn.cursor() as cur:
cur.execute("""
UPDATE inbox SET status='success' WHERE dedup_key=%s
""", (dedup_key,))
conn.commit()
r.sadd('processed_jobs', dedup_key)
r.expire(dedup_key, 3600)
ch.basic_ack(delivery_tag=method.delivery_tag)
except Exception as e:
with conn.cursor() as cur:
retry_count += 1
if retry_count >= MAX_RETRIES:
# Poison: Move to DLQ
cur.execute("UPDATE inbox SET status='failed' WHERE dedup_key=%s", (dedup_key,))
ch.basic_reject(delivery_tag=method.delivery_tag, requeue=False)
# RabbitMQ auto-DLQs if TTL policy set on queue
else:
next_retry = datetime.utcnow() + timedelta(seconds=calculate_next_retry(retry_count))
cur.execute("""
UPDATE inbox SET retry_count=%s, next_retry_at=%s, status='failed'
WHERE dedup_key=%s
""", (retry_count, next_retry, dedup_key))
conn.commit()
ch.basic_reject(delivery_tag=method.delivery_tag, requeue=True) # Retry
conn.rollback()
raise # Log error
channel.basic_qos(prefetch_count=1) # Fair dispatch
channel.basic_consume(queue='jobs', on_message_callback=callback)
channel.start_consuming()
RabbitMQ Setup for Retries/DLQ (via policy):
# Declare queues with x-dead-letter-exchange
rabbitmqadmin declare queue name=jobs durable=true \
arguments='{"x-dead-letter-exchange":"dlq_x","x-message-ttl":60000}' # 1min TTL for retry
rabbitmqadmin declare exchange name=dlq_x type=direct
rabbitmqadmin declare queue name=dlq durable=true
rabbitmqadmin declare binding source=dlq_x destination=dlq routing_key=poison
Additional Features
- Cleanup Cron: Delete old inbox/outbox rows (
DELETE WHERE created_at < NOW() - INTERVAL '7 days').
- Monitoring: Track metrics (Prometheus: jobs_processed, retries, dlq_size).
- Scaling: Multiple workers (Redis dedup prevents double-process).
- Distributed Locks: For critical sections, use
redlock-py.
- Testing: Inject duplicates by re-publishing same dedup_key.
This setup ensures exactly-once semantics (or at-least-once with idempotency). Deploy relay/worker as services (e.g., Docker + Supervisor). For Kafka/SQS, adapt publishers/consumers similarly.
Questions? Need tweaks for your stack (e.g., Node.js, Go)? Let me know! 🕵️