Skip to lesson

Handling slow work asynchronously

The ShopLite admin wants to export six months of orders. The export takes 95 seconds, and the gateway cuts every request at 30 seconds. How can an API handle work that is too slow for one request?

Your turn: design the order export

GET /api/v1/reports/orders-export builds a CSV of six months of orders. It takes 95 seconds, runs on four app servers behind a gateway, and the admin's browser gives up long before it ends.

Before you read on, think about these questions and write your design in a few lines.

  • What should the first request answer within a second, and with which status code?
  • How will the admin's browser find out the file is ready?
  • Four servers share the work: where must the progress of the export be stored?

Slow work that does not fit in one request

An asynchronous API accepts a slow request, answers at once with a job id, and does the work in the background. The client then checks the job's status or is called back when it is done.

Which ShopLite tasks are too slow to answer inside one request? The table checks five tasks against a 2-second user limit and a 30-second gateway limit.

Example 1 · Which tasks are too slow for a normal request

SlowWorkTable.javaJava
import java.util.List;
record Task(String name, double seconds) {}
public class SlowWorkTable {    static final double PROXY_TIMEOUT_S = 30;     // a common gateway/load balancer limit    static final double USER_PATIENCE_S = 2;      // what a user waits for a page
    public static void main(String[] args) {        List<Task> tasks = List.of(                new Task("Show one order", 0.08),                new Task("Export 6 months of orders as CSV", 95),                new Task("Import 20,000 products from Excel", 240),                new Task("Resize 8 product photos", 6),                new Task("Monthly GST report PDF", 40));
        for (Task t : tasks) {            String style;            if (t.seconds() <= USER_PATIENCE_S) {                style = "synchronous";            } else if (t.seconds() < PROXY_TIMEOUT_S) {                style = "async (too slow for a user to wait)";            } else {                style = "async (a proxy would cut the request at 30 s)";            }            System.out.printf("%-35s %6.1f s  %s%n", t.name(), t.seconds(), style);        }    }}
Output
Show one order                         0.1 s  synchronous
Export 6 months of orders as CSV      95.0 s  async (a proxy would cut the request at 30 s)
Import 20,000 products from Excel    240.0 s  async (a proxy would cut the request at 30 s)
Resize 8 product photos                6.0 s  async (too slow for a user to wait)
Monthly GST report PDF                40.0 s  async (a proxy would cut the request at 30 s)

What this code does

  • Anything over about 2 seconds is too slow for a user to wait on; anything over the 30-second proxy limit may fail outright even if the server finishes.
  • Only "show one order" stays synchronous. The export, the import and the GST report would be cut by a proxy, so they must be asynchronous.

Some work takes far longer than a normal request: exporting six months of orders, importing 20,000 products, resizing photos, building a monthly GST report. Users will not stare at a spinner for 90 seconds, and they should not have to.

There is also a hard limit. Load balancers, gateways and proxies often cut requests that run longer than about 30 to 60 seconds, so a long synchronous request can fail even when the server finishes the work. If a mobile user switches apps, the connection may drop too.

202 Accepted, a job id and a status endpoint

202 Accepted is an HTTP status that means the server took the request and will process it later. The answer carries a job id, and a Location header points to the job's status endpoint.

POST starts the work and answers 202 Accepted with a job id, GET /jobs/{id} shows the progress, and a result link appears when the job is done.

Text
POST /api/v1/reports/orders-export          -> 202 Accepted                                               Location: /api/v1/jobs/job-42                                               {"jobId": "job-42", "status": "PENDING"}GET  /api/v1/jobs/job-42                     -> 200 {"status": "RUNNING", "progress": 40}GET  /api/v1/jobs/job-42                     -> 200 {"status": "DONE", "resultUrl": "/api/v1/jobs/job-42/result"}GET  /api/v1/jobs/job-42/result              -> 200 (the CSV file)

Example 2 · 202 Accepted, then polling a status endpoint

JobApiDemo.javaJava
import java.util.HashMap;import java.util.Map;
class Job {    final String id;    String status = "PENDING";    int progress = 0;    String resultUrl = null;
    Job(String id) {        this.id = id;    }}
