Celery Tasks
Task Management
Software Development
Python Programming
Debugging

Deleting all pending tasks in Celery (purge the queue)

Codemia Knowledge Hub ·

The fastest way to delete all pending Celery tasks is app.control.purge() (or celery -A myapp purge from a shell), which removes the waiting messages from the broker queue. For finer control, revoke specific tasks by ID or purge individual named queues. The methods differ in how they treat tasks that workers have already fetched or started, so pick based on whether you need a clean slate or selective cancellation.

Where Celery tasks live

StateLocationCan Be Deleted?
Pending (queued)Broker (RabbitMQ, Redis, etc.)Yes, via purge
Reserved (prefetched by worker)Worker memoryYes, via revoke
Active (currently executing)Worker processYes, via revoke with terminate=True
Completed / FailedResult backendNo (already finished)

Purging only removes messages from the broker queue. Tasks a worker has already fetched (reserved) or started (active) need revocation.

Purging from Python

The most common approach, removing pending messages from the default queue:

python
1from celery import Celery
2
3app = Celery('myapp', broker='redis://localhost:6379/0')
4
5# Purge all messages from the default queue
6discarded = app.control.purge()
7print(f"Purged {discarded} messages")

To target a specific queue:

python
1from kombu import Connection
2
3def purge_queue(broker_url, queue_name):
4    """Purge all messages from a specific queue."""
5    with Connection(broker_url) as conn:
6        simple_queue = conn.SimpleQueue(queue_name)
7        count = simple_queue.clear()
8        simple_queue.close()
9        print(f"Purged {count} messages from '{queue_name}'")
10
11purge_queue('redis://localhost:6379/0', 'celery')
12purge_queue('redis://localhost:6379/0', 'high_priority')

With RabbitMQ, you can also purge through the management tooling. This is the classic (v1, Python) rabbitmqadmin syntax:

bash
1# Purge the default 'celery' queue
2rabbitmqadmin purge queue name=celery
3
4# List all queues and their message counts
5rabbitmqadmin list queues name messages

The v2 rabbitmqadmin (rabbitmqadmin-ng) uses subcommands and flags instead: rabbitmqadmin queues purge --name celery and rabbitmqadmin queues list.

Purging with the celery CLI

With shell access, celery purge is the simplest option:

bash
1# Purge the default queue (prompts for confirmation)
2celery -A myapp purge
3
4# Force purge without confirmation
5celery -A myapp purge -f
6
7# Purge specific queues
8celery -A myapp purge -Q high_priority,low_priority

To see what is queued before purging:

bash
1# Show active, reserved, and scheduled tasks
2celery -A myapp inspect active
3celery -A myapp inspect reserved
4celery -A myapp inspect scheduled
5
6# Show worker statistics (pool, prefetch count, task totals)
7celery -A myapp inspect stats

Revoking specific tasks

To cancel particular tasks rather than everything, call revoke with the task ID:

python
1from celery import Celery
2
3app = Celery('myapp', broker='redis://localhost:6379/0')
4
5# Revoke a pending task (workers skip it when it arrives)
6app.control.revoke('task-id-123')
7
8# Revoke and terminate an active task
9app.control.revoke('task-id-456', terminate=True)
10
11# Revoke and terminate with SIGKILL (last resort)
12app.control.revoke('task-id-789', terminate=True, signal='SIGKILL')

Several at once:

python
# Revoke a batch of tasks
task_ids = ['id-1', 'id-2', 'id-3', 'id-4']
app.control.revoke(task_ids)

From the AsyncResult returned when you dispatch a task:

python
result = my_task.delay(arg1, arg2)
# Later, cancel it
result.revoke(terminate=True)

terminate=True sends SIGTERM by default. If the task ignores it (common with subprocess calls or C extensions), escalate to signal='SIGKILL', which prevents cleanup code from running.

Revoking every instance of one task name

Combine inspection with revocation:

python
1def revoke_all_by_name(app, task_name):
2    """Revoke reserved (prefetched) and active instances of a named task.
3
4    Messages still waiting in the broker are not visible to inspect();
5    purge the queue for those.
6    """
7    inspector = app.control.inspect()
8    
9    revoked = 0
10    
11    # Check reserved (prefetched) tasks
12    reserved = inspector.reserved() or {}
13    for worker, tasks in reserved.items():
14        for task in tasks:
15            if task['name'] == task_name:
16                app.control.revoke(task['id'], terminate=True)
17                revoked += 1
18    
19    # Check active (running) tasks
20    active = inspector.active() or {}
21    for worker, tasks in active.items():
22        for task in tasks:
23            if task['name'] == task_name:
24                app.control.revoke(task['id'], terminate=True)
25                revoked += 1
26    
27    print(f"Revoked {revoked} instances of '{task_name}'")
28
29revoke_all_by_name(app, 'myapp.tasks.send_email')

