# How to auto-delete unused queues in LavinMQ

By Hailay Gebremeskel. Published 31 July 2025.

## How to auto-delete unused queues in LavinMQ

Unused queues can clutter your broker and degrade performance over time. This happens where queues are most often created for short-term use. For example, in Remote Procedure Call (RPC), autoscaled microservices, or IoT device networks.

Over time, these queues can become unused for various reasons. For example, when a client disconnects, a microservice scales down, or an IoT device goes offline. If not cleaned up, these unused queues can add unnecessary overhead.

In LavinMQ, it is possible to auto-delete unused queues. This helps to keep your messaging system clean and efficient.

There are several ways to auto-delete a queue in LavinMQ. Each method serves different use cases and has its own cleanup behavior. This tutorial walks through each method one by one.

## 1. Use `auto_delete=True`

Setting `auto_delete=True` when declaring a queue deletes it when the last consumer unsubscribes.

When to use it:

- Short-lived consumers like RPC clients.
- Temporary consumers that do not need persistent queues.

## 2. Use `exclusive=True`

Setting `exclusive=True` ties the queue to a single connection. The queue is deleted as soon as that connection closes.

When to use it:

- Private, per-connection queues.
- Temporary work queues for testing or isolated sessions.

## 3. Set a Queue TTL (`x-expires`)

Use a time-to-live (TTL) policy to delete queues that are inactive for a specific duration.

Set `arguments = {'x-expires': 60000}` when declaring a queue.

Key notes:

- `x-expires` is measured in milliseconds.
- A queue is unused if it has no consumers and no message activity (publishing or consuming).

Here’s a quick Python example that demonstrates all the methods we discussed using the Pika library:

```python
  import os
  import pika

  # Get connection URL from environment or fallback to localhost
  url = os.environ.get('CLOUDAMQP_URL', 'amqp://guest:guest@localhost:5672/%2f')
  params = pika.URLParameters(url)
  connection = pika.BlockingConnection(params)
  channel = connection.channel()

  channel.queue_declare(
  queue='my_temp_queue',    # Replace with your queue name
  exclusive=True,           # Deleted when connection closes
  auto_delete=True,         # Deleted when last consumer unsubscribes
  arguments={'x-expires': 60000}  # Delete after 60 seconds of inactivity
)
```

## Summary

Auto-deleting unused queues helps keep your messaging system clean and maintain optimal performance.

Want to dive deeper into LavinMQ’s powerful messaging features? Check out our [documentation](https://lavinmq.com/documentation/) and start exploring!
