Search code examples
rabbitmqmessage-queueamqp

RabbitMQ - Is there a way to limit the number of messages in a queue?


Is there a way to limit the maximum number of messages a queue can hold in RabbitMQ?

For example, if this number is set to 10 and the current size is 10, the oldest message will be discarded when a new message is pushed to the queue (FIFO).


Solution

  • Yes there is, with the x-max-length attribute:

    Map<String, Object> args = new HashMap<String, Object>();
    args.put("x-max-length", 10);
    channel.queueDeclare("myqueue", false, false, false, args);
    

    You can also achive this by configuring a policy for it with rabbitmqctl:

    rabbitmqctl set_policy Ten ".*" '{"max-length":10}' --apply-to queues
    

    Oldest messages are dropped when new ones come in.

    Details can be found here: https://www.rabbitmq.com/maxlength.html