Workbench / Volume 3 Exercises: The Backend
V3·51
Async Work, Jobs & Messaging
Exercises for Volume 3, chapter 51: choosing synchronous or asynchronous work; async tasks, executors and futures; scheduled jobs; background workers and in-process queues; messaging models; delivery guarantees; Kafka and RabbitMQ essentials; cloud queues; dead-letter queues; the transactional outbox; idempotent consumers; ordering; workflows and sagas; and jobs and messaging across languages. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.
Start here: how this chapter's exercises work
The four sets and the locking work as before. The code runs on JDK 21, PostgreSQL 16 and Redis 7 Streams (as a real broker with consumer groups). Kafka and RabbitMQ weren't available offline, so their exercises give expected behaviour, marked as such. Every quoted output is real, and four of them catch experienced developers:
- P2. A
scheduleAtFixedRatejob that threw once on its third run never ran again.isDonewastrue, and nothing was logged anywhere. ACompletableFuture.runAsyncthat threw and was never joined also printed nothing. - P3. A bounded pool with
DiscardPolicycompleted 12 of 100 tasks and reported no error.AbortPolicythrew for 88, andCallerRunsPolicycompleted all 100 by slowing the submitter to 306 ms. - P5. Five orders' status events (200 each) through a shared pool of 8 threads arrived out of order 309 times. Partitioning by order id onto 8 single-threaded lanes gave 0.
- P7. In Redis Streams, a consumer that read three messages, acknowledged one and crashed left two pending. A second consumer's
XAUTOCLAIMtook them over, along with its own three unacknowledged messages, and all five then showed 2 deliveries.
The chapter's lab already covered these, and the exercises build on them rather than repeat them:
- in-memory work lost when the process died (36 of 100 SMS sent);
- competing workers without locking (2,695 side effects for 1,000 jobs) against
SKIP LOCKED(1,000); - redelivery after a crash sending an SMS twice, and an idempotent consumer sending it once;
- dual writes leaving an order without an event, against the outbox staying consistent;
- a poison message retried with backoff and sent to a dead-letter state.
Coverage map.
| Chapter component | Exercises |
|---|---|
| synchronous against asynchronous | T1 |
| async tasks, executors, futures | T2, P1, P2 |
| scheduled jobs | T3, P2 |
| background workers; in-process queues | T2, P3 |
| messaging models | T4, P7 |
| delivery guarantees | T5, P7 |
| Kafka essentials | T6, P8 |
| RabbitMQ essentials; cloud queues | T7 |
| dead-letter queues | T7, P6 |
| the transactional outbox | T8, P4 |
| idempotent consumers | T5, P6 |
| ordering | T6, P5 |
| workflows and sagas | T9, P9 |
| other languages | T9 |
Theory
T1. What belongs outside the request
- For each TiffinBox action, decide whether it runs synchronously in the request, asynchronously in-process, in a durable job, or as a message to other services: - charging the card at checkout; - sending the confirmation SMS; - recalculating the kitchen's daily report; - updating the search index when a dish changes; - expiring unpaid orders after 15 minutes; - notifying the delivery-partner service that an order is ready; - resizing an uploaded dish photo.
- What does the user see when work moves out of the request? Explain
202 Acceptedwith a status resource (ch45), optimistic UI, eventual consistency, and the "read your own writes" problem. - Name the costs of asynchrony: - failures nobody sees (P2); - duplicates (the lab); - ordering (P5); - observability across hops (trace context in messages); - more infrastructure; - harder testing.
When is synchronous work simply better?
T2. In-process async: executors, futures and in-process queues
- Compare
ExecutorService(fixed, cached, virtual-thread-per-task),CompletableFuturecomposition (supplyAsync,thenCompose,allOf,orTimeout,exceptionally), structured concurrency (ch38) and Spring's@Async(proxy rules from ch46, the default executor,AsyncUncaughtExceptionHandler). P2: arunAsyncthat threw and was never joined printed nothing. Why, and how do you make async failures visible? - Bounded queues and rejection (P3: a pool of 2 with a queue of 10 and 100 tasks of 10 ms):
-
AbortPolicy: 12 done, 88 exceptions; -CallerRunsPolicy: 100 done, the submit loop slowed to 306 ms; -DiscardPolicy: 12 done, silently.
Which is backpressure, which is load shedding, and which is a bug? Why is Executors.newFixedThreadPool's unbounded queue dangerous?
3. When is in-process async acceptable (losing work on a crash is fine: cache warming, metrics flushes, best-effort prefetches), and when must work be durable (anything a user or the business would miss)? How do you shut down an executor gracefully (ch47's lifecycle)?
T3. Scheduled jobs
- P2:
scheduleAtFixedRatestopped forever after one exception, silently. Explain why (theScheduledFuturecompletes exceptionally and later runs are suppressed), how Spring's@Scheduleddiffers (itsTaskUtilserror handler logs and keeps scheduling), and the rule for every scheduled job (catch, log, count, alert on absence). fixedRateagainstfixedDelay(P3: a 50 ms schedule for an 80 ms task): fixed rate started runs at 2, 82, 163, 243… ms, so back to back with no gap, 9 runs in 700 ms; fixed delay started them at 0, 130, 261, 391…, 6 runs. Also explain cron expressions with zones (zone = "Asia/Kolkata") and DST, and what happens to missed runs while the app was down.- With 6 instances,
@Scheduledruns on all 6. How do you run a job once across the cluster: ShedLock (a lock table), a leader election, a database job table withSKIP LOCKED(ch49's C3), KubernetesCronJob, or Quartz clustered? Which fits the daily kitchen report?
T4. Messaging models
- Compare: - point-to-point queues (one consumer per message; competing consumers); - publish/subscribe (every subscriber group gets every message); - logs (Kafka, Redis Streams: retained, replayable, consumers track offsets); - request/reply over messaging.
Which fits "send SMS", "an order was placed", "rebuild the search index from history", "ask the pricing service for a quote"?
2. Commands against events:
- SendSms (a command: one handler, can be rejected);
- OrderPlaced (an event: a fact in the past tense, any number of consumers).
What goes in an event (ids only, "notification", against full state, "event-carried state transfer"), and how do you version event schemas (ch45's rules, a schema registry, compatibility modes)? 3. P7's Redis Streams run showed consumer groups, pending entries and reclaiming. Map those concepts to Kafka (consumer groups, offsets, rebalancing) and RabbitMQ (queues, acks, prefetch, redelivery).
T5. Delivery guarantees and idempotent consumers
- Explain at-most-once, at-least-once and "exactly-once". P7: after the crash, the reclaimed messages showed 2 deliveries. Why is at-least-once the practical default, and why does "exactly-once" in Kafka only hold within Kafka (transactions with
read_committed), not for side effects like SMS? - Make consumers idempotent (the lab: SMS sent once with recorded message ids):
- a
processed_messages(consumer, message_id)table withINSERT … ON CONFLICT DO NOTHINGin the same transaction as the effect; - natural idempotency (UPDATE … SET status = 'PAID' WHERE id = ? AND status = 'PENDING'); - idempotency keys passed to external APIs (the SMS provider's dedupe key).
What about effects outside the database (sending the SMS) that can't share a transaction? 3. When is at-most-once acceptable (telemetry, presence pings), and how does acknowledging before processing achieve it?
T6. Kafka essentials and ordering
- Explain: - topics, partitions, offsets, segments and retention; - keys (the partitioner sends the same key to the same partition); - consumer groups (one consumer per partition per group; more consumers than partitions sit idle); - committing offsets (auto against manual, after processing); - rebalancing (cooperative sticky assignment).
How many partitions should orders have, and why can't you shrink them later?
2. Ordering. P5: 200 status events for each of 5 orders through a shared pool of 8 threads arrived out of order 309 times; key-partitioned single-threaded lanes gave 0. Explain why Kafka guarantees order only within a partition, why the key must be the entity id (orderId), and how parallel processing inside a consumer (a thread pool) destroys ordering unless you partition by key there too (Confluent's parallel consumer, P5's lanes).
3. Producer settings: acks=all, enable.idempotence=true, max.in.flight.requests.per.connection ≤ 5, retries, linger.ms, batch.size, and compression. What happens to ordering and duplicates with retries if idempotence is off?
T7. RabbitMQ, cloud queues and dead-letter queues
- RabbitMQ essentials:
- exchanges (direct, topic, fanout, headers), bindings and queues;
- acks,
basic.nack/rejectwith requeue; - prefetch (basic.qos); - durable queues and persistent messages; - publisher confirms; - quorum queues (Raft-replicated) against classic queues; - streams.
Design TiffinBox's topology for order.placed (fanout to notification, loyalty and analytics) and sms.send (a work queue).
2. Cloud queues:
- SQS (visibility timeout, at-least-once, FIFO queues with MessageGroupId and deduplication ids, long polling);
- Google Pub/Sub (ack deadlines, ordering keys);
- Azure Service Bus (sessions).
What's the equivalent of P7's idle reclaim in SQS?
3. Dead-letter queues. The lab sent a poison message to a dead state after retries. Design DLQ handling: max delivery counts (RabbitMQ x-delivery-limit on quorum queues, SQS maxReceiveCount, Kafka retry topics plus DLT in Spring Kafka), what to store with the dead message (error, stack, attempts, original topic and offset), alerting, inspection tooling, and redrive after a fix. Why must a poison message not block its partition in Kafka forever?
T8. The transactional outbox
- The lab: dual writes (save the order, then publish) produced an order with no event and an event with no order, while the outbox stayed consistent. Explain both failure orders (commit then publish fails; publish then commit fails), and why "publish inside the transaction" doesn't fix it.
- Design the outbox: the table (
id,aggregate_type,aggregate_id,type,payload jsonb,headers,created_at,published_at), writing it in the same transaction as the state change, and relaying by either: - polling (SELECT … FOR UPDATE SKIP LOCKED LIMIT 100, publish, mark published; ch49's P9); P6 measured polling every 500 ms at an average 276 ms latency (max 742), against LISTEN/NOTIFY at 4.6 ms (max 11); - change data capture (Debezium reading the write-ahead log, with the outbox event router).
Compare them.
3. What ordering and duplicate guarantees does the relay give (at-least-once; order per aggregate if published in id order per key), and what does the consumer side need (idempotency, T5)? What is the inbox pattern?
T9. Workflows, sagas, and other languages
- Placing an order touches payments, the kitchen and delivery. Design it as a saga: - choreography: services react to each other's events; - orchestration: a coordinator sends commands and tracks state.
Include compensations (refund the payment if the kitchen rejects) and timeouts (the kitchen doesn't answer in 5 minutes). When does a workflow engine (Temporal, Camunda, AWS Step Functions) pay off?
2. Why can't sagas give isolation? Describe semantic locks (PENDING states), commutative updates and reordering steps so the riskiest come first.
3. Compare jobs and messaging elsewhere:
- Python (Celery with RabbitMQ or Redis; RQ; Dramatiq);
- Node (BullMQ on Redis);
- Ruby (Sidekiq);
- .NET (Hangfire, MassTransit);
- Go (asynq, Watermill).
Which give at-least-once with retries and DLQs by default, and which pitfalls (in-memory loss, non-idempotent tasks, task arguments holding stale data) recur?
Programming exercises
P1. CompletableFuture fan-out with timeouts and visible failures
Implement "after an order is placed, prefetch the kitchen's ETA, warm the customer's cache and record an analytics event" in-process:
- CompletableFuture.supplyAsync on a named, bounded executor (or virtual threads);
- orTimeout per task;
- allOf with a total deadline;
- failures logged and counted, never swallowed.
Show what a fire-and-forget future that throws prints without handling (P2) and with whenComplete.
P2. Scheduled jobs that don't die silently
- Reproduce the
scheduleAtFixedRatefailure (a run throws, and later runs are suppressed). - Measure fixed rate against fixed delay with a task slower than the period.
- Then write a
SafeJobwrapper (catch, log, count, record last success), a "stale job" alert rule, and a ShedLock-style lock table for running once across instances, tested with two schedulers sharing PostgreSQL.
P3. Bounded executors and rejection policies
With a ThreadPoolExecutor of 2 threads and a queue of 10, submit 100 tasks of 10 ms under AbortPolicy, CallerRunsPolicy and DiscardPolicy, and record done, rejected and submit time. Then build an in-process SMS buffer that sheds load with a 503 problem when full, and explain why the real fix is a durable queue.
P4. The outbox with polling and LISTEN/NOTIFY
Implement the outbox for OrderPlaced:
- write the order and the outbox row in one transaction;
- a relay with SKIP LOCKED batches that publishes to Redis Streams (XADD) and marks rows published;
- measure the latency from commit to publish with polling every 500 ms, and with LISTEN/NOTIFY plus a 5-second fallback poll;
- kill the relay mid-batch, and show the duplicates the consumer must tolerate.
P5. Ordering per key
Replay 5 orders' status events (200 each) through a shared pool of 8 threads and through 8 key-partitioned single-threaded lanes, and count out-of-order events per order. Then implement a lane-based consumer for Redis Streams or Kafka records that processes different orders in parallel while preserving each order's sequence, and decide what to do with an event older than the order's current state (an eventVersion check).
P6. Idempotent consumers, retries and a dead-letter queue
Build an SMS consumer on Redis Streams:
- an idempotency table in PostgreSQL;
- a provider dedupe key;
- retries with exponential backoff and jitter for transient errors (simulated 503s);
- immediate dead-lettering for permanent errors (an invalid phone);
- a delivery-count limit using XPENDING's delivery counts;
- a DLQ stream with full context;
- a redrive command.
Show counts after 1,000 messages with 5% transient and 1% permanent failures.
P7. Consumer groups, crashes and reclaiming
With Redis Streams:
1. create a stream and a consumer group;
2. have consumer c1 read 3 messages, acknowledge 1, and "crash";
3. inspect XPENDING;
4. have c2 read new messages, then XAUTOCLAIM idle ones;
5. explain the delivery counts.
Then write the equivalent sequence for Kafka (a consumer committing offsets after processing, killed mid-batch) and RabbitMQ (manual ack, channel closed), with expected redeliveries.
P8. Kafka with Spring for Apache Kafka
Configure (expected behaviour if Kafka isn't available):
- a producer with acks=all, idempotence and keys by orderId;
- a @KafkaListener with manual acks after processing, concurrency equal to the partition count, and an ErrorHandlingDeserializer for poison payloads;
- a DefaultErrorHandler with exponential backoff and a DeadLetterPublishingRecoverer;
- @RetryableTopic for non-blocking retries;
- Testcontainers tests for ordering per key, redelivery after a forced crash, and the dead-letter topic.
P9. An order saga with an orchestrator
Implement the T9 saga as an orchestrator:
- an order_saga table (state, step deadlines, version);
- commands sent via the outbox;
- events consumed idempotently;
- timeouts via delayed jobs (ch49's C3);
- compensations (refund, cancel);
- a state-machine test covering the happy path, a kitchen rejection, a kitchen timeout, a payment failure and a duplicate event.
Cumulative projects (chapters so far: Volume 1, Volume 2, and Volume 3's 33–51)
C1. TiffinBox's event backbone
Build the event backbone: - an outbox in the order, payment and kitchen services (P4); - a relay (LISTEN/NOTIFY plus a fallback poll, or Debezium); - topics or streams with keys by aggregate id; - versioned event envelopes with trace context (ch47); - idempotent consumers with inboxes (T8); - retries and DLQs with redrive tooling (P6); - lag, DLQ depth and oldest-pending metrics with alerts; - contract tests for event schemas (ch45); - a replay tool for rebuilding read models.
Combines: ch44's architecture, ch45's contracts, ch47's observability, ch49's persistence, and this chapter.
C2. Notifications that never double-send and never vanish
Build the notification service: SMS, email and push for order events, with: - per-channel workers; - templates; - customer preferences and quiet hours (22:00–07:00 IST, delayed rather than dropped); - provider dedupe keys; - retries with backoff, and fallback to another provider after repeated failures; - rate limits per provider (ch45's P8); - a DLQ; - delivery receipts via webhooks (ch50's P9); - a status API for support.
Load test 50,000 notifications with failure injection, and prove zero duplicates and zero losses.
Combines: ch38's concurrency, ch45's rate limits and idempotency, ch47's operations, ch49's job queue, ch50's webhooks, and this chapter.
C3. Migrate an in-memory @Async email feature to durable jobs
Take an earlier service that sends emails with @Async (the lab's experiment 1 pattern). Migrate it to the job table (ch49's C3) or a queue without losing or duplicating emails during the cutover:
- dual-run with a feature flag;
- idempotency keys;
- a drain of in-flight async tasks at shutdown;
- reconciliation;
- removing the old path.
Measure losses on kill -9 before and after.
Combines: ch46's @Async proxies, ch47's lifecycle, ch49's jobs, ch52's flags (preview), and this chapter.
What the chapter leaves out
Event sourcing and CQRS
Event sourcing stores state as a sequence of events (the order's history) and derives current state by replaying it. CQRS separates write models from read models fed by events. Both are powerful for audit-heavy domains, and costly: schema evolution of old events, replay times, snapshots, eventual consistency everywhere. Most services need an outbox and read models, not full event sourcing.
Stream processing
Kafka Streams, Flink and Spark Structured Streaming compute over event streams: windows ("orders per kitchen per 5 minutes"), joins between streams, and stateful aggregations with exactly-once state stores. TiffinBox's real-time kitchen load dashboard is a stream-processing job, not a consumer with a HashMap.
Backpressure across services
When consumers fall behind, lag grows. Options are autoscaling consumers on lag (KEDA), shedding non-critical events, prioritised queues, and limits on producers. Monitor lag in time ("5 minutes behind"), not just message counts.
Schema registries and serialisation formats
Avro and Protobuf with a schema registry give compact messages and enforced compatibility. JSON is readable and easy, but lacks enforcement without JSON Schema checks. Choose per platform, and enforce compatibility in CI either way.
Spring Modulith events and in-process event publication
Spring Modulith's @ApplicationModuleListener with an event publication registry gives outbox-like durability for events between modules in one application (ch46's T7 events, persisted and retried). It's a good step before splitting services.
Senior exercises
S1. TiffinBox's async and messaging standard
Write the standard: - when to go async; - in-process async only for best-effort work; - bounded executors with explicit rejection; - scheduled jobs wrapped, single-runner and alerted on absence; - durable jobs on PostgreSQL for service-local work; - a broker for cross-service events; - the outbox for every published event; - envelopes and schema compatibility; - keys by aggregate id; - idempotent consumers; - retry classification and DLQs with redrive; - ordering rules; - sagas with orchestration for multi-service flows; - metrics and alerts.
Tie each to an output.
S2. Review an async pull request
A PR adds:
- @Async public void sendReceipt(Order o) called from the same class's placeOrder;
- executor = Executors.newFixedThreadPool(50) for SMS;
- @Scheduled(fixedRate = 60000) that expires orders, running on all 6 instances;
- kafkaTemplate.send("orders", order) (no key) right after orderRepository.save(order) inside @Transactional;
- a consumer that adds loyalty points without checking for duplicates;
- catch (Exception e) { /* retry later */ } in the consumer, acknowledging anyway.
Write the review.
S3. Choose the messaging infrastructure
TiffinBox has PostgreSQL and Redis in production, 14 services, about 300 events per second at peak, growing to perhaps 3,000. Decide between: - PostgreSQL job tables and outbox only; - Redis Streams; - RabbitMQ (quorum queues); - Kafka (managed); - a cloud queue or pub/sub.
Write the decision record with criteria, the migration path and revisit triggers.
S4. Teach "async without surprises" with five outputs
Prepare a 20-minute session using:
- the lab's in-memory loss (36 of 100);
- P2's silent scheduled-job death;
- P3's DiscardPolicy (12 of 100, no error);
- P5's ordering (309 against 0);
- P7's reclaim (delivery count 2).
S5. Plan the messaging platform for two quarters
As platform lead, plan: - the events library (envelope, outbox, relay, consumers with inboxes, retries, DLQ, metrics); - managed Kafka adoption (S3); - migrating 5 webhook integrations to events; - the job library on PostgreSQL; - the scheduled-job hygiene sweep (P2); - schema registry and compatibility CI; - DLQ tooling; - lag-based autoscaling; - the saga orchestrator for orders (P9); - training (S4).
Give milestones, risks and metrics.