BE·51
Asynchronous Work, Jobs and Messaging
Moving work out of the request path. Covers synchronous versus asynchronous processing, in-process async (@Async, executors, virtual threads, futures), scheduled jobs and distributed scheduling, background workers, then durable messaging with Kafka, RabbitMQ and cloud queues: delivery guarantees, acknowledgements, ordering, consumer groups, dead-letter queues, the transactional outbox and idempotent consumers. Compared with Go worker pools, Celery, Sidekiq, Oban, Hangfire, Temporal and Rust's job crates.
Start here: work that shouldn't make the user wait
Not everything belongs in the request
When a customer places an order, the service must save it before answering. But sending the confirmation SMS, emailing a receipt, updating the analytics warehouse, resizing a photo or notifying the kitchen display can happen a moment later. Doing them inside the request makes the customer wait for slow third parties, and makes the order fail when the SMS provider is down. Moving them out of the request is asynchronous work, and there are three levels of it, each surviving more kinds of failure:
| Level | Where the work waits | Survives a process crash? | Example |
|---|---|---|---|
| In-process async | Memory (an executor's queue) | No | @Async, CompletableFuture, virtual threads |
| Durable job queue | A database table | Yes | A job table polled with SKIP LOCKED; JobRunr, db-scheduler, Quartz |
| Message broker | A broker's durable log or queue | Yes, and decouples services | Kafka, RabbitMQ, SQS, Pub/Sub, NATS JetStream |
Level 1: in-process
static String sendSms(String to, String text) { sleep(300); return "SMS to " + to + ": " + text; } // a slow provider
sendSms("+91-98xxxxxx21", "Your order 101 is confirmed"); // inside the request
Future<String> sms = background.submit(() -> sendSms("+91-98xxxxxx21", "Your order 102 is confirmed")); // handed off
1) SMS sent inside the request: customer waited 306 ms
2) SMS handed to a background thread: customer waited 8 ms
...later: SMS to +91-98xxxxxx21: Your order 102 is confirmed
The customer's wait dropped from 306 ms to 8 ms. But the work now lives only in this process's memory: if the process is restarted for a deploy or crashes before the task runs, the SMS silently never happens (the lab killed a process with 100 queued tasks and 64 vanished). That's acceptable for best-effort work like warming a cache, and not for anything the business depends on.
Level 2: a durable job queue
Store the job in the database in the same transaction as the order, and let a separate worker run it:
// in the request: save the jobs and return
c.setAutoCommit(false);
INSERT INTO job(kind, payload) VALUES ('sms', 'Your order 103 is confirmed'), …
c.commit();
// in a worker process: claim one ready job at a time, run it, mark it done
SELECT id, payload FROM job WHERE status = 'READY' AND run_after <= now() ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED
… send the SMS …
UPDATE job SET status = 'DONE', attempts = attempts + 1 WHERE id = ?
COMMIT
3) request saved 3 SMS jobs in the database and returned immediately; then the process stopped
4) a worker process starts later:
worker: SMS to +91-98xxxxxx21: Your order 103 is confirmed
worker: SMS to +91-98xxxxxx21: Your order 104 is confirmed
worker: SMS to +91-98xxxxxx21: Your order 105 is confirmed
jobs DONE: 3
The request process stopped, and nothing was lost: the jobs were committed with the order, so they exist if and only if the order does. FOR UPDATE SKIP LOCKED lets many workers pull from the same table without taking the same job (each skips rows another worker has locked), which the lab shows is the difference between 1,000 SMS and 2,695. Jobs can also carry a run_after time (scheduled and retried work) and an attempts count (giving up after too many failures). This simple worker holds the row lock while it works; production workers instead mark a job as claimed with a lease timeout, so a slow job doesn't hold a transaction open.
Level 3: messages between services
When other services need to react (the kitchen display, loyalty points, the data warehouse), the order service publishes an event ("OrderPlaced 101") to a message broker, and each interested service consumes it at its own pace. The producer doesn't know or wait for the consumers, so they can be deployed, scaled and fail independently. Brokers come in two styles: queues (RabbitMQ, SQS: each message goes to one consumer, then is deleted) and logs (Kafka, Pub/Sub, Kinesis: messages are kept, and each consumer group tracks its own position).
The rules that make async work reliable
Whatever the level, three facts shape the design, and the lab reproduces a failure for each:
- Delivery is at-least-once. A worker can crash after doing the work but before recording that it did, so the job or message is delivered again. Consumers must therefore be idempotent: processing the same message twice has the same effect as once.
- Don't write to two systems and hope. Saving the order and then publishing the event can fail in between, leaving an order with no event (or an event with no order). The transactional outbox writes the event to a table in the same transaction, and a relay publishes it afterwards.
- Some messages will never succeed. A job with an invalid phone number fails every time; retry with increasing delays (backoff), then move it to a dead-letter state for a human, so it doesn't block or spin forever.
How deep to go in async work and messaging
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Decide what can be asynchronous; use executors and scheduled jobs |
| L2 | Build durable job queues; publish and consume messages with Kafka or RabbitMQ |
| L3 | Explain delivery guarantees, ordering, partitions, consumer groups, outbox, idempotency, DLQs and sagas |
| L4 | Diagnose lost work, duplicate processing, poison messages, consumer lag and ordering bugs |
| L5 | Design event flows and workflows (choreography vs orchestration) across services |
| L6 | Run messaging platforms and event-schema governance for an organisation |
Choosing where work runs
Synchronous versus asynchronous
A request handler can do work synchronously, completing it before responding, or asynchronously, accepting it and doing it later or elsewhere.
| Synchronous | Asynchronous | |
|---|---|---|
| Client sees | The final result (or failure) | An acknowledgement (202 Accepted, an operation ID), then the result via polling, webhook, push or email |
| Latency | The sum of all the work | Fast acknowledgement; work proceeds independently |
| Failure handling | Immediate, visible to the caller | Must be designed: retries, dead letters, compensation, user notification |
| Coupling | Caller and callee must both be up | Temporal decoupling: producer and consumer needn't be up at the same time (with a durable queue) |
| Load | Spikes hit every downstream immediately | Queues absorb bursts (load levelling) |
| Consistency | Easier to reason about | Eventual consistency, so the UI and APIs must cope |
Move work async when it's slow (report generation, video transcoding, bulk imports), unreliable (third-party APIs, email, webhooks to customers), not needed for the response (analytics, search indexing, cache warming, notifications), bursty (flash sales), or must be fanned out to many consumers (an OrderPlaced event consumed by billing, shipping and analytics).
Keep it synchronous when the user genuinely needs the result now and the work is fast and reliable. Asynchrony adds failure modes, so don't add it for its own sake.
The crucial distinction is in-process versus durable:
- In-process async (a thread pool,
@Async, goroutines,tokio::spawn,Task.Run): fast and simple, but the work is lost if the process dies (deploy, crash, OOM-kill, scale-in). Use it only for work you can afford to lose or can recompute. - Durable async (a message broker, a database-backed job queue, a workflow engine): work survives restarts and failures, at the cost of infrastructure and the delivery-semantics problems below.
In-process async
Async tasks, executors and futures
@Configuration
@EnableAsync
class AsyncConfig {
@Bean(name = "mailExecutor")
Executor mailExecutor() {
var ex = new ThreadPoolTaskExecutor(); // Spring's wrapper over ThreadPoolExecutor (chapter 38)
ex.setCorePoolSize(4);
ex.setMaxPoolSize(8);
ex.setQueueCapacity(500); // bounded!
ex.setThreadNamePrefix("mail-");
ex.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
ex.setWaitForTasksToCompleteOnShutdown(true); // drain on graceful shutdown
ex.setAwaitTerminationSeconds(20);
ex.setTaskDecorator(new ContextPropagatingTaskDecorator()); // carry MDC/tracing context to the worker thread
return ex;
}
}
// With spring.threads.virtual.enabled=true, Boot's default async executor uses virtual threads
// (SimpleAsyncTaskExecutor with virtual threads, optionally with a concurrency limit).
@Service
class Notifications {
@Async("mailExecutor")
public CompletableFuture<Void> sendConfirmation(OrderId id) { // runs on the executor, through a proxy
mailer.send(templates.confirmation(id));
return CompletableFuture.completedFuture(null);
}
}
@Async pitfalls (all from proxies and threads, chapters 38 and 46):
- Self-invocation skips the proxy, so the method runs synchronously.
- Exceptions from
void@Asyncmethods go to anAsyncUncaughtExceptionHandlerand are otherwise lost. ReturnCompletableFutureand handle failures, or log in the handler. - Context:
SecurityContext, MDC, transactions and request scope don't follow to the async thread unless propagated. Each async task needs its own transaction. - Durability: if the pod is killed mid-task, the work is gone. For emails that must be sent, use a durable mechanism (the outbox below, or a job queue).
- Unbounded queues hide overload until memory runs out.
Scheduled jobs
@Configuration @EnableScheduling class SchedulingConfig {}
@Component
class Housekeeping {
@Scheduled(cron = "0 15 2 * * *", zone = "UTC") // 02:15 UTC daily (6 fields: sec min hour dom mon dow)
void purgeExpiredCarts() { carts.deleteExpired(Instant.now().minus(Duration.ofDays(7))); }
@Scheduled(fixedDelayString = "PT30S", initialDelayString = "PT10S") // 30 s after the previous run FINISHES
void retryFailedWebhooks() { webhooks.retryDue(); }
@Scheduled(fixedRate = 60_000) // every 60 s from the previous START (runs can overlap if long)
void publishMetrics() { … }
}
Scheduling concerns:
- Multiple instances: with 5 replicas, every replica runs
@Scheduledmethods, so the purge runs 5 times concurrently. Solutions: - ShedLock (a lock row in the DB or Redis, so only one instance runs each job execution);
- a dedicated scheduler deployment with one replica;
- Quartz in clustered JDBC mode (persistent jobs, misfire handling, clustering);
- Kubernetes CronJobs (the platform schedules a container run);
- cloud schedulers (EventBridge Scheduler, Cloud Scheduler) triggering an endpoint or queue;
- or a job framework (JobRunr, db-scheduler).
- Idempotency and overlap: jobs can run twice (lock expiry, retries, manual reruns). Design them to be idempotent, for example by processing "items due and not yet processed" rather than "everything since the last run".
- Time zones and DST: schedule in UTC, or specify the zone explicitly. A local 02:30 job doesn't run (or runs twice) on DST transition days.
- Observability: record each run's start, end, outcome and items processed. Alert on missed runs, not just failed ones (dead-man's-switch monitoring).
- Long jobs: process in chunks with checkpoints, so a restart resumes instead of starting over (Spring Batch provides chunk-oriented processing, restartability and job repositories).
@Scheduled(cron = "0 15 2 * * *", zone = "UTC")
@SchedulerLock(name = "purgeExpiredCarts", lockAtMostFor = "PT30M", lockAtLeastFor = "PT1M") // ShedLock
void purgeExpiredCarts() { … }
Background workers and in-process queues
A background worker consumes tasks from a queue and processes them outside request threads. In-process versions are a bounded BlockingQueue plus worker threads, or Go channels and goroutines:
// Go: a bounded worker pool with backpressure and graceful shutdown
type Job struct{ OrderID string }
func StartWorkers(ctx context.Context, n int, jobs <-chan Job, handle func(context.Context, Job) error) *sync.WaitGroup {
var wg sync.WaitGroup
for i := range n {
wg.Add(1)
go func(id int) {
defer wg.Done()
for {
select {
case <-ctx.Done():
return // shutdown requested
case j, ok := <-jobs:
if !ok {
return // channel closed: no more work
}
if err := handle(ctx, j); err != nil {
slog.Error("job failed", "worker", id, "order", j.OrderID, "err", err)
}
}
}
}(i)
}
return &wg
}
// jobs := make(chan Job, 1000) // bounded buffer: a full channel blocks producers (backpressure)
The same durability caveat applies. For anything that matters, the queue must be outside the process: a broker, or a database table used as a queue.
Durable messaging
Messaging models
Durable async work flows through a message broker (or a database-backed queue). The two fundamental models are queues and logs:
| Message queue (RabbitMQ, ActiveMQ/Artemis, AWS SQS, Azure Service Bus queues, Google Cloud Tasks) | Log / event stream (Apache Kafka, Redpanda, AWS Kinesis, Azure Event Hubs, Apache Pulsar, NATS JetStream) | |
|---|---|---|
| Consumption | Competing consumers: each message is processed by one worker | Consumer groups each read the full stream; within a group, partitions are split among members |
| After processing | Message deleted on ack | Message retained (days, forever with compaction); the consumer advances its offset |
| Replay | Not inherent (re-publish) | Yes: reset offsets to reprocess history, or bootstrap a new service from the log |
| Ordering | Generally none across workers (FIFO queue variants exist, such as SQS FIFO with message groups) | Per partition: messages with the same key go to the same partition, in order |
| Routing | Rich (RabbitMQ exchanges: direct, topic, fanout, headers; bindings) | By topic and key; filtering happens in consumers |
| Throughput | Tens of thousands of msgs/s per queue (RabbitMQ), elastic in the cloud | Very high (millions of msgs/s per cluster); sequential disk I/O, batching, zero-copy |
| Per-message features | Priorities, per-message TTL, delayed delivery, request/reply | Minimal (the log is the abstraction) |
| Best for | Task/work queues, commands, RPC-style jobs, complex routing | Event streaming, event sourcing and CDC feeds, analytics pipelines, fan-out to many independent consumers, replayable integration |
Many systems use both: Kafka for domain events and data pipelines, and RabbitMQ or SQS for task queues. Pub/sub systems (Google Pub/Sub, SNS → SQS fan-out, Redis Pub/Sub, NATS core) sit in between, and Vol. 5 compares them in depth with their consistency models.
Delivery guarantees
Every messaging system faces the same unavoidable problem (the two generals' problem, Vol. 5): you can't know whether a message was processed if the acknowledgement is lost.
| Guarantee | Meaning | How |
|---|---|---|
| At-most-once | Never redelivered; may be lost | Ack before processing (or auto-ack). A crash during processing loses the message |
| At-least-once | Never lost; may be duplicated | Ack after processing. A crash after processing but before the ack causes a redelivery. The practical default everywhere |
| Exactly-once | Processed exactly once | Not achievable end to end across arbitrary systems. Effectively-once = at-least-once delivery + idempotent processing (or atomic offset commits within one system, like Kafka transactions for read-process-write within Kafka) |
The consequence for application code: every consumer must be idempotent, or deduplicate. Plan for duplicates, reordering, and poison messages.
Kafka essentials
// Producer: durable writes, idempotence, a meaningful key for ordering
@Service
class OrderEventsPublisher {
private final KafkaTemplate<String, OrderEvent> kafka;
OrderEventsPublisher(KafkaTemplate<String, OrderEvent> kafka) { this.kafka = kafka; }
CompletableFuture<SendResult<String, OrderEvent>> publish(OrderEvent e) {
return kafka.send("orders.events.v1", e.orderId(), e); // key = orderId → all events of one order in order
}
}
spring.kafka:
bootstrap-servers: kafka:9092
producer:
acks: all # wait for all in-sync replicas (with min.insync.replicas=2 on the topic)
properties:
enable.idempotence: true # broker deduplicates producer retries (sequence numbers per partition)
delivery.timeout.ms: 120000
linger.ms: 5 # small batching delay for throughput
compression.type: zstd
consumer:
group-id: billing
auto-offset-reset: earliest
enable-auto-commit: false # the Spring listener container commits after processing
isolation-level: read_committed
listener:
ack-mode: record # commit the offset after each record is processed (or batch)
@Component
class BillingListener {
@KafkaListener(topics = "orders.events.v1", concurrency = "3") // ≤ number of partitions
void on(OrderEvent event, @Header(KafkaHeaders.RECEIVED_KEY) String key) {
switch (event) {
case OrderPlaced p -> billing.createInvoice(p); // must be idempotent
case OrderCancelled c -> billing.voidInvoice(c);
default -> {} // tolerate new event types
}
}
}
// Error handling: retry with backoff, then publish to a dead-letter topic
@Bean
DefaultErrorHandler kafkaErrorHandler(KafkaTemplate<Object, Object> template) {
var recoverer = new DeadLetterPublishingRecoverer(template); // → orders.events.v1-dlt
var backoff = new ExponentialBackOffWithMaxRetries(5); // 0.5 s, 1 s, 2 s, 4 s, 8 s
backoff.setInitialInterval(500);
backoff.setMultiplier(2.0);
var handler = new DefaultErrorHandler(recoverer, backoff);
handler.addNotRetryableExceptions(DeserializationException.class, ValidationException.class); // poison: DLT immediately
return handler;
}
Core Kafka concepts:
- Topic: a named stream, split into partitions. Each partition is an append-only, ordered log replicated across brokers (a leader plus followers;
replication.factor=3,min.insync.replicas=2). - Key → partition (by hash). Ordering is guaranteed only within a partition, so key by the entity whose events must stay ordered (
orderId). - Consumer group: partitions are distributed across the group's members. Parallelism ≤ partition count. Adding consumers beyond the number of partitions leaves them idle.
- Offsets: each group commits its position per partition. On restart or rebalance, consumption resumes from the last committed offset, so anything processed but not yet committed is reprocessed (at-least-once).
- Rebalances: when consumers join or leave (deploys, crashes, slow processing exceeding
max.poll.interval.ms), partitions are reassigned. Cooperative rebalancing and static membership reduce the disruption. - Retention and compaction: delete old segments by time or size, or compact, keeping the latest value per key, which is good for "current state" topics and changelogs.
- Schemas: use Avro, Protobuf or JSON Schema with a schema registry and compatibility rules (BACKWARD, FORWARD, FULL), so producers and consumers evolve independently (chapter 45's compatibility rules apply to events too).
- Transactions / exactly-once semantics for read-process-write within Kafka (consume from A, produce to B, commit offsets atomically). They don't extend to external databases. For those, use idempotent consumers or the outbox.
RabbitMQ essentials
@Configuration
class RabbitConfig {
@Bean TopicExchange orders() { return new TopicExchange("orders"); }
@Bean Queue emailQueue() {
return QueueBuilder.durable("email.order-confirmations")
.quorum() // replicated (Raft) quorum queue
.deadLetterExchange("orders.dlx") // rejected/expired messages go here
.deliveryLimit(5) // poison message protection (quorum queues)
.build();
}
@Bean Binding emailBinding() { return BindingBuilder.bind(emailQueue()).to(orders()).with("order.placed.#"); }
}
@Component
class EmailWorker {
@RabbitListener(queues = "email.order-confirmations", concurrency = "2-8")
void handle(OrderPlaced e) { // AUTO ack mode: ack after success, nack/requeue on exception
if (sentEmails.alreadySent(e.orderId())) return; // idempotency check
mailer.sendConfirmation(e);
sentEmails.record(e.orderId());
}
}
// Producer side: rabbitTemplate.convertAndSend("orders", "order.placed.eu", event) with publisher confirms enabled
Concepts: exchanges route messages to queues through bindings (direct, topic with wildcards, fanout, headers). Durable queues and persistent messages survive broker restarts. Publisher confirms acknowledge the producer's send. Consumer acks (manual or auto-after-success) and the prefetch count (how many unacked messages a consumer holds) control flow and fairness. Quorum queues (Raft-replicated) are the recommended durable queue type. Streams add Kafka-like append-only logs inside RabbitMQ.
Cloud queues
| Service | Model | Notes |
|---|---|---|
| AWS SQS | Queue (standard: at-least-once, best-effort order; FIFO: ordered per message group, deduplication window) | Visibility timeout: a received message is hidden for N seconds and reappears if not deleted. Long polling. Redrive policy to a DLQ after maxReceiveCount. Spring Cloud AWS provides @SqsListener |
| AWS SNS + SQS | Pub/sub fan-out to multiple queues | The standard AWS fan-out pattern; EventBridge for routing rules |
| Google Pub/Sub | Pub/sub with subscriptions (push or pull), ordering keys, exactly-once delivery option (within Pub/Sub) | Ack deadline extension |
| Azure Service Bus | Queues and topics/subscriptions, sessions (ordered groups), duplicate detection, scheduled messages, dead-lettering | Rich enterprise messaging |
| Kinesis / Event Hubs | Partitioned logs (Kafka-like); Event Hubs speaks the Kafka protocol | Streaming |
Dead-letter queues
A poison message fails every time: malformed data, a bug, or a reference to something that doesn't exist. Without protection, it's redelivered forever, blocking a partition (Kafka) or burning CPU (queues). A dead-letter queue/topic (DLQ/DLT) receives messages that exceeded their retry limit or hit non-retryable errors:
- Distinguish transient from permanent failures. Retry transient ones (timeouts, 503s, lock conflicts) with exponential backoff and jitter (chapter 52). Send permanent ones (deserialisation errors, validation failures) to the DLQ immediately.
- Keep context: original topic, partition and offset, exception class, message and stack trace, retry count, timestamps. Spring's
DeadLetterPublishingRecovereradds these as headers. - Alert on DLQ depth > 0. A DLQ nobody watches is a silent data-loss mechanism.
- Tooling to inspect, fix and replay: after fixing the bug, re-publish DLQ messages to the main topic (idempotent consumers make this safe).
- Retry topics (Kafka): non-blocking retries via
orders-retry-1mandorders-retry-10mtopics (Spring Kafka's@RetryableTopic), so one failing message doesn't block its partition. The cost is per-key ordering.
The transactional outbox
The dual-write problem: a service must update its database and publish an event. Two separate systems can't be updated atomically:
- write to the DB, then publish: a crash in between, or a broker outage, means the event is lost;
- publish, then write: the DB write fails, so a phantom event describes something that didn't happen;
- distributed transactions (XA/2PC) are slow, fragile, and unsupported by most brokers.
The transactional outbox solves it:
@Transactional
public Order place(PlaceOrder cmd) {
Order order = orders.save(Order.from(cmd));
outbox.save(new OutboxEvent(
UUID.randomUUID(), // event ID: consumers deduplicate on it
"Order", order.getId().toString(), // aggregate type + ID (also the Kafka key)
"OrderPlaced", json.write(OrderPlaced.from(order)),
Instant.now()));
return order; // both rows commit atomically, or neither does
}
Two ways to relay:
- Polling publisher: a scheduled job selects unpublished rows (
ORDER BY id LIMIT 100 FOR UPDATE SKIP LOCKED), publishes them, and marks them published. It's simple, with some latency and DB load, and it needs a single active poller or row locking. - Change data capture (CDC): Debezium reads the database's write-ahead log (PostgreSQL logical replication, MySQL binlog) and publishes outbox inserts to Kafka (with the outbox event router). It has low latency and no polling queries, but it's more infrastructure.
Libraries: Spring Modulith's event publication registry (persists @ApplicationModuleListener events and can externalise them to Kafka/AMQP), Eventuate Tram, and Debezium's outbox router. Other ecosystems: MassTransit and NServiceBus have built-in outboxes (.NET), Watermill has Go outbox components, Oban jobs are inserted in the same transaction (Elixir), and Rails/Sidekiq uses after_commit hooks (which still risk loss on crash; database-backed job queues avoid it).
The mirror pattern on the consumer side is the inbox: record processed message IDs in the same transaction as the consumer's state changes.
Idempotent consumers
Since delivery is at-least-once, consumers must make duplicates harmless:
@KafkaListener(topics = "orders.events.v1", groupId = "billing")
@Transactional
public void on(ConsumerRecord<String, String> rec) {
UUID eventId = UUID.fromString(new String(rec.headers().lastHeader("eventId").value(), UTF_8));
// Inbox: the insert fails (unique constraint) if this event was already processed
int inserted = jdbc.sql("INSERT INTO processed_events(event_id, processed_at) VALUES (?, now()) ON CONFLICT DO NOTHING")
.param(eventId).update();
if (inserted == 0) return; // duplicate: already handled
billing.createInvoice(parse(rec.value())); // same transaction as the inbox row
}
Idempotency techniques, from simplest:
- Natural idempotency: "set status to SHIPPED" and upserts keyed by business ID (
INSERT … ON CONFLICT (order_id) DO UPDATE) are harmless when repeated. - Deduplication table (inbox) keyed by message ID, written in the same transaction as the effect.
- Version or sequence checks: apply an event only if its sequence number is greater than the last applied for that entity. This also handles reordering.
- Idempotency keys passed downstream: when the consumer calls an external API (a payment provider), use the event ID as the provider's idempotency key (chapter 45).
Ordering
- Per-key ordering is usually what matters ("events for order 42 in order"), and partitioned logs give it when the key is the entity ID. Global ordering doesn't scale (a single partition) and is rarely needed.
- Ordering breaks under parallel processing within a partition, retries that requeue a message behind later ones, retry topics, and multiple producers for the same key. Design consumers to tolerate reordering where possible: version checks, commutative updates, state machines that reject impossible transitions and park messages for later.
- Concurrency inside a partition (the Confluent Parallel Consumer, per-key parallelism) raises throughput while keeping per-key order.
Workflows and sagas
Multi-step business processes across services (reserve stock → charge payment → create shipment, with compensation on failure) are sagas. They're coordinated by choreography (services react to each other's events) or orchestration (a coordinator tells each service what to do). Durable workflow engines (Temporal, Camunda/Zeebe, AWS Step Functions, Azure Durable Functions, Restate) persist workflow state and turn "write code that survives crashes and waits for days" into ordinary-looking code. Vol. 5 covers sagas, compensation and workflow engines in depth.
Jobs and messaging across languages
| Ecosystem | In-process | Durable job queues | Messaging clients |
|---|---|---|---|
| Java/Spring | @Async, executors, virtual threads, @Scheduled |
JobRunr, db-scheduler, Quartz, Spring Batch; Temporal Java SDK | Spring Kafka, Spring AMQP, Spring Cloud Stream (binder abstraction), Spring Cloud AWS (SQS), Spring Pulsar |
| Go | goroutines + channels, errgroup, time.Ticker |
River (Postgres-backed, transactional enqueue), Asynq (Redis), Temporal Go SDK (Temporal itself is written in Go) | franz-go and confluent-kafka-go, amqp091-go, Watermill (an abstraction with outbox support) |
| Rust | tokio::spawn, JoinSet, tokio::time::interval |
apalis (Redis/Postgres/SQLite), fang, graphile-worker-rs | rdkafka, lapin (AMQP), async-nats |
| C#/.NET | Task.Run, BackgroundService/IHostedService, Channel<T> |
Hangfire, Quartz.NET, Coravel; Temporal .NET SDK | Confluent.Kafka, MassTransit/NServiceBus (sagas, outbox, retries), Azure Service Bus SDK |
| Python | asyncio.create_task, concurrent.futures |
Celery (Redis/RabbitMQ), RQ, Dramatiq, arq; Temporal Python SDK | confluent-kafka, aiokafka, aio-pika |
| Ruby | Threads | Sidekiq (Redis), GoodJob and Solid Queue (Postgres; Rails 8's default) | ruby-kafka, Bunny |
| Elixir | Task, GenServer, Task.Supervisor |
Oban (Postgres-backed, enqueued in the same transaction, unique jobs, cron, rate limits) | Broadway (Kafka/SQS/RabbitMQ pipelines with backpressure, batching and acks), brod |
| Node | Promises, worker threads | BullMQ (Redis), Graphile Worker (Postgres) | KafkaJS, amqplib |
A trend worth noticing: Postgres-backed job queues (Oban, River, GoodJob, Solid Queue, Graphile Worker, JobRunr, db-scheduler) are popular because enqueueing a job in the same transaction as the business change gives outbox-like atomicity with no extra infrastructure. They're built on SELECT … FOR UPDATE SKIP LOCKED and LISTEN/NOTIFY. They're excellent up to quite high volumes, beyond which a dedicated broker wins.
Lab: five ways asynchronous work goes wrong
JDK 21 and PostgreSQL 16, with the database standing in for both a job queue and a broker (the failure modes are identical with Kafka, RabbitMQ or SQS; only the APIs differ). Each experiment reproduces a bug that routinely reaches production.
Experiment 1: work queued in memory
ExecutorService ex = Executors.newFixedThreadPool(4);
for (int i = 1; i <= 100; i++) ex.submit(() -> { sleep(50); record that SMS i was sent; });
sleep(500); Runtime.getRuntime().halt(1); // a deploy, an OOM kill, a node failure
100 confirmation SMS tasks queued in memory; the process is killed 0.5 s later
after restart: 36 of 100 SMS were sent; the rest are gone, with no record they ever existed
Sixty-four customers never got their confirmation, and nothing anywhere says so. Graceful shutdown (chapter 47) would have helped for a deploy, by draining the executor first, but not for a crash or an out-of-memory kill. Use in-memory async only for work you can afford to lose or can recompute, and put everything else in durable storage first.
Experiment 2: competing workers
Four workers process 1,000 jobs from one table; each job's side effect is recorded:
SELECT then UPDATE (no locking): side effects 2695, duplicated jobs 890, 1739 ms
SELECT … FOR UPDATE SKIP LOCKED: side effects 1000, duplicated jobs 0, 666 ms
Without locking, workers kept picking the same "first ready job" before any of them had marked it done: 890 of 1,000 jobs ran more than once, and the total work was 2.7× what was needed. FOR UPDATE locks the chosen row until commit, and SKIP LOCKED makes other workers pass over it to the next free row instead of waiting, so the workers spread out and finished 2.6× faster. This is the standard PostgreSQL queue pattern (used by libraries such as JobRunr, db-scheduler, Oban in Elixir, river in Go and Solid Queue in Rails). It works well up to thousands of jobs per second; beyond that, or for fan-out to many services, use a broker.
Experiment 3: redelivery after a crash
A consumer sends the SMS, then crashes before acknowledging the message, so the message is delivered again:
plain consumer: SMS sent 2 time(s)
consumer that records message ids it has done: SMS sent 1 time(s)
This is at-least-once delivery, the guarantee every practical broker gives: a message is redelivered whenever its processing isn't confirmed (crash, timeout, rebalance, network failure). The fix is in the consumer: record each processed message id (INSERT INTO processed … ON CONFLICT DO NOTHING) and skip ids already seen. That protection is exact when the record and the consumer's own changes commit in one database transaction. For effects in other systems, like this SMS, there's a remaining window between sending and recording: close it by passing the message id as an idempotency key to the provider (chapter 45), as payment and messaging APIs support, or accept and detect rare duplicates. "Exactly-once" features (Kafka transactions) cover reads and writes within Kafka itself, not your database or a third-party API.
Experiment 4: dual writes versus the outbox
dual writes: orders in DB [1], events on broker [OrderPlaced 2] → order 1 has no event, event 2 has no order
outbox before relay: orders [1], outbox [OrderPlaced 1]
after the relay runs: orders [1], broker [OrderPlaced 1] → consistent
Order 1 was committed and then the broker was unreachable: the kitchen never heard about a paid order. Order 2's event was published and then its database transaction failed: the kitchen started cooking an order that doesn't exist. No ordering of two independent writes avoids both. With the outbox, the order and an outbox row commit or roll back together (order 2's failure removed its event too), and a relay (a polling loop as here, or change-data capture with Debezium reading the database log) publishes outbox rows afterwards, at least once. Consumers deduplicate as in experiment 3. The same pattern in reverse, the inbox, makes consumption atomic with the consumer's writes.
Experiment 5: a poison message
Four jobs; job 2 has an invalid phone number and fails every time:
job 1 done at 44 ms
job 2 failed (attempt 1), retry in 50 ms
job 3 done at 87 ms
job 4 done at 98 ms
job 2 failed (attempt 2), retry in 100 ms
job 2 failed (attempt 3), retry in 200 ms
job 2 failed (attempt 4), retry in 400 ms
job 2 failed (attempt 5) → DEAD
final: [1:DONE:1, 2:DEAD:5, 3:DONE:1, 4:DONE:1] | dead job's error: [invalid phone number]
Three properties made this safe. Retries used exponential backoff (50, 100, 200, 400 ms; add jitter in production so many failing jobs don't retry in lockstep), and run_after let other jobs run meanwhile, so jobs 3 and 4 weren't blocked behind job 2. Retries were bounded: after five attempts the job became DEAD with its error recorded, for a person to fix or discard, instead of retrying forever. And failures were classified: an invalid phone number will never succeed, so a real worker would dead-letter it immediately and reserve retries for transient errors (timeouts, 503s). In a partitioned log like Kafka, a message that blocks its partition stops every message behind it, so consumers must catch, retry a bounded number of times, then publish to a dead-letter topic and move on.
Try it yourself
- Change experiment 1's executor to save jobs in the
jobtable first and have the executor only wake the worker. Kill it again: what survives? - Add a lease column (
locked_until) to experiment 2 so a worker can claim a job, commit, do slow work outside the transaction, and another worker can reclaim the job if the first dies. - Use PostgreSQL's
LISTEN/NOTIFYto wake workers immediately instead of polling, and measure the latency from insert to processing. - Reproduce experiment 4 with a real Kafka or RabbitMQ container (Testcontainers, chapter 54) and Debezium as the relay.
Revision sheet: asynchronous work, jobs and messaging
Key ideas
- Where work runs: in the request (the user needs the result), in-process async (best effort), durable jobs (must happen, same service), messaging (other services react).
- In-process: executors (virtual threads for I/O),
@Async,CompletableFuture,@Scheduled(and the single-instance problem: ShedLock, leader election), graceful draining. - Durable jobs: job tables with
FOR UPDATE SKIP LOCKED, leases,run_after, attempts, backoff with jitter, dead states; JobRunr, db-scheduler, Quartz. - Messaging models: point-to-point queues vs publish/subscribe; queues (RabbitMQ exchanges and bindings, SQS) vs logs (Kafka topics, partitions, offsets, consumer groups, retention, compaction).
- Guarantees: at-most-once, at-least-once (the practical default), effectively-once via idempotency; Kafka idempotent producers and transactions within Kafka.
- Patterns: transactional outbox (polling or CDC with Debezium), inbox/idempotent consumer, dead-letter queues, retry topics, ordering by key/partition, sagas (choreography vs orchestration) and durable workflow engines (Temporal).
- Elsewhere: Celery/RQ/Dramatiq (Python), Sidekiq/Solid Queue (Ruby), BullMQ (Node), Oban (Elixir), river/asynq (Go), Hangfire/MassTransit (.NET).
Numbers to remember
- Lab: a crash lost 64 of 100 in-memory tasks; unlocked competing workers ran 890 of 1,000 jobs more than once (2,695 side effects); one redelivery doubled an SMS without deduplication; a poison job retried at 50/100/200/400 ms then went dead without blocking others.
Pitfalls
- Business-critical work in memory only;
@Asyncmethods losing exceptions. - Dual writes to the database and a broker; publishing inside a transaction that may roll back.
- Non-idempotent consumers; deduplication records committed separately from the effects.
- Unbounded retries, retries without backoff or jitter, poison messages blocking partitions.
- Assuming global ordering; changing partition keys; large messages instead of references.
- Scheduled jobs running on every instance.
Glossary
- At-least-once: every message is delivered one or more times.
- Idempotency key: an identifier that lets a receiver ignore repeats.
- Outbox: a table of events written in the business transaction, published later.
- Dead-letter queue: where messages go after failing too often.
- Consumer group: consumers sharing a topic's partitions, each partition read by one member.
- Saga: a sequence of local transactions with compensating actions instead of a distributed transaction.