class ReportApi {    private final Map<String, Job> jobs = new HashMap<>();    private int next = 1;
    // POST /api/v1/reports/orders-export  -> 202 Accepted    String startExport() {        Job job = new Job("job-" + next++);        jobs.put(job.id, job);        return "202 Accepted, Location: /api/v1/jobs/" + job.id + ", body {\"jobId\":\"" + job.id + "\",\"status\":\"PENDING\"}";    }
    // GET /api/v1/jobs/{id}    String status(String id) {        Job j = jobs.get(id);        if (j == null) {            return "404 job not found";        }        String body = "{\"status\":\"" + j.status + "\",\"progress\":" + j.progress                + (j.resultUrl == null ? "" : ",\"resultUrl\":\"" + j.resultUrl + "\"") + "}";        return "200 " + body;    }
    // What the background worker does, one step at a time (called by hand here)    void workStep(String id) {        Job j = jobs.get(id);        j.status = "RUNNING";        j.progress += 50;        if (j.progress == 100) {            j.status = "DONE";            j.resultUrl = "/api/v1/jobs/" + id + "/result";        }    }}
public class JobApiDemo {    public static void main(String[] args) {        ReportApi api = new ReportApi();        System.out.println("POST export   -> " + api.startExport());        System.out.println("GET job-1     -> " + api.status("job-1"));        api.workStep("job-1");        System.out.println("GET job-1     -> " + api.status("job-1"));        api.workStep("job-1");        System.out.println("GET job-1     -> " + api.status("job-1"));        System.out.println("GET job-9     -> " + api.status("job-9"));    }}
Output
POST export   -> 202 Accepted, Location: /api/v1/jobs/job-1, body {"jobId":"job-1","status":"PENDING"}
GET job-1     -> 200 {"status":"PENDING","progress":0}
GET job-1     -> 200 {"status":"RUNNING","progress":50}
GET job-1     -> 200 {"status":"DONE","progress":100,"resultUrl":"/api/v1/jobs/job-1/result"}
GET job-9     -> 404 job not found

What this code does

  • startExport creates a PENDING job and returns 202 with its location. status answers GET /jobs/{id} with state and progress, or 404 for an unknown id.
  • The worker steps are called by hand here so the output is fixed. Once DONE, the status includes resultUrl for the download.

The Location header points to the status endpoint, and the client polls it every few seconds: GET /jobs/{id} returns the state and progress.

When the job is done, the status response includes a link to the result, such as /jobs/{id}/result or a short-lived download URL. The server can suggest how often to poll with a Retry-After header, so clients do not hammer the status endpoint.

Order of execution

Order one export

Put the steps of one asynchronous export in order.

Webhooks: the server calls you back

A webhook is an HTTP request that the server sends to a URL the client registered, when something happens, such as a finished job. It turns polling around: the server calls the client.

Polling wastes calls when a job takes hours. With a webhook the client registers a URL and the server calls it. The example shows a first delivery that fails and a retry.

Example 3 · A webhook with retries when the client endpoint is down

WebhookDemo.javaJava
import java.util.function.Function;
public class WebhookDemo {    // The client's callback endpoint: down for the first attempt, then fine (a fixed pattern)    static int attempts = 0;    static Function<String, Integer> clientEndpoint = payload -> {        attempts++;        return attempts == 1 ? 503 : 200;    };
    static void notifyClient(String callbackUrl, String payload) {        long[] waitsSeconds = {0, 10, 60, 300};   // retry after 10 s, 1 min, 5 min (simulated, no real waiting)        for (int i = 0; i < waitsSeconds.length; i++) {            int status = clientEndpoint.apply(payload);            System.out.println("  POST " + callbackUrl + " (after " + waitsSeconds[i] + " s) -> " + status);            if (status >= 200 && status < 300) {                return;            }        }        System.out.println("  giving up; the client can still poll GET /jobs/{id}");    }
    public static void main(String[] args) {        String payload = "{\"jobId\":\"job-7\",\"status\":\"DONE\",\"resultUrl\":\"/api/v1/jobs/job-7/result\"}";        System.out.println("job-7 finished, calling the client's webhook:");        notifyClient("https://seller.example.com/hooks/shoplite", payload);    }}
Output
job-7 finished, calling the client's webhook:
  POST https://seller.example.com/hooks/shoplite (after 0 s) -> 503
  POST https://seller.example.com/hooks/shoplite (after 10 s) -> 200

What this code does

