Volume 3 Companion: The BackendPractice for Volume 3
0 / 0

Workbench / Volume 3 Companion: The Backend

V3·51

Asynchronous Work, Jobs and Messaging

Companion to Volume 3, chapter 51: how choosing where work runs, in-process async, scheduled jobs and durable messaging connect; new angles (a lock as a single checkout counter, compaction as tidying a warehouse, a log as an outbox you already have); what the chapter simplifies, measured on the build's stage 52: a dashboard that made every browser's beacon wait 105 ms, a background job whose cost grew with the data until it rewrote ten bytes for every byte written, a scheduler that stops a failing job forever without a word, and the difference between logging every deprecated call and reporting who makes them; the theory behind them (lock scope, write amplification, failure as a state, the log as the outbox); how Spring's scheduler keeps a failing task alive, from its source; four debugging drills; interview questions with how to approach each.

6 sections · ~10 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 51 covers choosing where work runs (synchronous or asynchronous, in-process or durable), in-process async (executors and futures, scheduled jobs, in-process queues), durable messaging (messaging models, delivery guarantees, Kafka, RabbitMQ, cloud queues, dead-letter queues, the transactional outbox, idempotent consumers, ordering, workflows and sagas) and jobs and messaging in other languages.

where work runs in-process durable messaging making it reliable in the request the user waits after the response someone must remember in-process lost on crash durable survives restarts executors, futures bounded pools scheduled jobs fixed delay, cron in-memory queues backpressure virtual threads cheap waiting queues and topics point-to-point, pub-sub Kafka, RabbitMQ logs and brokers dead-letter queues poison messages workflows, sagas compensation at-least-once duplicates happen idempotent consumers effects once transactional outbox no dual writes ordering per key partitions or either or plus feeding on run on with across steps needs fed by keeping builds on: ch36 concurrency · ch38 races · ch44 backend · ch49 transactions · goes on: ch52 resilience · Vol 6 distributed systems exercises: P1–P9 fan-out, scheduled jobs, bounded executors, outbox, ordering, idempotent consumers, consumer groups, Kafka, a saga; C1–C3
Concept map of chapter 51, asynchronous work, jobs and messaging: choosing where work runs (synchronous or asynchronous, in-process or durable), in-process async (executors and futures, scheduled jobs, in-process queues), durable messaging (models, delivery guarantees, Kafka, RabbitMQ, cloud queues, dead letters, the outbox, idempotent consumers, ordering, sagas) and other languages, with links such as at-least-once delivery requiring idempotent consumers and the outbox removing dual writes.

The links worth remembering:

  • Async moves work in time, not out of existence. It still runs, on some thread, holding some lock, using some disk; it's just no longer in front of a user. Its cost and its failures need somewhere to show up.
  • Every durable handoff is a write followed by a read by someone else: at-least-once delivery, idempotent consumers and the outbox are what make that pair safe.
  • A job is a small service: it has a schedule, a budget, a failure mode and an owner.

Explain it differently

1. A lock is a single checkout counter. Customers (beacons) take seconds each; then someone arrives with a full trolley (the summary) and everyone behind waits. Let the trolley shopper photograph the trolley at the counter and total it at a side table (Gaps 1).

2. Compaction is tidying a warehouse. Re-shelving the whole warehouse every time a box arrives keeps it tidy and keeps the staff from doing anything else. Tidy when the mess is worth it (Gaps 2).

3. A log is an outbox you already have. The chapter's outbox writes the event in the same transaction as the change, so it can't be lost. TiffinBox's log is that: every change is a record before it's acknowledged. Anything downstream (the kitchen stream, a report, a future webhook) can read it and keep a cursor (Theory 4).

Gaps and misconceptions

What the chapter oversimplifies

All outputs are real, from OpenJDK 21.0.12 and the build's stage 51 and 52 code (exp/52), unless stated.

1. Background work still takes the lock. TiffinBox's real-user monitoring keeps up to 500 series of 5,000 values; GET /rum/summary sorted them all while holding the same lock that every incoming beacon needs. Beacons accepted one a millisecond, alone and while a dashboard asks for the summary ten times a second:

Terminal
# stage 51
alone                beacon accept: p50      9.6 us   p99      65.4 us   max    2230.6 us
while summaries run  beacon accept: p50      6.8 us   p99  105562.0 us   max  148351.2 us   (23 summaries meanwhile)
summary(): 109.1 ms each

