wasAsked.

Compare scheduled jobs, asynchronous methods, and message queues for long-running Spring Boot work.

Flipkart · Full Stack Developer · 3-4-years · technical

Published

Year not specified · Java, Spring Boot, Messaging

Community answers

Posted by wasAsked editorial collection

Spring Boot offers several ways to move work out of the HTTP request; each fits a different need. 1. Scheduled jobs (@Scheduled) @Scheduled(cron = "0 0 2 * * *") public void nightlyReport() { ... } - Enabled with @EnableScheduling; runs at fixed times or intervals. - Good for: nightly reports, cleanups, periodic synchronisation. - Caveat: with several instances, every instance runs the job. Use ShedLock (database-based locking), Quartz in clustered mode, or a platform scheduler (Kubernetes CronJob) so it runs once. - Jobs are not durable by default: if the app is down at the scheduled time, the run is missed unless you track state. 2. Asynchronous methods (@Async) @Async public CompletableFuture<Void> sendWelcomeEmail(User user) { ... } - Enabled with @EnableAsync; runs the method on a separate thread pool (configure a ThreadPoolTaskExecutor with limits; virtual threads are an option with Java 21+). - Good for: short fire-and-forget work inside the same process (sending an email after registration). - Caveats: work is lost if the process crashes or restarts; there is no retry or persistence; self-invocation within the same class bypasses the proxy, so @Async has no effect; exceptions in void methods need an AsyncUncaughtExceptionHandler. 3. Message queues (RabbitMQ, Kafka, Amazon SQS, Azure Service Bus) - The API publishes a message and returns 202 Accepted with a job ID; separate consumers (@RabbitListener, @KafkaListener) process it. - Good for: long-running or important work (video processing, payment workflows, bulk imports), work that must survive restarts, and scaling workers independently. - Benefits: durability, retries with backoff, dead-letter queues, load levelling and horizontal scaling. - Requirements: idempotent consumers (at-least-once delivery), the transactional outbox pattern for reliable publishing, and monitoring of queue depth. Choosing - Time-based recurring work: scheduled job with distributed locking. - Quick, non-critical in-process side effects: @Async (or Spring application events with @TransactionalEventListener). - Long-running, critical or high-volume work, or work spanning services: a message queue. Also mention Spring Batch for large, chunked batch processing with restartability, and exposing job status to the frontend instead of holding HTTP requests open.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics