System Design Part 5 Service communication

Message Queues: Decoupling, Peak Shaving, Retries, and Why Messages Will Be Duplicated

Bill.Lin 17 min read

System Design series Part 5-2 | Previous: REST, gRPC, and GraphQL | Next: Pub/Sub and Delivery Semantics | Series map

Scenario and problem

After a sign-up succeeds, the system still has three things to do: send a confirmation email, notify the speaker, and send the sign-up record to the recommendation system. Right now all of it runs synchronously inside the sign-up API, and the problems show up one after another:

  1. Slow: the sign-up API’s latency is the sum of all four tasks, and sending the email is the slowest
  2. Cascading failure: when the mail service is down, sign-ups fail too. The user has actually got a seat but sees an error
  3. Peaks: in the 10 minutes after sign-ups open for a popular talk, 30,000 sign-ups pour in, but the email provider allows at most 50 emails per second. With synchronous calls, the requests over that limit can only fail
Everything runs synchronously in the sign-up API1 / 4
Everything runs synchronously in the sign-up APIUserSign-up APIMail serviceSpeaker alertRecommenderUserSign-up APIMail serviceSpeaker alertRecommendersign upconfirm emailnotifysend recordUserSign-up APIMail servicesign upslowest callLatency = sum of all fourSign-up APIMail serviceUsercall failsDownGot a seat, sees an errorUserSign-up APIMail service30k in 10 minover 50/sAt most 50 per second
  1. Three tasks after a sign-upAfter a sign-up succeeds, the system still has to send a confirmation email, notify the speaker, and send the sign-up record to the recommendation system. Right now all of it runs synchronously inside the sign-up API.
  2. SlowThe sign-up API's latency is the sum of all four tasks, and sending the email is the slowest.
  3. Cascading failureWhen the mail service is down, sign-ups fail too. The user has actually got a seat but sees an error.
  4. PeaksIn the 10 minutes after sign-ups open for a popular talk, 30,000 sign-ups pour in, but the email provider allows at most 50 emails per second. With synchronous calls, the requests over that limit can only fail.

The simplest approach and its limits

  • @Async onto a thread pool: the sign-up API gets faster, but the work exists only in memory. When the service restarts or crashes, every job that has not run yet is gone, and there is nowhere to see which ones failed
  • The database as a queue: in the same transaction as the sign-up, write a “send email” record, and have a background worker pick it up with SELECT ... FOR UPDATE SKIP LOCKED. The job commits together with the sign-up, so it cannot be lost, and several background workers never grab the same record. At low volume this is a very good choice. Its limits are the cost of polling, lock contention and table bloat from heavy updates, and one more table or status column for every new kind of consumer

Only when you need more volume, more kinds of consumers, and fuller retries and monitoring is it time for a dedicated message broker.

Core mechanism

Three things a queue gives you

  • Decoupling in time: the producer can respond to the user as soon as it has sent the message; the consumer can process it a bit later, or even be down for a while
  • Peak shaving: production and consumption do not have to run at the same rate; the difference waits in the queue. Sending 30,000 emails at 50 per second takes 600 seconds, so they are all sent about 10 minutes after the peak, instead of 29,000 requests failing
  • Failure isolation and retries: when the mail service is down, the messages stay in the queue waiting to be retried, and the sign-up itself is unaffected

The price is eventual consistency: at the moment the sign-up succeeds, the confirmation email has not been sent yet. The product has to accept this delay, and the UI has to be able to show “processing”.

Competing consumers and prefetch

Several consumers subscribe to the same queue, and each message goes to only one of them. When the consumers cannot keep up, adding instances raises the processing rate.

Prefetch sets the maximum number of unacknowledged messages the broker pushes to each consumer at a time. The larger the value, the higher the throughput, because a consumer does not have to wait for the next message every time it finishes one; but messages pile up in the consumer’s memory and are spread less evenly. Spring AMQP’s default is 250. Lower it when messages are large, processing is slow, or you need strict ordering.

When you ack decides the delivery semantics

After the broker sends a message, it waits for the consumer to reply with an ack before deleting it:

sequenceDiagram
    participant Q as Queue
    participant C as Consumer
    participant M as Mail service
    Q->>C: message for sign-up #918
    C->>M: send confirmation email
    M-->>C: success
    Note over C: crashes before the ack
    Note over Q: no ack, so it redelivers once the connection drops
    Q->>C: message for sign-up #918 (redelivered)
    C->>M: sends it again