Clearing the broker directly

When Celery commands are unavailable (workers down, or the app cannot connect), work on the broker itself.

For Redis:

bash
1# Delete the default Celery queue key
2redis-cli DEL celery
3
4# With priorities enabled, each priority level is its own key
5redis-cli --scan --pattern 'celery*'
6
7# Delete a named queue
8redis-cli DEL high_priority
9
10# Flush entire Redis database (nuclear option)
11redis-cli FLUSHDB
python
1import redis
2
3r = redis.Redis(host='localhost', port=6379, db=0)
4deleted = r.delete('celery')
5print(f"Deleted queue key: {deleted}")

With the Redis transport, a task sent with a non-zero priority lands in a separate list such as celery\x06\x166 (the queue name, a \x06\x16 separator and the priority step), so DEL celery alone leaves those behind. celery purge clears them too.

FLUSHDB deletes everything in that Redis database. If it also holds cache, sessions or rate limits, all of it is gone, so target the queue keys instead.

For RabbitMQ:

bash
1# Purge via rabbitmqctl
2rabbitmqctl purge_queue celery
3
4# Delete the queue entirely
5rabbitmqctl delete_queue celery

Preventing task buildup

Task expiration

Set an expiration so stale tasks are discarded automatically:

python
1# Per-task expiration
2@app.task(expires=3600)  # Expire after 1 hour
3def send_notification(user_id, message):
4    pass
5
6# Per-call expiration
7send_notification.apply_async(
8    args=[user_id, message],
9    expires=600  # Expire after 10 minutes
10)

Do not confuse expires with countdown. countdown=120 delays execution by 120 seconds, while expires=120 discards the task if it has not started within 120 seconds.

Rate limiting

Stop producers from overwhelming the queue:

python
@app.task(rate_limit='100/m')  # Max 100 executions per minute
def process_webhook(payload):
    pass

Deduplication

Stop two copies of a task from running at the same time with a lock. This does not stop duplicates from being queued; the second copy is still delivered and simply exits early:

python
1from celery import Celery
2import redis
3
4app = Celery('myapp', broker='redis://localhost:6379/0')
5redis_client = redis.Redis()
6
7@app.task(bind=True)
8def deduplicated_task(self, key, *args):
9    lock_key = f"task_lock:{key}"
10    if not redis_client.set(lock_key, self.request.id, nx=True, ex=3600):
11        print(f"Task for {key} already running, skipping")
12        return
13    try:
14        # Do actual work
15        pass
16    finally:
17        redis_client.delete(lock_key)

Monitoring queue depth

Set alerts on queue length (for example with Prometheus and Flower). Finding thousands of stuck tasks after the fact is much harder than preventing the buildup.

Comparing the methods

MethodScopeRequires WorkersSafe for Production
app.control.purge()All queued tasksNoUse with caution
celery purge CLIAll or specific queuesNoUse with caution
app.control.revoke(id)Single taskYes (for active tasks)Yes
Broker flush (Redis/RabbitMQ)All data in brokerNoLast resort only
Task expirationStale tasksNoYes (preventive)

Why tasks keep running after a purge

  • Active tasks are untouched. app.control.purge() only removes broker messages. Tasks workers are executing keep running; use revoke(terminate=True) for them.
  • Prefetched tasks are untouched. Workers prefetch tasks into memory, and purging the queue does not affect them. Restarting the workers after purging does not help either: on shutdown a worker returns its unacknowledged prefetched messages to the queue (it logs Restoring 4 unacknowledged message(s)), so they come back. Revoke them individually, or stop the workers first, then purge, then start the workers again:
bash
1# 1. Stop every worker (systemctl stop celery, supervisorctl stop, or Ctrl+C)
2celery -A myapp control shutdown
3
4# 2. Purge while nothing holds prefetched messages
5celery -A myapp purge -f
6
7# 3. Start the workers again
8celery -A myapp worker --loglevel=INFO

Inspect the queue state with celery inspect before and after purging to confirm the result.


Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design