Очереди недоставленных сообщений и стратегии повторных попыток
Узнайте, как обрабатывать сообщения, не прошедшие обработку, с помощью повторных попыток с увеличением интервала, ограничений повторной доставки и очередей недоставленных сообщений, сохраняя надёжность асинхронных конвейеров.
«Очереди недоставленных сообщений и стратегии повторных попыток» — бесплатный урок API Rate Limiting & Scalability Patterns на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения API Rate Limiting & Scalability Patterns, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс API Rate Limiting & Scalability Patterns содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
When Messages Fail
In an async pipeline, a consumer can fail to process a message — a bug, a bad payload, or a downstream outage. Without a plan, that message can block the queue or be lost.
This lesson covers retries and the dead letter queue.
Acknowledgements
A consumer acks a message to confirm successful processing. If it nacks (or never acks), the broker can redeliver it.
Acking before doing the work risks loss; ack only after success.
msg = queue.receive()
process(msg)
msg.ack() # only after successNaive Retries Are Dangerous
Immediately re-processing a failed message can create a tight loop that hammers a struggling downstream service — a self-inflicted outage.
You need delay and a limit.
Exponential Backoff
Wait longer after each failed attempt: 1s, 2s, 4s, 8s. This gives a transient problem time to recover instead of pounding it.
def delay(attempt):
return min(2 ** attempt, 60)Jitter
If many consumers back off on the same schedule, they retry in sync — a thundering herd. Add random jitter to spread retries out.
import random
def delay(attempt):
base = min(2 ** attempt, 60)
return base / 2 + random.uniform(0, base / 2)Max Retry Limit
Some failures never succeed — a malformed message is poison. After a fixed number of attempts, stop retrying and move the message aside.
The Dead Letter Queue
A dead letter queue (DLQ) is a separate queue where messages go after exhausting retries. The main pipeline keeps flowing while failures are quarantined for inspection.
if msg.attempts >= MAX_RETRIES:
dlq.send(msg)
else:
requeue(msg, delay(msg.attempts))Inspecting the DLQ
The DLQ is your debugging surface. Engineers review failed messages, find the root cause, fix code or data, and then replay them back into the main queue.
Idempotent Consumers
Retries mean a message may be processed more than once. Make handlers idempotent — processing the same message twice yields the same result, for example by tracking processed message IDs.
if seen.contains(msg.id):
msg.ack() # already handled
else:
process(msg)
seen.add(msg.id)Alerting on the DLQ
A growing DLQ is a signal something is broken. Alert when its depth crosses a threshold so failures get human attention before they pile up.
Poison Message Patterns
Some failures repeat no matter how many times you retry — a malformed payload, a missing referenced record. Detect these early by inspecting the error type: route deterministic, non-transient failures straight to the DLQ instead of wasting retry attempts.
if is_permanent(error):
dlq.send(msg) # no point retrying
else:
requeue(msg, delay(msg.attempts))Quick Check
Test your understanding of failure handling.
Recap
You learned to handle message failures:
- Ack after success, nack to redeliver
- Exponential backoff with jitter spaces retries
- A retry limit protects against poison messages
- A DLQ quarantines failures for inspection and replay
- Make consumers idempotent
Часто задаваемые вопросы
Урок «Очереди недоставленных сообщений и стратегии повторных попыток» бесплатный?
Да — полный текст урока «Очереди недоставленных сообщений и стратегии повторных попыток» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс API Rate Limiting & Scalability Patterns, подпишись на CoddyKit PRO. Курс API Rate Limiting & Scalability Patterns содержит 4 уроков всего.
Чему я научусь в уроке «Очереди недоставленных сообщений и стратегии повторных попыток»?
Узнайте, как обрабатывать сообщения, не прошедшие обработку, с помощью повторных попыток с увеличением интервала, ограничений повторной доставки и очередей недоставленных сообщений, сохраняя надёжнос… Ты практикуешь API Rate Limiting & Scalability Patterns с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать API Rate Limiting & Scalability Patterns?
Предыдущий опыт не требуется. API Rate Limiting & Scalability Patterns на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Очереди недоставленных сообщений и стратегии повторных попыток»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке API Rate Limiting & Scalability Patterns?
Да. Каждый урок API Rate Limiting & Scalability Patterns включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Введение в асинхронные API
- Основы очередей сообщений
- Реализация фоновых задач
- Очереди недоставленных сообщений и стратегии повторных попыток