When to ack On a crash Semantics
Ack after processing The message is redelivered and may be processed twice at-least-once
Ack on receipt The message is lost at-most-once

In the vast majority of cases you ack after processing, so consumers will receive duplicate messages, and the processing logic must be idempotent. Besides crashes, duplicates also come from producers resending after a timeout, reconnecting after a network interruption, and so on. How to make processing idempotent is covered in Idempotency and Idempotency Keys in Part 5.

A consumer also cannot take too long to reply. By default, if RabbitMQ gets no ack within 30 minutes, it closes that consumer’s channel and redelivers the message to someone else.

Classifying failures: transient and permanent

Type Examples Handling
Transient Mail service timeout, a 503 response, not enough database connections Wait and retry, with growing intervals
Permanent Malformed email address, a message that cannot be deserialized, the matching sign-up has been deleted Retrying will never succeed; send it straight to the DLQ

A poison message is a message that keeps failing. If you put it back on the queue right after every failure, it is redelivered over and over, ties up consumers, and can even block the messages behind it. How to handle it:

  • Limit redeliveries: RabbitMQ’s quorum queue counts the failed deliveries of each message, and once the count passes the limit, it forwards the message to a dead letter exchange; with no DLX configured, the message is simply dropped. Since RabbitMQ 4.0 this limit defaults to 20, and the official docs recommend a DLX for every quorum queue so that messages do not silently disappear
  • Dead letter queue (DLQ): holds the messages that cannot be processed. Monitor its length and alert on it; after fixing the problem, you can move the messages back to the original queue to be processed again
  • Delayed retries: redelivering immediately amounts to rapid back-to-back retries, which puts extra pressure on a downstream that is recovering. You can retry with backoff intervals in the consumer, or send failed messages to a retry queue with a TTL, which moves them back to the original queue when they expire

Ordering

A single queue is first-in, first-out, but the processing order is not necessarily the same: several consumers processing in parallel, or a message redelivered after a failure, can both make a message sent later finish first.

If “sign-up canceled” is processed before “sign-up succeeded”, a wrong confirmation email goes out. Options:

  • Make order not matter: messages carry a version or state, and the consumer compares it with the latest state in the database before processing, instead of acting in the order the messages arrive
  • Partition by key: messages for the same sign-up always go to the same partition and are processed in order by the same consumer. This is how log-based brokers such as Kafka do it; the next post covers it in detail
  • A single consumer: RabbitMQ’s single active consumer lets only one consumer process the whole queue, gaining order and losing parallel processing

Durability

Messages must not be lost when the broker crashes. You need both of these:

  • Replicate the queue: RabbitMQ’s quorum queue uses Raft to replicate messages to a majority of nodes (Consensus and Raft)
  • The producer must confirm that the broker received it: turn on publisher confirms, so the broker replies only after the message is safely stored. If you treat a send as successful without a confirm, the message is lost when the broker crashes

The dual-write problem

A sign-up has to write to the database and also send a message, and the two cannot go in the same transaction:

Order What a crash in between does
Send the message, then commit the transaction The transaction rolls back but the message is already out: a confirmation email for a sign-up that does not exist
Commit the transaction, then send the message The message is never sent: the sign-up succeeded, but the confirmation email will never go out

The “database as a queue” approach above happens not to have this problem, because the “pending job” is in the same transaction as the sign-up. Combine that idea with a broker and you get the transactional outbox: first write to an outbox table inside the transaction, then have a separate process send the outbox contents to the broker (Outbox Pattern, covered in detail in Part 7).

What goes in a message

  • Only an ID, or the full data: with only an ID, the consumer has to query back and gets the latest state, but pays for an extra query and depends on the producer’s database; with the full data, the consumer is self-sufficient, but it may get stale state, and the message is larger
  • Keep large files out of messages: store large content such as handout PDFs in object storage, and put only its location in the message (claim check, File and Object Storage)
  • The message format must be able to evolve: producers and consumers are not deployed at the same time. Add fields in a way old consumers can ignore, and before removing a field, make sure no consumer uses it anymore

Comparing options

