Async Processing
Some Orders work should leave the request thread immediately: audit writes, thumbnail generation, non-critical notifications.
Introduction
Some Orders work should leave the request thread immediately: audit writes, thumbnail generation, non-critical notifications.
Boot 3 enables this with @EnableAsync and @Async methods returning void or CompletableFuture. Always define an explicit ThreadPoolTaskExecutor — the default unbounded behavior is risky under load.
@Async only works through Spring proxies (no self-invocation). For durable, retryable workloads, prefer Kafka/SQS over in-process threads.
This lesson configures a bounded pool for TechLearningPRO Orders side effects.
Purpose of this lesson
Offload non-critical Orders work with @Async and a bounded executor on Boot 3 / Java 21.
Understanding the topic
Async is best-effort parallelism inside the JVM — not a message bus.
- @EnableAsync: activates annotation-driven async.
- executor bean: core/max/queue/prefix tuned to load.
- proxy rule: external bean call required.
- context: SecurityContext propagation needs explicit config if required.
- graduation path: move durable work to a broker.
Step-by-step explanation
- Add
AsyncConfigwith@EnableAsyncand a namedThreadPoolTaskExecutor. - Annotate
AuditService.recordwith@Async("ordersExecutor"). - Call it from
OrderService(different bean), not from a private method on itself. - Load-test and watch queue rejection metrics when the pool saturates.
Informative example
Bounded async executor and Orders audit offload.
@Configuration@EnableAsyncpublic class AsyncConfig {@Bean(name = "ordersExecutor")ThreadPoolTaskExecutor ordersExecutor() {ThreadPoolTaskExecutor ex = new ThreadPoolTaskExecutor();ex.setCorePoolSize(8);ex.setMaxPoolSize(32);ex.setQueueCapacity(500);ex.setThreadNamePrefix("orders-async-");ex.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());ex.initialize();return ex;}}@Servicepublic class AuditService {private final AuditRepository audits;public AuditService(AuditRepository audits) {this.audits = audits;}@Async("ordersExecutor")public CompletableFuture<Void> record(AuditEvent event) {audits.save(event);return CompletableFuture.completedFuture(null);}}
Real-world use
Orders audit logging once used the default async executor during a flash sale and spawned thousands of threads until the pod OOM-killed. A bounded pool with CallerRunsPolicy degraded latency gracefully instead of crashing.
Security implications
Async threads can drop or mishandle security context.
- Do not assume
SecurityContextHolderis present in @Async threads without a decorator. - Never log tokens when copying context for debugging.
- Reject tasks clearly when the pool is saturated rather than silently dropping audited security events.
Best practices
- Name executors; never rely on the hidden default for production.
- Propagate MDC/request ids into async threads for tracing.
- Escalate to Kafka when work must survive process death.
Common mistakes
- Calling
@Asyncmethods onthisinside the same class. - Unbounded queues that hide backpressure until memory dies.
- Using @Async for payment capture that must not be lost on restart.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhy configure your own ThreadPoolTaskExecutor?+
Answer
2IntermediateQuestionWhy might @Async appear to do nothing?+
Answer
3IntermediateQuestionWhen is a message queue better than @Async?+
Answer
Hands-on exercise
Lab. Configure ordersExecutor and an @Async audit method. Demonstrate that a same-class call stays synchronous, then fix it by calling through another bean. Saturate the queue and observe CallerRunsPolicy.
Summary
Async processing keeps TechLearningPRO Orders responsive: explicit executors for best-effort work, brokers when durability matters.