Skip to content

Queuing - Message Queues and Asynchronous Communication

Message Queues (MQ) are a form of asynchronous communication used to enable distributed systems to communicate and process tasks efficiently. Queues help decouple components, improve scalability, and enhance fault tolerance.


Producer

Sends messages to the queue.

Consumer

Receives and processes messages from the queue.

Broker

Manages the queue and ensures messages are delivered to consumers.

Message

The data sent from the producer to the consumer.


  • Asynchronous Processing: Offload long-running tasks to background workers.
  • Decoupling: Separate components so they can evolve independently.
  • Load Leveling: Smooth out spikes in traffic by buffering requests.
  • Fault Tolerance: Ensure messages are not lost if a component fails.

# Producer
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='', routing_key='hello', body='Hello, RabbitMQ!')
print(" [x] Sent 'Hello, RabbitMQ!'")
connection.close()
# Consumer
import pika
def callback(ch, method, properties, body):
print(f" [x] Received {body}")
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()



ProsCons
Decouples components and improves scalabilityAdds complexity to the system
Enhances fault tolerance and reliabilityRequires additional infrastructure
Enables asynchronous processingCan introduce latency

  • Set up a simple queue system like RabbitMQ or Redis.
  • Experiment with producing and consuming messages in your preferred language.