Dev tools
Message Queue: What It Is and When You Need One
What a message queue is, how it works, delivery guarantees, examples and the main tools, plus when to use message queues and how they differ from pub/sub.
A message queue is a buffer that lets one part of a system send work to another without waiting for it. A producer puts a message on the queue, the queue stores it safely, and a consumer takes it off and processes it when it's ready; each message is normally handled by exactly one consumer. That simple idea decouples services, absorbs traffic spikes and keeps work from being lost when something crashes.
This guide answers what is a message queue in plain terms, shows how one works step by step, explains delivery guarantees, walks through message queue examples with real numbers, compares the main tools, and covers when to use message queues, when not to, and how a message queue differs from pub/sub and event streaming.
What Is a Message Queue?
A message queue is a piece of infrastructure that holds messages between the software that creates them and the software that handles them. A message is a small packet of data, often JSON, describing a piece of work or an event: "resize image 4812," "send a welcome email to user 991," "charge order 5520."
Three roles make it work:
- Producer: the code that creates and sends messages, such as a web server receiving an upload.
- Queue (or broker): the service that stores messages durably until they're processed.
- Consumer (or worker): the code that takes messages off the queue and does the work.
The key property is that the producer and consumer don't need to be running, fast or even healthy at the same time. The web server can accept 1,000 uploads a minute and return immediately, while a pool of workers resizes images at whatever pace they can manage.
How a Message Queue Works
Here's the life of one message in a typical queue such as Amazon SQS or RabbitMQ:
- Send. The producer sends a message to the queue and gets an acknowledgment that it's stored.
- Store. The queue persists the message, often on several machines so a server failure doesn't lose it.
- Receive. A consumer asks for messages. The queue hands one over and hides it from other consumers for a while. In SQS this is the visibility timeout, 30 seconds by default and up to 12 hours.
- Process. The consumer does the work.
- Acknowledge. When the work succeeds, the consumer tells the queue to delete the message (an "ack").
- Retry on failure. If the consumer crashes or doesn't acknowledge in time, the message becomes visible again and another consumer gets it.
- Dead-letter. After a set number of failed attempts, the message moves to a dead-letter queue so a broken message doesn't block everything and someone can inspect it.
Delivery Guarantees
Queues promise different things about how many times a message arrives. Knowing which one you have decides how you write consumers.
| Guarantee | What it means | Risk | How to cope |
|---|---|---|---|
| At-most-once | Each message is delivered zero or one times | Lost messages | Use only for data you can afford to lose, like metrics samples |
| At-least-once | Each message is delivered one or more times | Duplicates | Make consumers idempotent: processing twice has the same effect as once |
| Exactly-once processing | Duplicates are removed within limits, or processing is transactional | More cost and lower throughput | Use deduplication IDs or transactions where the tool supports them |
Most production queues are at-least-once. Amazon's documentation for SQS standard queues says every message is delivered at least once but "a message may be delivered more than once," and tells you to design idempotent consumers. SQS FIFO queues add deduplication IDs for exactly-once processing within a deduplication window. In practice, idempotent consumers are the most reliable path to "exactly once" whatever the tool: store a processed-message ID, or use operations like "set status to paid" rather than "add a payment."
Ordering is a separate promise. SQS standard queues offer best-effort ordering; FIFO queues keep order within each message group. Kafka keeps order within a partition. If order matters, make it explicit with a group or partition key.
Message Queue Examples
Here are common message queue examples and why a queue helps in each:
| Example | Producer | Consumer | Why a queue |
|---|---|---|---|
| Order processing | Checkout service | Payment, inventory and shipping workers | Checkout responds instantly; fulfillment survives outages |
| Email and notifications | App servers | Email sender | Smooths bursts and retries when the email provider is slow |
| Image and video processing | Upload API | Resizing or transcoding workers | Heavy work runs in the background on scalable workers |
| AI jobs | Web app | GPU workers running models | Expensive inference runs at the pace the GPUs allow |
| Webhook handling | Webhook receiver | Business logic workers | Acknowledge the sender fast, process later; see our guide to webhook vs API |
| Data ingestion | Devices or log shippers | Database writers | Protects the database from spikes |
| Scheduled and delayed work | Any service | Workers | Delay messages, for example a reminder in 15 minutes |
Worked example: absorbing a traffic spike
An online store normally receives 20 orders a second, and its fulfillment workers can process 100 orders a second. A flash sale brings 200 orders a second for 5 minutes.
| Without a queue | With a queue | |
|---|---|---|
| During the spike | Checkout calls fulfillment directly; 100 orders a second fail or time out | Checkout stores each order in the queue and responds immediately |
| Backlog after 5 minutes | Not applicable; failed orders are lost or retried by customers | (200 − 100) × 300 seconds = 30,000 orders waiting |
| After the spike | Errors stop | Workers drain the backlog at 100 − 20 = 80 orders a second: 30,000 ÷ 80 = 375 seconds, about 6 minutes |
| Customer experience | Failed checkouts | Every order accepted; confirmations arrive a few minutes later |
The queue turns an outage into a short delay. You can also add workers automatically when the backlog grows, which most cloud queues make easy to monitor.
Message Queue vs Pub/Sub
People often confuse these two messaging patterns, so here's message queue vs pub sub in one table.
| Message queue (point-to-point) | Publish/subscribe | |
|---|---|---|
| Who gets a message | One consumer | Every subscriber |
| Typical message | A command or job: "do this" | An event: "this happened" |
| Adding a new consumer | Shares the existing work | Gets its own copy of every message |
| Example | Ten workers share image-resizing jobs | An "order placed" event goes to billing, email and analytics separately |
| Tools | SQS, RabbitMQ queues, Redis lists, task queues | SNS, Google Pub/Sub, RabbitMQ fanout exchanges, Kafka topics |
The two combine often: a pub/sub topic fans an event out to several queues, one per service, and each service's workers share its queue. That's how many cloud setups pair SNS with SQS.
Message Queue vs Message Broker vs Event Streaming
- A message queue is the data structure: messages waiting in line for a consumer.
- A message broker is the server that manages queues, routing and delivery. RabbitMQ is a broker that hosts many queues and routes messages to them through exchanges.
- Event streaming platforms like Apache Kafka store messages in an append-only log that consumers read at their own position. Messages aren't deleted when read; they stay until a retention period ends, so new consumers can replay history.
The lines have blurred. RabbitMQ added streams, a replicated log similar to Kafka's, and Kafka added share groups, which let several consumers share a partition with per-message acknowledgments: Apache Kafka 4.2 lists share groups (KIP-932) among its features, and Confluent describes them as production-ready. A queue still fits best when messages are units of work; a log fits best when many systems need the same history of events.
Popular Message Queue Tools
| Tool | Type | Delivery and ordering | Strengths | Good for |
|---|---|---|---|---|
| Amazon SQS | Managed queue | Standard: at-least-once, best-effort order; FIFO: ordered within groups, deduplication | No servers to run; messages up to 1 MiB, retained 4 days by default and up to 14 | Background jobs on AWS |
| RabbitMQ | Open-source broker | At-least-once with acks; order per queue | Flexible routing, many protocols (AMQP, MQTT, STOMP), quorum queues for replication | Task queues and complex routing |
| Apache Kafka | Event streaming log | Order per partition; replay by offset | Very high throughput, long retention, stream processing | Event pipelines, analytics, event-driven systems |
| Redis (lists, Streams) | In-memory data store | Depends on setup | Very fast, often already deployed | Lightweight job queues |
| Google Cloud Pub/Sub | Managed pub/sub | At-least-once, optional ordering keys | Global, serverless | Event fan-out on Google Cloud |
| Azure Service Bus | Managed broker | Queues and topics, sessions for ordering | Enterprise features, transactions | Business workflows on Azure |
| NATS JetStream | Lightweight messaging with persistence | At-least-once | Small footprint, simple operations | Edge and microservices |
| Celery, BullMQ, Sidekiq | Task queue libraries on top of a broker | Depends on broker | Retries, schedules and dashboards for jobs | App background jobs in Python, Node.js, Ruby |
Sources: AWS SQS developer guide, RabbitMQ documentation and project pages for the other tools.
A Minimal Example With Amazon SQS
Sending and processing a message with the AWS SDK for Python (boto3) looks like this:
import json
import boto3
sqs = boto3.client("sqs")
QUEUE_URL = "https://sqs.us-east-1.amazonaws.com/123456789012/image-jobs"
sqs.send_message(QueueUrl=QUEUE_URL, MessageBody=json.dumps({"image_id": 4812}))
resp = sqs.receive_message(QueueUrl=QUEUE_URL, MaxNumberOfMessages=10, WaitTimeSeconds=20)
for msg in resp.get("Messages", []):
job = json.loads(msg["Body"])
resize_image(job["image_id"]) # your work; must be safe to run twice
sqs.delete_message(QueueUrl=QUEUE_URL, ReceiptHandle=msg["ReceiptHandle"])WaitTimeSeconds enables long polling, so the worker waits for messages instead of hammering the queue with empty requests. The message is deleted only after the work succeeds; if resize_image crashes, the message reappears after the visibility timeout and another worker retries it.
When to Use Message Queues
Use a message queue when:
- Work can happen later. Emails, reports, thumbnails, AI jobs, anything the user doesn't need in the same response.
- Load is spiky. A queue absorbs bursts so downstream systems run at a steady rate.
- Work is slow or expensive. Long tasks shouldn't block web requests or tie up connections.
- A downstream system is unreliable. Retries and dead-letter queues handle failures without losing work.
- Services should be independent. Teams can deploy, scale and restart producers and consumers separately.
- You need to spread work across many machines. Add workers to go faster.
When Not to Use a Message Queue
- The caller needs the answer now. A login check or a price lookup should be a direct request; use REST or gRPC, compared in our guide to gRPC vs REST.
- Traffic is tiny and simple. A queue adds infrastructure, monitoring and failure modes. A cron job or a database table of pending tasks may be enough.
- Strict global ordering is essential at high volume. Queues scale by processing in parallel, which works against global order.
- You need to query the data. Queues are for moving work, not storing records; keep state in a database.
Common Mistakes
- Non-idempotent consumers. At-least-once delivery means duplicates will happen; charging a card twice is the classic bug.
- No dead-letter queue. One malformed message retried forever blocks or burns capacity.
- Visibility timeout shorter than the job. The message reappears while still being processed, and a second worker starts the same job.
- Huge messages. Put large files in object storage and send a reference; SQS caps messages at 1 MiB.
- Not monitoring queue depth and message age. A growing backlog is your earliest warning that consumers can't keep up.
- Retrying instantly. Back off between retries when a downstream service is overloaded; our guide to API rate limiting explains backoff.
FAQ
What is a message queue in simple terms?
It's a waiting line for tasks between programs. One program drops a message describing work into the queue, and another program picks it up and does the work when it's ready, so neither has to wait for the other.
What is a message queue used for?
Background jobs like sending emails or processing uploads, smoothing traffic spikes, connecting microservices, retrying work when a service fails, and spreading tasks across many workers.
Is Kafka a message queue?
Not traditionally. Kafka is an event streaming platform that stores messages in a log that consumers read by position, and messages stay after they're read. Newer Kafka versions add share groups with queue-like behavior, but RabbitMQ and SQS remain closer to the classic queue model.
What is a message queue in system design?
In system design, a message queue is the component that decouples services and handles asynchronous work. It improves reliability and scalability, at the cost of eventual consistency and extra infrastructure to monitor.
Which message queue is best?
It depends on your stack. On AWS, SQS is the simplest. For flexible routing and protocols, RabbitMQ. For high-throughput event streams and replay, Kafka. For small apps, a Redis-based job library is often enough.