Option Characteristics Good for
Database table + SKIP LOCKED Same transaction as the business data, no new infrastructure Low volume, few kinds of consumers
RabbitMQ (quorum queue) Flexible routing (exchanges, routing keys), per-message acknowledgement, DLX and redelivery limits Work queues that need fine-grained routing and retries
Amazon SQS Fully managed, visibility timeout, redrive policy to a DLQ; standard queues are at-least-once with no ordering guarantee, FIFO queues guarantee order On AWS, when you do not want to run a broker
Kafka Messages are a retained log that several consumer groups can each read and replay Event streams, multiple subscribers, replay; covered in the next post
Redis Streams Lightweight, easy to adopt when you already have Redis Low volume, when Redis’s durability is acceptable

In Java

1. Declare the queue, the DLX, and the redelivery limit

java
@Configuration
public class RegistrationMessagingConfig {

    public static final String EXCHANGE = "registration";
    public static final String EMAIL_QUEUE = "registration.confirmation-email";
    public static final String EMAIL_DLQ = EMAIL_QUEUE + ".dlq";

    @Bean
    public Declarables registrationTopology() {
        DirectExchange exchange = new DirectExchange(EXCHANGE);
        DirectExchange deadLetters = new DirectExchange(EXCHANGE + ".dlx");
        Queue emailQueue = QueueBuilder.durable(EMAIL_QUEUE)
                .withArgument("x-queue-type", "quorum")
                .deliveryLimit(5)                           // more than 5 failed deliveries: forward to the DLX
                .deadLetterExchange(deadLetters.getName())
                .deadLetterRoutingKey(EMAIL_QUEUE)
                .build();
        Queue emailDlq = QueueBuilder.durable(EMAIL_DLQ)
                .withArgument("x-queue-type", "quorum")
                .build();
        return new Declarables(exchange, deadLetters, emailQueue, emailDlq,
                BindingBuilder.bind(emailQueue).to(exchange).with("registered"),
                BindingBuilder.bind(emailDlq).to(deadLetters).with(EMAIL_QUEUE));
    }

    @Bean
    public MessageConverter jsonMessageConverter() {
        return new JacksonJsonMessageConverter();
    }
}

2. Send the message only after the transaction commits

java
@Service
public class RegistrationService {

    private final RegistrationRepository registrations;
    private final ApplicationEventPublisher events;

    public RegistrationService(RegistrationRepository registrations, ApplicationEventPublisher events) {
        this.registrations = registrations;
        this.events = events;
    }

    @Transactional
    public Registration register(long lectureId, long memberId) {
        Registration registration = registrations.save(new Registration(lectureId, memberId));
        events.publishEvent(new RegistrationConfirmed(registration.getId(), lectureId, memberId));
        return registration;
    }
}

@Component
public class RegistrationEventRelay {

    private final RabbitTemplate rabbitTemplate;

    public RegistrationEventRelay(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void relay(RegistrationConfirmed event) {
        rabbitTemplate.convertAndSend(RegistrationMessagingConfig.EXCHANGE, "registered", event);
    }
}

@TransactionalEventListener sends the message only after the transaction commits, which avoids “emailing a sign-up that was rolled back”. But it does not solve the other half: if the service crashes after the commit and before the send, or the broker is briefly unreachable, the message is lost. For confirmation emails, you can pair it with a compensation job that periodically scans for sign-ups with no email sent; messages that must not be lost need the outbox.

3. The consumer: separate permanent failures, and be idempotent

java
@Component
public class ConfirmationEmailListener {

    private final EmailSender emailSender;
    private final SentEmailRepository sentEmails;

    public ConfirmationEmailListener(EmailSender emailSender, SentEmailRepository sentEmails) {
        this.emailSender = emailSender;
        this.sentEmails = sentEmails;
    }

