Here is the uncomfortable question nobody asks about their Celery setup: a worker picks up a task that charges a card, creates a shipment, and sends an email. It charges the card. Then the pod gets OOM-killed. What happens next?
If you are honest, the answer is “I don’t actually know.” Maybe the task retries from the top and charges the card twice. Maybe it does not retry at all because the broker already acked the message. Maybe a human finds it in a dead-letter queue three days later. The task was never one atomic thing. It was three side effects with no memory of which ones already happened.
This is not a Celery bug or a BullMQ bug. It is the fundamental shape of a task queue. A task is a function you run once, somewhere, and hope it finishes. The queue remembers that the task exists. It does not remember how far the task got. The moment your business process is longer than a single idempotent operation, you are hand-rolling a state machine to track progress, and that state machine is where the bugs live.
Temporal attacks the problem from a different direction. It does not give you a better queue. It gives you durable execution: your workflow function runs, and every step it takes is checkpointed to a database before the next step runs. If the process dies, a different worker replays the history, fast-forwards to exactly where you were, and keeps going. The function resumes mid-execution on another machine as if nothing happened. That is the whole pitch, and it is a bigger deal than it sounds.
Where the task queue breaks
Let me make the failure concrete, because “add retries” is the answer most people reach for and it does not fix this.
Here is a reasonable-looking Celery task for a subscription signup:
@app.task(bind=True, max_retries=3)
def onboard_customer(self, user_id):
charge = stripe.charge(user_id, amount=4900) # step 1
account = provision_account(user_id) # step 2
send_welcome_email(user_id) # step 3
mark_onboarded(user_id) # step 4
Now provisioning (step 2) throws a transient error. Celery retries the whole task. It runs stripe.charge again. The customer is charged twice. You reach for idempotency keys on the charge. Fine. Now the worker crashes between step 2 and step 3, after provisioning succeeded. The retry re-runs provisioning, which was not written to be idempotent, and now the customer has two accounts.
The real fix inside a task queue is to make every step idempotent, store a progress marker after each one, and check that marker on entry so retries skip completed steps. You end up writing this:
@app.task(bind=True)
def onboard_customer(self, user_id):
state = load_state(user_id) # read progress from DB
if not state.charged:
charge_idempotent(user_id)
state.charged = True; save(state)
if not state.provisioned:
provision_idempotent(user_id)
state.provisioned = True; save(state)
if not state.emailed:
send_welcome_email(user_id)
state.emailed = True; save(state)
...
That works. It is also a hand-rolled durable execution engine with a progress table, bolted onto a system that was supposed to save you from writing it. Every new workflow gets its own bespoke copy. The progress schema, the “check then do” dance, the compensation logic when a late step fails permanently: all of it is reinvented per task, and all of it is subtly wrong the first few times. This is the exact code Temporal deletes.
The durable execution model
Temporal splits your code into two kinds of things, and understanding the split is the whole game.
A workflow is your orchestration logic. It decides what happens in what order. It is the function above, minus the progress bookkeeping. Workflow code must be deterministic, because Temporal reconstructs its state by replaying it: given the same event history, the same code must make the same decisions. That determinism requirement is why you cannot call requests.get, read the clock, or generate a random UUID directly inside a workflow. Those are non-deterministic, and a replay would diverge from the original run.
An activity is a single unit of side-effecting work: charge the card, call an API, write to a database, send an email. Activities are plain functions with no determinism constraint. They can do anything. Temporal records the result of each activity in the workflow’s history, so on replay it does not re-run the activity, it just hands back the recorded result.
That is the key mechanic. Replay re-runs your workflow code but short-circuits every activity that already completed by returning its stored result. So the workflow fast-forwards through everything it already did, in memory, in milliseconds, and arrives at the first thing it had not yet done.
Temporal Service (durable event history, backed by a DB)
^ |
append events | | deliver tasks
| v
+----------------------+-------------------------+----------------+
| Worker process(es) |
| |
| Workflow code (deterministic) Activity code (side effects) |
| - decides order - charge card |
| - calls activities - call API |
| - handles retries/timeouts - write DB |
+-----------------------------------------------------------------+
The same workflow in Temporal looks like this:
from temporalio import workflow
from datetime import timedelta
@workflow.defn
class OnboardCustomer:
@workflow.run
async def run(self, user_id: str) -> None:
await workflow.execute_activity(
charge_subscription, user_id,
start_to_close_timeout=timedelta(seconds=30),
)
await workflow.execute_activity(
provision_account, user_id,
start_to_close_timeout=timedelta(seconds=60),
)
await workflow.execute_activity(
send_welcome_email, user_id,
start_to_close_timeout=timedelta(seconds=30),
)
await workflow.execute_activity(
mark_onboarded, user_id,
start_to_close_timeout=timedelta(seconds=10),
)
There is no progress table. There is no “if not state.charged” guard. If the worker dies after provision_account completes, a replacement worker replays the history, sees that charge and provision already returned, skips straight past them, and calls send_welcome_email. The code reads like a plain sequential function because, from your point of view, it is one. Temporal supplies the durability underneath.
The activities themselves are ordinary:
from temporalio import activity
@activity.defn
async def charge_subscription(user_id: str) -> str:
# runs at-least-once; use an idempotency key keyed on the
# workflow run so a retried activity does not double-charge
key = activity.info().workflow_run_id
return await stripe.charge(user_id, amount=4900, idempotency_key=key)
You still want idempotency on activities, because an activity that times out after its side effect committed but before Temporal recorded the result will be retried. But you write it once, per activity, for a clear reason, instead of threading a progress machine through your whole orchestration.
Setting up a worker
A worker is a process you run that hosts workflow and activity code and polls a task queue. This is the part that replaces your Celery worker fleet.
import asyncio
from temporalio.client import Client
from temporalio.worker import Worker
async def main():
client = await Client.connect("temporal:7233", namespace="default")
worker = Worker(
client,
task_queue="onboarding",
workflows=[OnboardCustomer],
activities=[charge_subscription, provision_account,
send_welcome_email, mark_onboarded],
)
await worker.run()
asyncio.run(main())
Starting a workflow from your API is a client call:
client = await Client.connect("temporal:7233")
await client.start_workflow(
OnboardCustomer.run, "user_123",
id="onboard-user_123", # dedup key: one onboarding per user
task_queue="onboarding",
)
That workflow ID is a real dedup guarantee. Start it twice with the same ID and the second call is rejected (configurably), so an API retry cannot kick off two onboardings. Try getting that from a Celery delay().
Deploys matter here too. When you ship new code, old running workflows do not care that the worker restarted. They were checkpointed in the Temporal service, not in worker memory. The new worker picks them up and replays. A deploy that would have dropped in-flight Celery tasks is a non-event.
Retries and timeouts are declarative
The task-queue version of retries is max_retries=3 and a prayer. Temporal makes the retry policy an explicit, per-activity object, and it enforces timeouts the queue cannot.
from temporalio.common import RetryPolicy
await workflow.execute_activity(
call_flaky_vendor, order_id,
start_to_close_timeout=timedelta(seconds=20),
retry_policy=RetryPolicy(
initial_interval=timedelta(seconds=1),
backoff_coefficient=2.0,
maximum_interval=timedelta(seconds=60),
maximum_attempts=0, # 0 = retry forever
non_retryable_error_types=["CardDeclined"],
),
)
Two timeout types are worth knowing. start_to_close_timeout bounds a single attempt. schedule_to_close_timeout bounds the total time across all retries. And a heartbeat_timeout lets a long activity report “still alive” so Temporal can detect a stuck worker in seconds instead of waiting for a long timeout to expire. For a job that processes a million rows, you heartbeat progress, and if the worker dies at row 600k, the retried activity can resume from the last heartbeated checkpoint rather than starting over.
The saga pattern, without the state machine
Now the hard case: a multi-step transaction where a late step fails permanently and you have to undo the earlier ones. Book a trip: reserve a flight, reserve a hotel, charge the card. If the charge is declined, you must cancel the hotel and cancel the flight, in reverse order. This is the saga pattern, and in a task queue it is a miserable hand-written state machine. In Temporal it is a try/except with a compensation stack, because the workflow is just code.
@workflow.defn
class BookTrip:
@workflow.run
async def run(self, req: TripRequest) -> str:
compensations = []
try:
flight = await workflow.execute_activity(
reserve_flight, req, start_to_close_timeout=timedelta(seconds=30))
compensations.append((cancel_flight, flight))
hotel = await workflow.execute_activity(
reserve_hotel, req, start_to_close_timeout=timedelta(seconds=30))
compensations.append((cancel_hotel, hotel))
await workflow.execute_activity(
charge_card, req, start_to_close_timeout=timedelta(seconds=30),
retry_policy=RetryPolicy(non_retryable_error_types=["CardDeclined"]))
return "confirmed"
except Exception:
for undo, handle in reversed(compensations):
await workflow.execute_activity(
undo, handle, start_to_close_timeout=timedelta(seconds=30))
raise
Read that again and notice what is not there. No table tracking which steps completed. No reconciliation job scanning for half-booked trips. No “resume from step 2” logic. The compensations list is an ordinary Python list, and Temporal makes it durable for free, because the whole function is durable. If the worker crashes after the hotel reservation, the replacement replays, rebuilds the exact compensations list from history, and continues. The reversed-order rollback that the generic saga orchestrator needs an entire persistence layer to guarantee is here just reversed(compensations).
That is the deepest point in this whole post. The saga pattern is normally presented as heavy distributed-systems machinery. With durable execution, it collapses into the control flow you would write if crashes did not exist, because the engine makes crashes stop mattering.
Temporal vs the task queue, honestly
Temporal is not a drop-in Celery replacement, and pretending otherwise sets you up to hate it. Here is the real comparison.
| Concern | Celery / BullMQ | Temporal |
|---|---|---|
| Model | Fire a task, hope it finishes | Durable function, resumes after crash |
| Progress state | You build a progress table | Engine checkpoints every step |
| Survives worker crash | Loses in-flight work | Replays and continues |
| Survives deploy | In-flight tasks dropped | In-flight workflows unaffected |
| Multi-step saga | Hand-rolled state machine | try/except with compensations |
| Retries | Basic, per-task | Per-activity policy, multiple timeout types |
| Long-running (days/weeks) | Painful; needs external state | Native; a workflow can sleep for a month |
| Dedup | Not built in | Workflow ID is a dedup key |
| Operational cost | A broker (Redis/RabbitMQ) | A stateful service plus a database |
| Best for | Short, independent, fire-and-forget jobs | Stateful, multi-step business processes |
That last row is the decision. A workflow can literally do await asyncio.sleep(timedelta(days=30)) to wait a month between steps, and that sleep survives every crash and deploy in between, because it is a timer in the durable history, not a thread parked in memory. Try expressing “charge the user, wait 14 days, then charge again unless they cancelled” in Celery and you are back to cron jobs and a status column.
Python or Go, and the operational reality
Temporal ships first-class SDKs for Go, Java, Python, TypeScript, and .NET, and they interoperate: a Go workflow can call a Python activity on another task queue. Go is the most common choice for the workflow tier because it is what Temporal itself is written in and the SDK is the most mature; Python and TypeScript are extremely popular for teams whose activities are already in those languages. Pick the language your side effects live in and you will be fine.
The honest cost is operational. Temporal is a stateful service backed by Cassandra, PostgreSQL, or MySQL, and running it yourself is real work: it is not “apt install a broker.” Temporal Cloud exists precisely so you do not have to, and for most teams the hosted option is the right call until you have a reason not to. Either way, you are adding a meaningful piece of infrastructure, not swapping one Redis for another.
There is also a learning curve that bites early. The determinism constraint on workflow code is non-negotiable and non-obvious: a datetime.now() or a random value or a direct network call inside a workflow is a bug that may only surface on replay. You use workflow.now(), workflow.uuid4(), and you push every side effect into an activity. Once the split clicks it is natural, but the first week you will fight it.
What actually works and what to do
What works: everything the pitch claims. Durable execution is not marketing. A workflow genuinely survives worker crashes, deploys, and network partitions with no extra code from you, and the saga collapse is real. For any process that is multi-step, long-running, must-not-double-execute, and currently held together by a progress table and a reconciliation cron, Temporal deletes a category of bug you have been living with.
What does not: it is overkill for short, stateless, fire-and-forget jobs. If your “background job” is resizing an image or sending one email with no downstream steps, a task queue is simpler and you should keep it. Temporal earns its operational weight only when state and ordering matter. And it is not free to run; budget for Temporal Cloud or for someone who owns the cluster.
What to do: do not rip out Celery across the board. Find the one workflow that keeps you up at night, the payment-plus-provision-plus-notify chain with the hand-rolled progress table and the Sunday reconciliation job, and port that one. You will feel the difference the first time a deploy lands mid-execution and nothing breaks. Then port the next one. The value is concentrated in exactly the workflows where the task queue was never the right tool, and those are the ones you already know by name.
Comments