Building Idempotent Celery Tasks in Django
Learn how to build idempotent Celery tasks in Django: atomic claims, unique constraints, idempotency keys, upserts, external API keys, and tests that prove it.
Introduction
If you run Celery in production long enough, a task will run twice. Maybe a worker crashed halfway and the broker redelivered the message. Maybe a retry repeated work that had already partly succeeded. Maybe a user double-clicked, or a webhook arrived twice. You did not write a bug, and you cannot fully prevent it. Celery's delivery model is closer to "at least once" than "exactly once".
The only reliable answer is to build tasks that are idempotent: running them twice, or five times, leaves the system in the same state as running them once.
This guide focuses on how to design and test idempotent Celery tasks in Django. It covers the core patterns, from simple to advanced, with code you can adapt, plus the traps that catch even experienced teams.
What Idempotent Actually Means
A task is idempotent if the final state is the same no matter how many times it runs with the same input. It does not mean the task does nothing the second time. It means the second run does not cause additional effects.
## Not idempotent: each run adds 10 more
Wallet.objects.filter(user_id=user_id).update(balance=F("balance") + 10)
## Idempotent: every run produces the same final state
Order.objects.filter(pk=order_id).update(total=calculate_total(order_id))
Two clarifications help avoid confusion:
- Idempotent is not the same as "safe to retry". A task can be safe to retry because it is idempotent, but a task that never changes anything (a read-only report) is trivially safe and not really the problem.
- Idempotency is about effects, not about execution. The code may well run twice. What matters is that the outcome is the same as running once.
Why You Can't Rely on "Exactly Once"
Duplicates come from several places, and each one is normal behavior:
acks_late=Trueand worker crashes. The task is acknowledged only after it finishes, so a dead worker's task is redelivered.- Retries. A task that fails after a side effect repeats that side effect.
- Redis visibility timeout. An unacknowledged message becomes visible again after the timeout, so a long task or long ETA can be delivered twice.
- Duplicate triggers. Double submits, repeated webhooks, and client retries queue the same task twice.
- Celery Beat mistakes. Overlapping runs or more than one Beat process queue tasks multiple times.
Because you cannot remove all of these, you design for them. If you want a deeper look at the causes, see the related reading section below.
Pattern 1: Set State, Don't Change It
The simplest and most powerful idea: make the task compute an absolute value from source data instead of applying a relative change.
| Relative (risky) | Absolute (safe) |
|---|---|
balance = balance + 10 |
balance = sum(ledger entries) |
count += 1 |
count = Items.filter(...).count() |
| Append to a list | Rebuild the list from source |
| "Add tag X" blindly | "Ensure tag X exists" |
@shared_task
def refresh_order_total(order_id):
order = Order.objects.get(pk=order_id)
order.total = sum(i.price * i.quantity for i in order.items.all())
order.save(update_fields=["total"])
Run it once or ten times, and the total is the same. When you can model the work this way, you often need nothing else.
For money, prefer a ledger: insert immutable entries, and derive the balance from them. Combine that with a unique key on each entry (below), and duplicate credits become impossible.
Pattern 2: Atomic Claim with a Conditional UPDATE
Many tasks follow "check status, do work, update status". The danger is that two copies both read pending before either writes, and both proceed. The fix is to make the check and the change a single atomic database operation:
Free tech newsletter
FreeFree to join — no card, no paywall. Weekly AI, cloud & tooling insights.
from django.utils import timezone
@shared_task(bind=True, acks_late=True)
def generate_invoice(self, order_id):
claimed = Order.objects.filter(
pk=order_id, invoice_status="pending"
).update(invoice_status="processing", invoice_claimed_at=timezone.now())
if not claimed:
return "skipped: already claimed or done"
try:
build_and_store_invoice(order_id)
except Exception:
Order.objects.filter(pk=order_id, invoice_status="processing").update(
invoice_status="pending"
)
raise
Order.objects.filter(pk=order_id).update(invoice_status="done")
update() returns the number of rows changed. Only one concurrent task can move the row from pending to processing, because the database applies the WHERE and the change together. Every other copy gets 0 and exits.
This is a form of compare-and-set, and it is one of the most useful tools in a Celery codebase. A few cautions:
- Handle stuck claims. If a worker dies while the status is
processing, nothing resets it. Store a claim timestamp and run a small periodic job that resets claims older than a safe threshold. Choose the threshold longer than the task's worst-case runtime, since resetting too early allows a genuine duplicate. - Reset on failure. In the example, a failure puts the row back to
pendingso a retry can claim it again. - Use a real state machine. Statuses like
pending,processing,done, andfailedmake behavior explicit, and also give you something to show in an admin page.
Pattern 3: Let the Database Enforce Uniqueness
Application-level checks can race. A unique constraint cannot. It turns "create this twice" into one success and one harmless failure.
class Payout(models.Model):
order = models.OneToOneField("Order", on_delete=models.PROTECT)
amount = models.DecimalField(max_digits=10, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
from django.db import IntegrityError, transaction
@shared_task
def create_payout(order_id):
order = Order.objects.get(pk=order_id)
try:
with transaction.atomic():
Payout.objects.create(order=order, amount=order.total)
except IntegrityError:
return # a payout already exists; this run is a duplicate
Django gives you several tools on top of this idea:
## Create or fetch: safe under concurrency when a unique constraint exists
obj, created = Subscription.objects.get_or_create(user_id=uid, plan_id=pid)
## Upsert with new values
Metric.objects.update_or_create(
day=day, name="signups", defaults={"value": value}
)
## Bulk insert that skips duplicates
Event.objects.bulk_create(events, ignore_conflicts=True)
## Bulk upsert (Django 4.1+, supported on PostgreSQL)
Event.objects.bulk_create(
events,
update_conflicts=True,
unique_fields=["external_id"],
update_fields=["status", "updated_at"],
)
get_or_create() and update_or_create() are only safe against races when a unique constraint backs them. Without one, two concurrent calls can both create rows. Add the constraint first, then rely on the helper.
Pattern 4: Idempotency Keys for Outside Events
When the duplicate comes from outside, such as a webhook or an API retry, use the event's own unique ID as the idempotency key, and record it in the same transaction as the change:
class ProcessedEvent(models.Model):
event_id = models.CharField(max_length=200, unique=True)
processed_at = models.DateTimeField(auto_now_add=True)
@shared_task
def handle_payment_webhook(event_id, payload):
try:
with transaction.atomic():
ProcessedEvent.objects.create(event_id=event_id)
apply_payment(payload)
except IntegrityError:
return # already handled
The ordering inside the transaction is what makes this correct:
- If
apply_paymentfails, the transaction rolls back and the key goes with it, so a retry can succeed. - If the event was already processed, the unique key fails and the work is skipped.
- Both the key and the business change commit together or not at all.
Make sure the key identifies the event, not the attempt. A random UUID generated inside the task is useless, since each retry would create a new one.
Pattern 5: Deterministic Keys for Your Own Triggers
When your own code queues a task, derive the key from the business identity of the work, not from random values or timestamps:
## Good: the same logical work always has the same key
key = f"invoice:{order.pk}"
key = f"daily-report:{company_id}:{report_date.isoformat()}"
## Bad: a new key on every attempt defeats the purpose
key = str(uuid.uuid4())
key = f"report:{timezone.now()}"
This leads to an important rule for scheduled work: pass the logical date as an argument, instead of calling timezone.now() inside the task. A report task that receives report_date can be re-run safely for that date. A task that computes "today" on each run gives different results depending on when the retry happens, and can quietly double-count or skip data around midnight.
Free tech newsletter
FreeFree to join — no card, no paywall. Weekly AI, cloud & tooling insights.
Pattern 6: Serialize Concurrent Updates with select_for_update
When two tasks might modify the same row at the same time, lock it:
@shared_task
def apply_discount(order_id, coupon_id):
with transaction.atomic():
order = Order.objects.select_for_update().get(pk=order_id)
if order.coupon_id == coupon_id:
return # already applied
order.coupon_id = coupon_id
order.total = recalc(order)
order.save()
The second task waits for the first to commit, then sees the updated state and exits at the early check. Keep the locked section short, and always lock rows in a consistent order across tasks to avoid deadlocks. select_for_update() only works inside transaction.atomic().
Pattern 7: Side Effects That Can't Be Rolled Back
Emails, SMS, payments, and webhooks to other systems are the hard part, because you cannot roll them back with a database transaction. There is a small window where the effect has happened, but your record of it has not been saved yet. If the worker dies in that window, the retry repeats the effect.
You cannot close this window completely on your own, but you can shrink it and choose which failure you prefer:
- Use the provider's idempotency key. Many payment and email APIs accept an idempotency key. Send the same deterministic key on every attempt, so the provider deduplicates for you. This is the best option when it exists.
response = requests.post(
PAYMENTS_URL,
json={"amount": str(order.total)},
headers={"Idempotency-Key": f"order-{order.pk}"},
timeout=10,
)
- Claim before you send. Use the atomic claim from Pattern 2: move the row to
sending, send, then marksent. This prevents concurrent duplicates. - Decide between at-most-once and at-least-once. If you mark
sentbefore sending, a crash loses the message. If you marksentafter, a crash can duplicate it. For payments, prefer providers with idempotency keys and treat duplicates as unacceptable. For low-stakes notifications, a rare duplicate email is often better than a lost one, so claim, send, then mark. - Send after commit. Queue tasks with
transaction.on_commit()so a task never runs against data that has not been saved yet:
def place_order(request):
with transaction.atomic():
order = Order.objects.create(...)
transaction.on_commit(lambda: send_confirmation.delay(order.pk))
For a stricter guarantee between the database and your queue, teams use the outbox pattern: write the intended message into an Outbox table in the same transaction as the business change, and let a separate worker publish and mark those rows. It takes more code, but it removes the gap between "data saved" and "message queued".
Pattern 8: Design Your Task Arguments for Idempotency
How you shape the task signature makes idempotency easier or harder.
- Pass identifiers, not state.
process_order.delay(order.pk)lets the task read fresh data. Passing a serialized order object can act on stale values during a retry. - Keep arguments stable. If a retry would receive different arguments from the original, you cannot reason about duplicates.
- Make chunk tasks range-based. A task that processes
idfrom 1,000 to 2,999 can be re-run safely, because it recomputes the same rows with the same inputs. This is also how large jobs stay restartable. - Avoid hidden inputs. Reading
timezone.now(), random numbers, or mutable global config inside the task makes two runs differ. Pass what matters as arguments.
Don't Forget to Test It
An idempotency bug stays invisible until production. Test it deliberately.
Run the task twice and compare state:
def test_generate_invoice_is_idempotent(db):
order = OrderFactory(invoice_status="pending")
generate_invoice.apply(args=[order.pk], throw=True)
first = snapshot(order)
generate_invoice.apply(args=[order.pk], throw=True)
second = snapshot(order)
assert first == second
assert Invoice.objects.filter(order=order).count() == 1
Simulate a crash in the middle, by mocking a call to raise, running the task, then running it again and checking the final state:
def test_recovers_after_partial_failure(db, mocker):
order = OrderFactory(invoice_status="pending")
mocker.patch("billing.tasks.build_and_store_invoice", side_effect=RuntimeError)
with pytest.raises(RuntimeError):
generate_invoice.apply(args=[order.pk], throw=True)
mocker.stopall()
generate_invoice.apply(args=[order.pk], throw=True)
order.refresh_from_db()
assert order.invoice_status == "done"
Test concurrency for critical paths. Races only show up with real parallelism. Use pytest.mark.django_db(transaction=True) with threads, or a small script that runs the task in parallel against a test database, and assert that exactly one effect happened. Remember that the default test transaction wrapper does not reproduce commit-time behavior, so tests of unique constraints and select_for_update need transaction=True.
Common Mistakes to Avoid
- Check-then-act without atomicity. Two copies both pass the check. Use a conditional
update()or a unique constraint. - Relying on
get_or_create()without a unique constraint. It can create duplicates under concurrency. - Incrementing instead of setting. Relative changes double-apply.
- Random or time-based keys. An idempotency key must be the same on every attempt.
- Marking work done before it is done. A crash after the mark loses the work.
- Forgetting stuck claims. A row left in
processingafter a crash blocks the work forever. - Locks as the only protection. A lock stops concurrent runs, but a duplicate that arrives after it is released still runs.
- Using
timezone.now()inside the task for business logic. Pass the logical date instead. - Untested idempotency. If you never run the task twice in a test, you do not know that it works.
Which Pattern Should You Use?
| Situation | Best pattern |
|---|---|
| Computing a value from source data | Set absolute state |
| Status-driven workflow (pending → done) | Atomic claim with conditional update() |
| Create something exactly once | Unique constraint + IntegrityError handling or get_or_create() |
| Webhooks and API retries | Idempotency key stored in the same transaction |
| Concurrent updates to one row | select_for_update() |
| Money, payments, external APIs | Provider idempotency key + deterministic key |
| Expensive job that must not overlap | Lock with a timeout, plus an idempotent body |
| Scheduled and reporting jobs | Pass the logical date as an argument |
| Message must follow a DB change reliably | transaction.on_commit() or the outbox pattern |
In practice, combine them: an idempotent design as the foundation, a database constraint as the safety net, and a claim or lock only where you need to avoid wasted work.
Free tech newsletter
FreeFree to join — no card, no paywall. Weekly AI, cloud & tooling insights.
Related Reading: Make Your Celery Stack Reliable End to End
Idempotency is the foundation, and these guides cover the layers around it:
- If you want to understand where duplicates come from: Celery: How to Prevent Duplicate Task Execution covers redelivery, the Redis visibility timeout, retries, and Beat, along with locks and idempotency keys.
- If your tasks retry on failure: Celery Retry with Exponential Backoff in Django shows how to retry the right errors with jitter. Retries are only safe when the task is idempotent.
- If you process huge datasets: How to Process Millions of Records Using Celery shows how range-based chunks make a big job restartable, which depends on idempotent chunk tasks.
- If you want the Django-specific version of that pattern: How to Process 5 Million Records with Django and Celery builds a dispatcher and chunk worker on the Django ORM.
- If workers get killed and tasks are redelivered: How to Fix Celery Worker Memory Leaks explains why out-of-memory kills cause reruns, which is exactly what idempotent tasks are built to survive.
- If your tasks open many database connections: Django Database Connection Pooling with PostgreSQL explains how to cap connections across workers, which matters when claims and locks hold transactions open.
- If your claim and lookup queries are slow: Django ORM Optimization for Millions of Records covers the indexes behind fast conditional updates and unique lookups.
A Practical Checklist
Before shipping a Celery task with side effects, confirm that:
- Running it twice produces the same final state
- It sets absolute values instead of applying relative changes
- Status transitions use an atomic conditional
update() - A unique constraint backs every "create once" rule
- Webhooks and external events use a stored idempotency key
- Idempotency keys are deterministic, not random or time-based
- External APIs receive an idempotency key where supported
- Stuck claims are detected and reset safely
- Business dates are passed as arguments, not read from the clock
- The task is queued with
transaction.on_commit() - You tested running it twice, and a crash in the middle
- Critical paths have a concurrency test
Conclusion
You cannot make Celery deliver every task exactly once, but you can make duplicates harmless. Compute state instead of changing it, claim work with an atomic conditional update, let the database enforce uniqueness, and record idempotency keys in the same transaction as the change. For side effects you cannot roll back, use provider idempotency keys and decide deliberately between losing a message and sending it twice.
Then test it by running every important task twice. A task that survives that test also survives worker crashes, retries, redeliveries, and double-clicks, and that is what turns background jobs from a source of late-night incidents into a dependable part of your system.
Frequently Asked Questions
What is an idempotent Celery task? It is a task that leaves the system in the same final state whether it runs once or many times with the same input. For example, setting a field from source data is idempotent, while incrementing a counter is not.
Why do Celery tasks need to be idempotent? Celery can deliver a task more than once because of worker crashes with late acknowledgement, retries, the Redis visibility timeout, duplicate triggers, and Beat misconfiguration. Idempotent tasks make those duplicates harmless.
How do I make a Django Celery task idempotent?
Compute values from source data instead of incrementing them, use an atomic conditional update() to claim work, rely on unique constraints with get_or_create() or update_or_create(), store idempotency keys for external events, and pass identifiers and logical dates as arguments.
Is get_or_create() safe for idempotent tasks?
Only when a unique constraint backs it. Without a database-level constraint, two concurrent calls can both create rows. Add the constraint first, then rely on the helper and handle IntegrityError in edge cases.
What is an idempotency key and how should I generate it?
It is a unique identifier for a logical operation, stored so repeat attempts can be detected. It must be the same on every attempt, so derive it from the business identity, such as an event ID or order-123, and never from random values or timestamps.
Does a lock make a Celery task idempotent? No. A lock only stops concurrent runs. If the lock expires or the task finishes and a duplicate arrives later, it runs again. Combine locks with idempotent logic and database constraints.
How do I test that a Celery task is idempotent?
Run the task twice with the same arguments and assert that the final state is identical, simulate a failure in the middle and run it again, and for critical paths run it concurrently with transaction=True tests to confirm that only one effect happens.