    @RabbitListener(queues = RegistrationMessagingConfig.EMAIL_QUEUE)
    public void onRegistered(RegistrationConfirmed event) {
        if (sentEmails.exists(event.registrationId())) {
            return;                                             // duplicate delivery: already sent
        }
        try {
            // When the email provider supports idempotency keys, pass the sign-up ID; one key sends only one email
            emailSender.sendConfirmation(event.memberId(), event.lectureId(), "registration-" + event.registrationId());
        } catch (InvalidRecipientException e) {
            throw new AmqpRejectAndDontRequeueException("invalid recipient", e);   // permanent failure: straight to the DLQ
        }
        sentEmails.markSent(event.registrationId());
    }
}
  • Transient failures (timeouts, connection errors) let the exception propagate: the message is rejected and redelivered, and after more than 5 failures it goes to the DLQ. Since Spring AMQP 4.0.6, the listener container rejects failed messages one at a time, so every failure counts toward the broker’s redelivery limit
  • Permanent failures throw AmqpRejectAndDontRequeueException: the message is not redelivered and goes straight to the DLX
  • Idempotency: check whether the email was already sent before sending it. A crash “after sending, before marking” still causes a resend; the mail service’s idempotency key covers that gap. When the provider does not support one, an occasional duplicate confirmation email is an acceptable cost. A payout is not (Distributed Locks and Fencing Tokens)
  • Spring Boot can also turn on listener-side retries (off by default), which retry with backoff inside the same consumer and, once they are used up, reject the message and hand it to the DLX

The code above is written from the official documentation for Spring AMQP 4.1, Spring Boot 4.1, and RabbitMQ, and has not been compiled or run.

Pitfalls and gotchas

  • No DLX configured: a quorum queue drops messages that exceed the redelivery limit; older versions have no limit at all, so a poison message is redelivered forever
  • Assuming a message is processed only once: at-least-once means there will be duplicates; every consumer has to be idempotent
  • Sending the message inside the transaction: when the transaction rolls back, the message is already out, and the consumer processes data that does not exist
  • Consumers taking too long: past the broker’s ack timeout, the channel is closed and the message is redelivered to another consumer, so the same message is processed twice at the same time. Split long jobs into smaller ones, or switch to “receive the message → write it to a job table → ack immediately”
  • Returning messages with nack: since RabbitMQ 4.3, basic.nack does not count as a failed delivery; only basic.reject does. If you handle acks yourself, use reject so that the redelivery limit can stop the message
  • A large prefetch with slow work: one consumer is holding hundreds of messages while the others sit idle; when that consumer crashes, those hundreds of messages are all redelivered at once
  • Monitoring only for errors: what matters is the queue length, how long the oldest message has been waiting, and the consumption rate. A queue that keeps growing means consumers cannot keep up; alert before users notice
  • Queues that grow without limit: when consumers are stalled for a long time, the broker’s disk and memory fill up and other queues suffer. Set max-length and choose the overflow behavior (for example, reject new messages so the producer knows)
  • Nobody watches the DLQ: a DLQ is pending work, not a trash can. It needs alerts, an owner, and a tool for redelivering its messages

Security

  • Messages are untrusted input too: your own producers are not the only things that can write to a queue; a compromised service, misconfigured permissions, or replayed old messages can all show up. Consumers have to validate the format and content of a message and check authorization again (for example, that this member really signed up for this talk), instead of accepting everything because “the message came from inside”
  • Do not use Java serialization: deserializing untrusted data can lead to remote code execution. Use a data format such as JSON, and let the listener’s parameter type decide which class to convert to, instead of letting a message header name an arbitrary class
  • Broker account permissions: each service uses its own account, granted only the vhost and the exchange and queue read/write permissions it needs. The sign-up service can only write to the registration exchange, and the mail service can only read its own queue. Disable the default guest account in production
  • Encrypted connections: use TLS between producers, consumers, and the broker; messages often carry personal data such as email addresses and names
  • Personal data in the DLQ: messages in a DLQ may stay there for a long time, and more people look at them. Set a retention period, control who can view and redeliver them, and keep message content to IDs as far as you can
  • Flooding the system through the queue: an attacker triggers operations that produce messages in large numbers (for example, signing up and canceling over and over), so the queue balloons and every consumer slows down. Rate-limit the APIs that produce messages, and give queues a length limit

When to use it, and when not to

  • Use a message queue: for work that is slow or depends on external services, when you need peak shaving or automatic retries after failures, and the producer does not need the result right away
  • Consider the database as a queue first: low volume, only one or two kinds of background jobs, and you want them in the same transaction as the business data
  • Do not use it: for operations where the user needs the result immediately (such as decrementing the seat itself), or for synchronous calls that have none of the needs above and would only “look more decoupled”. A queue brings the costs of eventual consistency, duplicate processing, monitoring, and operations

References

Comments