To handle a long-running REST API in Spring Boot, you should return a response immediately and process the work asynchronously, then let the client poll for the result. The common mistake is to keep the HTTP request open for minutes, which ties up server threads and can cause timeouts. Instead, design your API to accept a job, return a job ID, and provide a separate endpoint to check status and retrieve results.
Design the API for Asynchronous Jobs
When a request will take longer than a few seconds, treat it as a job rather than a synchronous request. Create three endpoints:
- POST /api/jobs – accepts the work, starts it in the background, returns a job ID (with HTTP 202 Accepted).
- GET /api/jobs/{id} – returns the current status (e.g., PENDING, RUNNING, COMPLETED, FAILED) and any progress info.
- GET /api/jobs/{id}/result – returns the final result when the job is complete.
This pattern decouples the client from the server's processing time. The client can poll the status endpoint every few seconds, or you can add a callback URL (webhook) that the server calls when done.
Run Work in the Background with @Async
Spring Boot provides the @Async annotation to run a method in a separate thread. To enable it, add @EnableAsync to a configuration class. Then annotate a service method that does the heavy work:
@Service
public class JobService {
@Async
public void processJob(Long jobId) {
// do long work here
// update job status in database
}
}
When the controller receives a POST request, it creates a job record in the database with status PENDING, calls the async method, and returns the job ID immediately. The async method runs on a separate thread, freeing the request thread.
Important: @Async only works when called from a different bean (not from the same class). Also, the method must return void or a Future/CompletableFuture if you need to track completion.
Store Job State in a Database
To let clients query status, you need to persist the job state. Use a simple table with columns: id, status, created_at, updated_at, result (or a separate result table). Update the status as the job progresses. For example:
@Entity
public class Job {
@Id
private Long id;
private String status; // PENDING, RUNNING, COMPLETED, FAILED
private String result;
// getters and setters
}
When the async method starts, set status to RUNNING. When it finishes, set status to COMPLETED and store the result. If an exception occurs, set status to FAILED and store an error message. The status endpoint reads this table and returns the current state.
Handle Timeouts and Thread Pool Sizing
By default, Spring's @Async uses a simple thread pool. For production, configure a proper executor with a bounded queue and a reasonable number of threads. For example, in application.properties:
spring.task.execution.pool.core-size=5
spring.task.execution.pool.max-size=10
spring.task.execution.pool.queue-capacity=100
If all threads are busy, new jobs wait in the queue. If the queue is full, the caller gets a rejection error. You can handle that by catching TaskRejectedException and returning a 503 Service Unavailable response.
Also consider setting a timeout on the client side. Most HTTP clients have a default read timeout (e.g., 30 seconds). If your job takes longer, the client will disconnect. The async pattern avoids this because the initial request returns quickly.
Where People Go Wrong
Here are common pitfalls and how to avoid them:
- Blocking the request thread: Using
Thread.sleep()or a long loop in a controller method. Always offload to a separate thread. - Using
@Asyncon a private method: Spring proxies only public methods called from another bean. Make the method public and call it from a different service. - Not handling failures: If the async method throws an exception, the job stays in RUNNING forever. Catch exceptions and update the status to FAILED.
- Polling too frequently: Clients that poll every 100ms can overload the server. Suggest a reasonable interval (e.g., 2-5 seconds) or use exponential backoff.
- Losing jobs on restart: If the server restarts, in-memory jobs are lost. Use a database and a startup runner to resume or mark unfinished jobs as FAILED.
When to Use Synchronous Instead
Not every long operation needs async. If the task takes under 2-3 seconds, a synchronous call is simpler and fine. Also, if you need the result to continue processing, you might prefer a synchronous call with a longer timeout. But for anything over 5 seconds, async with polling is safer.
Example Workflow
Here's a step-by-step flow:
- Client sends POST /api/jobs with a JSON body describing the work.
- Controller creates a Job record with status PENDING and saves it.
- Controller calls jobService.processJob(job.getId()) and returns 202 Accepted with the job ID.
- The async method updates status to RUNNING, does the work, then updates to COMPLETED with the result.
- Client polls GET /api/jobs/{id} every 3 seconds. When status is COMPLETED, it calls GET /api/jobs/{id}/result to get the data.
This pattern is used widely in APIs that generate reports, process images, or run complex calculations.
Alternatives to Polling
Polling is simple but can be inefficient. Two alternatives:
- Webhooks: The client provides a callback URL. When the job finishes, the server sends a POST to that URL with the result. This requires the client to be reachable.
- Server-Sent Events (SSE): The client opens a single long-lived connection, and the server pushes updates. This is more efficient than polling but keeps a connection open.
Choose polling for simplicity, webhooks for server-to-server, and SSE for real-time updates in a browser.
Quick Reference Table
| Factor | Recommendation |
|---|---|
| Task duration | < 2s: synchronous; > 5s: async |
| Thread pool size | Start with 5-10 threads, monitor queue |
| Client polling interval | 2-5 seconds, with backoff |
| Job persistence | Database table, not in-memory |
Testing Your Async API
Write integration tests that start a job, poll until completion, and verify the result. Use Awaitility or a simple loop with a timeout. Also test failure scenarios: force an exception and confirm the status becomes FAILED.
Remember: the key is to not hold the HTTP connection open. Return quickly, work in the background, and let the client check back. This keeps your server responsive and your API reliable.