The p99 went from 65 µs to 105 ms: a reader's convenience became every writer's latency. Stage 52 copies the values under the lock (milliseconds) and sorts outside it, and a job refreshes a cached copy every 10 seconds so readers don't compute at all:

Terminal
# stage 52
while summaries run  beacon accept: p50     10.3 us   p99      48.3 us   max    7849.9 us   (12 summaries meanwhile)

The 7.8 ms worst case is the copy. The chapter's "move it off the request" assumes the work is separable; here it wasn't until the lock's scope was cut to the part that needs it.

2. A background job's cost can grow with the data. Stage 50's compactor rewrote the whole snapshot after every segment roll. The same workload (60,000 orders, 32 KiB segments), compacting on every roll and only when the closed segments reach half the snapshot's size:

Terminal
ratio 0.0: 6.8 s; 46 compactions (0 skipped), 13,466,670 bytes appended, 137,001,661 rewritten by compaction (10.17 per byte)
           at most 61 files during the run, 3 at the end; restart 328 ms
ratio 0.5: 4.7 s; 14 compactions (222 skipped), 13,466,670 bytes appended, 25,645,701 rewritten by compaction (1.90 per byte)
           at most 127 files during the run, 13 at the end; restart 205 ms

Ten bytes written for every byte of real work, competing with the real work for the disk; the run itself took 45% longer. The ratio trades files on disk (more segments wait between compactions) for write volume. It's the knob behind Kafka's min.cleanable.dirty.ratio and LSM levels (chapter 49's companion, Theory 3). A background job needs a budget measured in the resources it shares.

3. A periodic job that throws is gone. The JDK's scheduler, with a task that fails on its third run:

Terminal
run 1
run 2
run 3
after 1 s: 3 runs; isDone=true, isCancelled=false; nothing was printed about the failure
only f.get() says why: java.lang.IllegalStateException: the third run fails

Nothing calls f.get() on a periodic task, so in practice the job just stops. Stage 52's Jobs catches failures, logs them with the job's name, counts them, and runs again on schedule; Spring's scheduler does the first three by default (Code walkthrough). A job that keeps failing quietly is no better than one that stopped, so GET /jobs shows each job's runs, failures, last success and last error:

Terminal
rum-summary    every 10s    runs      0  failures    0  last success never  last run 0 ms
usage          every 86400s runs      1  failures    0  last success <time>  last run 0 ms

The thing to alert on is "last success" older than a few periods, which catches both a job that fails and one that never runs.

4. Lines aren't a report. Stages 49 and 51 logged every deprecated call and every denial, one line each. Useful for searching, not for deciding whose code to change. Stage 52's usage job writes one line a day with the counts by caller and route:

Terminal
{"kind":"usage","since":…,"until":…,"counts":{"denied anonymous GET /kitchens/{k}/next":1,"denied anonymous POST /orders":3,"denied customer c2 GET /orders/{id}":1,"deprecated anonymous POST /orders":3}}

That's a batch job doing what batch jobs are for: turning a stream of events into a summary a person reads. The counts are in memory, so a restart loses a partial day; that's acceptable for a report and not for an order, which is the line between in-process and durable work the chapter draws.

Common misconceptions

Misconception What's actually true Where it's shown
"Background work doesn't affect requests." It shares locks, CPU and disk with them. Gaps 1, 2
"A job runs until it's stopped." On the JDK's scheduler, until it throws once. Gaps 3
"Logging every event is enough to act on." Someone needs the counts, by who and what. Gaps 4
"Async means fire and forget." It means someone else must remember: a queue, a log, a retry. The chapter's lab, Experiment 1
"Exactly-once delivery is a setting." Delivery is at-least-once; effects are made once by idempotent consumers. The chapter, "Delivery guarantees"

Theoretical gaps: the ideas behind the chapter

1. Lock scope. Hold a lock for the shortest work that needs consistency: copy, then compute. Readers that need a consistent snapshot can take one cheaply (a copy, a version, copy-on-write) and leave the expensive part outside. The same applies to database transactions: a report that holds a transaction open holds back vacuum and locks.

2. Write amplification and budgets. Background maintenance (compaction, reindexing, cache warming) consumes the same resources as foreground work. Measure it per byte or per request of real work, give it a ratio or a rate limit, and watch it in the same dashboards.

3. Failure is a state, not an event. A job's health is "when did it last succeed", not "did it throw just now". Alert on staleness; it covers crashes, hangs, a scheduler that stopped, and a deploy that forgot to register the job.

4. The log as the outbox. The transactional outbox exists so a change and its event commit together. A system whose source of truth is an append-only log already has that property: consumers read the log from a cursor they store, at least once, and act idempotently (keyed by record position or id). TiffinBox's kitchen stream reads from memory instead, which is why a reconnect after a restart gets a snapshot rather than a replay.

Applying it

Code walkthrough

Gaps 3 is a decision Spring makes for you. From spring-projects/spring-framework, main at commit 7ce40c8 (18 November 2026).

Repeating tasks swallow, one-shot tasks propagate

spring-context/src/main/java/org/springframework/scheduling/support/TaskUtils.java:

Java
	public static DelegatingErrorHandlingRunnable decorateTaskWithErrorHandler(
			Runnable task, @Nullable ErrorHandler errorHandler, boolean isRepeatingTask) {

		if (task instanceof DelegatingErrorHandlingRunnable dehRunnable) {
			return dehRunnable;
		}
		ErrorHandler eh = (errorHandler != null ? errorHandler : getDefaultErrorHandler(isRepeatingTask));
		return new DelegatingErrorHandlingRunnable(task, eh);
	}

	public static ErrorHandler getDefaultErrorHandler(boolean isRepeatingTask) {
		return (isRepeatingTask ? LOG_AND_SUPPRESS_ERROR_HANDLER : LOG_AND_PROPAGATE_ERROR_HANDLER);
	}
	...
		public void handleError(Throwable t) {
			logger.error("Unexpected error occurred in scheduled task", t);
		}

And DelegatingErrorHandlingRunnable.run:

Java
	public void run() {
		try {
			this.delegate.run();
		}
		catch (UndeclaredThrowableException ex) {
			this.errorHandler.handleError(ex.getUndeclaredThrowable());
		}
		catch (Throwable ex) {
			this.errorHandler.handleError(ex);
		}
	}

Spring's schedulers wrap every task before handing it to the JDK. A repeating task (@Scheduled(fixedDelay = …), cron) gets the log-and-suppress handler, so the exception never reaches the JDK's executor and the schedule survives; a one-shot task's exception is logged and rethrown so its Future reports it. That's Gaps 3's fix, on by default. What it doesn't give you is the state: a log line per failure, but nothing that says "this job last succeeded three days ago", which is what Theory 3 asks for (Micrometer's @Scheduled observations, if enabled, are the usual source).

Debugging drills

D1. Slow every few seconds

A service's p99 latency spikes every 10 seconds, for 100 ms, on endpoints that do almost nothing. CPU is low.

D2. The disk is busy and nobody's writing much

Disk throughput is far above what the application writes, and it grows month by month.

D3. The nightly export stopped in March

Nobody noticed for six weeks that a nightly export hadn't run. Logs from March show one exception from the job, then nothing.

D4. We can't tell who to call

A deprecated endpoint still gets traffic. The logs have a million lines about it, and nobody can say which teams to contact.

Career-oriented

Interview prep

Mid-level 1: CompletableFuture and threads

Question. "CompletableFuture.supplyAsync(task) with no executor: where does the task run, and why might that matter?"

How to get there. What's the default pool, and who else uses it?

Mid-level 2: scheduled job health

Question. "How would you know a scheduled job has stopped working?"

How to get there. What signals does a job produce, and which survive every way it can fail?

Senior 1: a slow report and a busy service

Question. "Product wants a live dashboard of order statistics. Computing it takes 200 ms over in-memory data that orders update. Design it."

How to get there. Who waits for whom, and how stale may the dashboard be?

Senior 2: replacing an in-process event bus

Question. "Our service publishes domain events to in-process listeners, and some listeners call other services. What goes wrong, and how would you change it?"

How to get there. What happens to an event when the process dies after the change commits?

Staff 1: a platform for background work

Question. "Teams run scheduled jobs in many ways (cron on VMs, @Scheduled, Kubernetes CronJobs). What should the platform offer?"

How to get there. What does every team get wrong alone?

Staff 2: when to introduce a message broker

Question. "Do we need Kafka?"

How to get there. What problem would it solve that you have now, and what would it cost?