Sub topic 2
At-Most-Once, At-Least-Once, and Exactly-Once Delivery
This chapter assumes you know basic Python, HTTP request/response, and that network services can fail independently.
Delivery guarantees
A delivery guarantee describes what can happen when a broker, network, or consumer fails:
- At-most-once delivers a message zero or one time. The consumer may lose it, but it will not receive a duplicate. A consumer usually acknowledges before processing. This minimizes duplicate work, but it can lose important work.
- At-least-once delivers a message one or more times. The broker redelivers an unacknowledged message after a failure. A consumer must tolerate duplicates.
- Exactly-once aims for one effect, even when delivery or processing is repeated. This requires coordination, such as a transaction covering message tracking and the side effect. It is expensive and often limited to one system.
Most practical systems choose at-least-once delivery and make consumers idempotent. An idempotent operation has the same final result when repeated.
Writing idempotent consumers
Give each message a unique ID. Store that ID in the same database transaction as the business change. If the ID already exists, skip the repeated message.
import sqlite3
def handle_once(db, message_id, apply_change):
with db:
inserted = db.execute(
"INSERT OR IGNORE INTO processed (message_id) VALUES (?)",
(message_id,),
).rowcount
if inserted == 0:
return False
apply_change(db)
return True
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE processed (message_id TEXT PRIMARY KEY)")
print(handle_once(db, "m-1", lambda db: None)) # True
print(handle_once(db, "m-1", lambda db: None)) # FalseRetries and dead-letter queues
Retry temporary failures with a delay and a maximum attempt count. Repeated immediate retries can overload a failing dependency. Send messages that exceed the limit to a dead-letter queue (DLQ) for inspection or repair. Record the error, message ID, and attempt count.
Scaling with competing consumers
Multiple consumers can read from one work queue. The broker gives each message to one consumer, so throughput increases without processing each message multiple times. This pattern is called competing consumers.
A prefetch limit controls how many unacknowledged messages each consumer can hold. A small limit improves fairness and applies backpressure; a larger limit can improve throughput for fast, uniform jobs. Ordering is usually not preserved across competing consumers.
Exercise
A consumer crashes after charging a customer but before acknowledging the message. What design prevents a second charge?
Show answer
Use a stable message or payment ID as a unique key, record it transactionally with the charge, and make a redelivery a no-op.