Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 55

    Async Processing

    Some Orders work should leave the request thread immediately: audit writes, thumbnail generation, non-critical notifications.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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

    1. Add AsyncConfig with @EnableAsync and a named ThreadPoolTaskExecutor.
    2. Annotate AuditService.record with @Async("ordersExecutor").
    3. Call it from OrderService (different bean), not from a private method on itself.
    4. Load-test and watch queue rejection metrics when the pool saturates.

    Informative example

    Bounded async executor and Orders audit offload.

    java
    @Configuration
    @EnableAsync
    public 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;
    }
    }
    @Service
    public 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 SecurityContextHolder is 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 @Async methods on this inside 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.

    3 questions
    1BeginnerQuestionWhy configure your own ThreadPoolTaskExecutor?+

    Answer

    The default can grow without bound; explicit core/max/queue give predictable memory and backpressure.
    2IntermediateQuestionWhy might @Async appear to do nothing?+

    Answer

    Self-invocation bypasses the Spring proxy, so the method runs synchronously on the caller thread.
    3IntermediateQuestionWhen is a message queue better than @Async?+

    Answer

    When tasks must survive crashes, retry with backoff, or scale across many instances independently of the web tier.

    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.

    Ready to mark this lesson complete?Track your journey across the entire course.