Acking messages with node-amqp

The documentation for node-amqp is pretty good, but I couldn’t find a good example of how to ack messages once some work has been done:

        var queueOpts = {
            durable: true,
            autoDelete: false
        };
        connection.queue('foo.bar', queueOpts, function (queue) {
            var subscriptionOpts = {
                ack: true,
                prefetchCount: 10
            };
            queue.subscribe(subscriptionOpts, function (message, headers, deliveryInfo, ack) {
                doWork(message).then(function() {
                    ack.acknowledge();
                }).fail(function(err) {
                    ack.reject(true);
                });
            });
        });

Remember, this just returns the message to the queue; so you’d probably want to track the number of attempts at processing it, and use a dead letter queue, to avoid poison messages.

Any messages not acked will be requeued when the connection is closed (you can check for them using the management plugin). Bear in mind that using acknowledgements only guarantees at least once delivery, so make sure your handlers are idempotent!