  • When job-7 finishes, the server POSTs the result to the client's URL. The first attempt gets 503, so it tries again after a delay and succeeds.
  • The delays are simulated. If every attempt failed, the server would give up and the client could still poll, which is why polling stays as a fallback.

Webhooks need their own care. The client's endpoint may be down, so the server retries with backoff and eventually gives up. The client may receive the same callback twice, so its receiver must be idempotent.

The payload should be signed so the client can check it came from you. Many APIs offer both: webhooks for speed, polling as the fallback.

Find the bug

Find the webhook bug

Click the line that makes the webhook receiver unsafe.

The server retries a delivery. Which line can charge a customer twice?

Round 1 of 2

Simulation: ExecutorService runs the job, the client polls

An ExecutorService is a Java pool of worker threads that runs the tasks you submit to it. The request thread hands the job to the pool and returns at once.

The request handler records the job as PENDING, submits the work to an ExecutorService and returns 202 straight away. Then main plays the client and polls.

Example 4 · An ExecutorService job polled by a client

JobPollingDemo.javaJava
import java.util.Map;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;
public class JobPollingDemo {    record Status(String state, int progress) {    }
    static Map<String, Status> jobs = new ConcurrentHashMap<>();
    static void runReport(String jobId) {        try {            for (int step = 1; step <= 4; step++) {                jobs.put(jobId, new Status("RUNNING", (step - 1) * 25));                Thread.sleep(250);                         // read and format one chunk of orders            }            jobs.put(jobId, new Status("DONE", 100));        } catch (InterruptedException e) {            jobs.put(jobId, new Status("FAILED", 0));            Thread.currentThread().interrupt();        }    }
    public static void main(String[] args) throws InterruptedException {        ExecutorService workers = Executors.newFixedThreadPool(2);
        String jobId = "job-42";        jobs.put(jobId, new Status("PENDING", 0));        workers.submit(() -> runReport(jobId));            // the request returns 202 here        System.out.println("POST /reports -> 202 Accepted, jobId=" + jobId);
        for (int poll = 1; ; poll++) {            Thread.sleep(400);                             // the client polls every 400 ms            Status s = jobs.get(jobId);            System.out.println("poll " + poll + ": " + s.state() + " " + s.progress() + "%");            if (s.state().equals("DONE") || s.state().equals("FAILED")) {                break;            }        }        workers.shutdown();        workers.awaitTermination(1, TimeUnit.SECONDS);        System.out.println("download: GET /api/v1/jobs/" + jobId + "/result");    }}
Sample output
POST /reports -> 202 Accepted, jobId=job-42
poll 1: RUNNING 25%
poll 2: RUNNING 75%
poll 3: DONE 100%
download: GET /api/v1/jobs/job-42/result

What this code does

  • The report runs on a pool thread and updates jobs after each chunk; main plays the client and polls every 400 ms until DONE.
  • The exact progress at each poll depends on thread timing, so the output is a sample. shutdown and awaitTermination stop the pool cleanly at the end.

The worker updates the job's status in a shared map as it goes. The client side is a loop: wait, GET the status, stop at DONE or FAILED.

In a real deployment the status map would be a jobs table or Redis, so any app server can answer the status request, and the worker might be a separate process fed by a queue.

Job states and storing results for download

Job states are the stages a background job moves through: PENDING, RUNNING and then DONE or FAILED. Only forward moves are allowed, so a finished job never runs again.

Only some state changes make sense. The example lists the allowed moves, stores a result file with an expiring link and records the error of a failed job.

Example 5 · Allowed state changes, stored results and errors

JobStatesDemo.javaJava
import java.time.LocalDateTime;import java.util.Map;import java.util.Set;
enum JobState { PENDING, RUNNING, DONE, FAILED }
class ExportJob {    static final Map<JobState, Set<JobState>> ALLOWED = Map.of(            JobState.PENDING, Set.of(JobState.RUNNING, JobState.FAILED),            JobState.RUNNING, Set.of(JobState.DONE, JobState.FAILED),            JobState.DONE, Set.of(),            JobState.FAILED, Set.of());
    final String id;    JobState state = JobState.PENDING;    String resultKey;            // where the file is kept in object storage    LocalDateTime expiresAt;     // when the download link stops working    String error;
    ExportJob(String id) {        this.id = id;    }
    void moveTo(JobState next) {        if (!ALLOWED.get(state).contains(next)) {            throw new IllegalStateException(id + ": cannot go from " + state + " to " + next);        }        state = next;    }}
public class JobStatesDemo {    public static void main(String[] args) {        LocalDateTime now = LocalDateTime.of(2026, 10, 16, 21, 0);
        ExportJob ok = new ExportJob("job-1");        ok.moveTo(JobState.RUNNING);        ok.moveTo(JobState.DONE);        ok.resultKey = "exports/2026/10/job-1-orders.csv";        ok.expiresAt = now.plusDays(7);        System.out.println(ok.id + ": " + ok.state + ", file " + ok.resultKey + ", link valid until " + ok.expiresAt);
        ExportJob bad = new ExportJob("job-2");        bad.moveTo(JobState.RUNNING);        bad.moveTo(JobState.FAILED);        bad.error = "row 1,203: date '31-02-2026' is not a real date";        System.out.println(bad.id + ": " + bad.state + ", error: " + bad.error);
        try {            ok.moveTo(JobState.RUNNING);        } catch (IllegalStateException e) {            System.out.println("rejected: " + e.getMessage());        }    }}
Output
job-1: DONE, file exports/2026/10/job-1-orders.csv, link valid until 2026-10-23T21:00
job-2: FAILED, error: row 1,203: date '31-02-2026' is not a real date
rejected: job-1: cannot go from DONE to RUNNING

What this code does

  • ALLOWED lists the legal next states. job-1 finishes and stores a file key with a link that expires after 7 days; job-2 fails with a row-level error message.
  • Trying to move a DONE job back to RUNNING is rejected, so a finished job can never be run twice by mistake.

A job is PENDING (accepted, waiting for a worker), RUNNING (with a progress number), then DONE or FAILED. A failed job stores a clear error message, such as which row of the import was wrong.

The result is usually a file. Store it in object storage, save its key on the job, and give the client a download link that expires (for example after 7 days). A cleanup job deletes old results so storage does not grow forever.

Predict the output

Allowed state changes

Predict whether the move is allowed.

Round 1 of 2

Can a finished job be started again?

Map<String, Set<String>> allowed = Map.of(
"PENDING", Set.of("RUNNING"),
"RUNNING", Set.of("DONE", "FAILED"));
System.out.println(allowed.getOrDefault("DONE", Set.of()).contains("RUNNING"));

Next step

Check your understanding

11 quick questions