Synchronous calls vs background jobs and queues
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's checkout takes about 3 seconds because it builds the invoice PDF and sends an email before it answers. When the email provider is down, a customer who has already paid sees an error. What must the customer really wait for?
Your turn: what must the customer wait for?
ShopLite checkout runs five steps in a row: save order (30 ms), charge payment (800 ms), update stock (20 ms), build invoice PDF (900 ms), send email (1200 ms). Think before you read on:
- How long does the customer wait in total?
- Which steps must finish before the answer, and which only need to happen soon?
- The email provider is down. What should the customer see, and what should happen to the email?
The synchronous request: the user waits for everything
A synchronous request does every step before it answers, so the user waits for the sum of all steps and any failing step fails the whole request.
Here checkout runs five steps in a row before it answers. Run the example: the second order fails because the email provider is down, after the customer was already charged.
Example 1 · A synchronous checkout: slow, and fragile
import java.util.LinkedHashMap;import java.util.Map;
public class SyncCheckoutDemo { // Simulated costs in ms (no real waiting, so the output is the same every run) static Map<String, Integer> steps = new LinkedHashMap<>();
static String checkout(int orderId, boolean emailProviderUp) { int clock = 0; for (Map.Entry<String, Integer> step : steps.entrySet()) { if (step.getKey().equals("send confirmation email") && !emailProviderUp) { return "order " + orderId + ": 500 error after " + clock + " ms (email provider down, payment already taken)"; } clock += step.getValue(); } return "order " + orderId + ": 201 Created after " + clock + " ms"; }
public static void main(String[] args) { steps.put("save order", 30); steps.put("charge payment", 800); steps.put("update stock", 20); steps.put("build invoice PDF", 900); steps.put("send confirmation email", 1200);
System.out.println(checkout(501, true)); System.out.println(checkout(502, false)); }}order 501: 201 Created after 2950 ms order 502: 500 error after 1750 ms (email provider down, payment already taken)
What this code does
- The clock adds simulated costs, so the output is the same every run. The customer waits 2,950 ms because PDF and email are inside the request.
- When the email provider is down, order 502 fails after the payment step: the customer is charged and sees an error. Neither problem is about load.
Every step can fail the whole request. If the email provider is down, the checkout returns an error even though the payment was already taken.
Some steps truly must finish before the answer (saving the order, taking the payment); others only need to happen soon.
Predict the output
Predict the failing checkout
The steps run in order, and the email provider is down.
What does the customer get for order 502?
The queue: producer, queue, consumer
Producer / consumer is the pattern in which a producer puts messages on a queue and moves on, and a consumer takes them off one by one and does the work.
A queue holds messages in order until someone takes them. Checkout (the producer) puts "email order 501" on the queue; a worker (the consumer) takes it.
[Checkout] ..put..> [[Queue: email-501, email-502, ...]] --take--> [Worker] --> [Email provider] producer holds jobs in order consumerExample 2 · Producer and consumer with a bounded queue
import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;
public class QueueBasicsDemo { public static void main(String[] args) throws InterruptedException { BlockingQueue<String> queue = new ArrayBlockingQueue<>(3); // holds at most 3 jobs
// Producer side: checkout adds jobs and moves on System.out.println("offer email-501: " + queue.offer("email-501")); System.out.println("offer email-502: " + queue.offer("email-502")); System.out.println("offer email-503: " + queue.offer("email-503")); System.out.println("offer email-504: " + queue.offer("email-504") + " (queue full)");
// Consumer side: a worker takes jobs in the order they arrived while (!queue.isEmpty()) { System.out.println("worker took " + queue.take()); } }}offer email-501: true offer email-502: true offer email-503: true offer email-504: false (queue full) worker took email-501 worker took email-502 worker took email-503
What this code does
ArrayBlockingQueue<>(3)holds at most three jobs.offerreturnsfalsefor the fourth, which is how a full queue pushes back on producers.- The worker takes jobs in arrival order (first in, first out) with
take.
A queue also has limits: when it is full, producers must wait or be told no, which protects the workers from overload. The example uses a queue that holds at most three jobs.
In the picture, checkout answers after 850 ms. The PDF and the email wait in the queue for the worker.
Order of execution
Life of an email job
Tap the steps in the order they happen.
Simulation: checkout returns fast, a worker sends emails
A poison pill is a special message that tells a worker to stop. When the worker takes it from the queue, it leaves its loop and the thread can finish.
Java's BlockingQueue is a thread-safe queue: put adds a job and take waits for one. The main thread plays checkout; one worker thread sends emails.
Example 3 · BlockingQueue: checkout answers at once, a worker sends emails
import java.util.concurrent.BlockingQueue;import java.util.concurrent.LinkedBlockingQueue;
record EmailJob(int orderId, String to) {}
public class AsyncCheckoutDemo { static final EmailJob STOP = new EmailJob(-1, ""); // a "poison pill" that tells the worker to stop
public static void main(String[] args) throws InterruptedException { BlockingQueue<EmailJob> queue = new LinkedBlockingQueue<>();
Thread worker = new Thread(() -> { try { while (true) { EmailJob job = queue.take(); // waits until a job arrives if (job == STOP) { break; } Thread.sleep(300); System.out.println(" worker: confirmation email for order " + job.orderId() + " sent to " + job.to()); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); worker.start();
String[][] orders = {{"501", "meena@example.com"}, {"502", "ravi@example.com"}, {"503", "asha@example.com"}}; for (String[] o : orders) { int id = Integer.parseInt(o[0]); // save order, charge payment, update stock ... then just add a job: queue.put(new EmailJob(id, o[1])); System.out.println("checkout " + id + ": 201 Created (email queued)"); }
queue.put(STOP); worker.join(); System.out.println("all emails sent; customers never waited for them"); }}checkout 501: 201 Created (email queued) checkout 502: 201 Created (email queued) checkout 503: 201 Created (email queued) worker: confirmation email for order 501 sent to meena@example.com worker: confirmation email for order 502 sent to ravi@example.com worker: confirmation email for order 503 sent to asha@example.com all emails sent; customers never waited for them
What this code does
- All three checkouts answer immediately; the worker sends each email 300 ms later. The order of lines comes from thread timing, so it is shown as sample output, though it is almost always this.
STOPis the poison pill that ends the worker's loop, andworker.join()waits for it before the last line prints.
To stop the worker cleanly, the producer puts the poison pill at the end. The main thread then calls join on the worker, which waits until the worker has finished.
The output shows the point of the queue: all three checkouts answer first, and the slow emails follow.
Failures: retries and dead letters
A dead-letter queue (DLQ) is a separate queue where a message goes after its last failed retry, so a person or an alert can look at it and one bad message never blocks the rest.
Background work fails too, but nobody is waiting, so it can try again. The example retries up to three times and then moves a hopeless message to a dead-letter queue.
Example 4 · Retries, a dead-letter queue and a duplicate message
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Map;import java.util.Queue;import java.util.Set;
record Message(String id, int orderId, int attempt) {}
public class RetryDlqDemo { static final int MAX_ATTEMPTS = 3; // How many times the SMS gateway fails for each order before it works (a fixed pattern) static final Map<Integer, Integer> failuresBeforeSuccess = Map.of(501, 0, 502, 1, 503, 5);
static Set<String> processedIds = new HashSet<>(); // for the idempotent consumer static List<Message> deadLetters = new ArrayList<>();
static boolean sendSms(Message m) { return m.attempt() > failuresBeforeSuccess.get(m.orderId()); }
public static void main(String[] args) { Queue<Message> queue = new ArrayDeque<>(); queue.add(new Message("m1", 501, 1)); queue.add(new Message("m2", 502, 1)); queue.add(new Message("m3", 503, 1)); queue.add(new Message("m1", 501, 1)); // the broker delivered m1 twice
while (!queue.isEmpty()) { Message m = queue.poll(); if (processedIds.contains(m.id())) { System.out.println(m.id() + ": duplicate, already done, skipped"); continue; } if (sendSms(m)) { processedIds.add(m.id()); System.out.println(m.id() + ": SMS for order " + m.orderId() + " sent on attempt " + m.attempt()); } else if (m.attempt() < MAX_ATTEMPTS) { System.out.println(m.id() + ": attempt " + m.attempt() + " failed, will retry"); queue.add(new Message(m.id(), m.orderId(), m.attempt() + 1)); } else { System.out.println(m.id() + ": failed " + MAX_ATTEMPTS + " times, moved to dead-letter queue"); deadLetters.add(m); } } System.out.println("Dead-letter queue: " + deadLetters.size() + " message(s) for a person to check"); }}m1: SMS for order 501 sent on attempt 1 m2: attempt 1 failed, will retry m3: attempt 1 failed, will retry m1: duplicate, already done, skipped m2: SMS for order 502 sent on attempt 2 m3: attempt 2 failed, will retry m3: failed 3 times, moved to dead-letter queue Dead-letter queue: 1 message(s) for a person to check
What this code does
- m2 fails once and succeeds on retry. m3 keeps failing, so after 3 attempts it goes to the dead-letter list instead of looping forever.
- m1 is delivered twice. The
processedIdsset makes the consumer idempotent, so the customer gets one SMS, not two.
A failed message is retried, usually a few times with a delay. After the last attempt it goes to the dead-letter queue. The same run also skips a duplicate: the next section explains why duplicates happen.
Duplicates: at-least-once delivery
An idempotent consumer handles the same message twice with the same effect as handling it once, usually by remembering the ids of messages it has already processed.
Most real brokers promise at-least-once delivery: every message arrives, but after a crash or a lost acknowledgement the same message can arrive twice. The consumer has to cope.
The usual way is to give each message an id and skip ids that were already processed, as the example did with m1.
Find the bug
Find the unsafe worker
Each snippet is a background worker. Tap the line that can hurt ShopLite.
A worker reduces stock. The broker may deliver a message twice.
Round 1 of 3Real queues: names and roles
A message broker is a separate server that stores queue messages safely, survives restarts and serves many producers and consumers.
In production the BlockingQueue becomes a message broker. You will meet these names; their details are beyond this module.
Next step
Check your understanding
11 quick questions