Patterncore
Asynchronous Request-Reply
Also called Asynchronous Request-Reply pattern, async request-reply, HTTP polling, 202 Accepted pattern, long-running operation.
For work that takes too long for one HTTP call, the API answers at once with 202 Accepted and the URL of a status endpoint; the client polls that URL until it points to the result.
- Family
- integration
- Intent
- Separate the back end that does long work from the client that asks for it, by an answer of 202 Accepted with a status URL, a status endpoint that the client polls, and a redirect to the result when the work is done.
- Also called
- async request-response
Intent
Let a client start work that takes a long time over HTTP, and get the result later, without an open connection. The Azure page states the aim so: separate the back-end processing from the front-end host when the processing must run asynchronously, but the front end still needs a clear response.1
Problem
Most API calls over HTTP answer in about 100 ms or less, and the answer comes back on the same connection.1 Some work takes a few seconds, and some runs in the background for minutes or longer. The client cannot wait for the end of such work in one call.1
A queue between the API and the worker lets each side scale alone, but then the client must also learn about the result in an asynchronous way.1 Callbacks are one answer. But it is often difficult to give a browser, or a client behind a firewall, a callback endpoint, and a long open connection adds complexity.1
The forces are a quick first answer, a clear state for the client at each time, and a result that the client can get when it is ready.
Solution
The client sends the request. The API checks it, puts the work on a queue and answers at once with 202 Accepted. The answer has a Location header with the URL of a status endpoint. The client polls that URL. While the work runs, the status endpoint answers 200 with the state of the work. When the work is done, it answers 303 See Other with the URL of the result, and the client gets the result there.1
client API / status endpoint worker
| POST /reports -------------> | |
| <---- 202, Location: /status/r1, Retry-After: 2 |
| | --- message on a queue ------> |
| GET /status/r1 ------------> | |
| <---- 200, status=Running | |
| ... | <--- result in a store ------- |
| GET /status/r1 ------------> | |
| <---- 303, Location: /reports/r1 |
| GET /reports/r1 -----------> | |
| <---- 200, the result | |
The participants are the client, the API that accepts the work, the queue, the worker, the store for the result, and the status endpoint.1
The status codes. RFC 9110 says that 202 means that the request "has been accepted for processing, but the processing has not been completed".2 HTTP has no way to send a status code later from an asynchronous operation. Thus the 202 answer ought to describe the current status and point to a status monitor.2 A 303 sends the client to another resource, which a client gets with GET or HEAD.2 The Azure page prefers 303 to 302. With a 302, the change of the method is not guaranteed, and some clients send the original method again, which can give a second POST.1 RFC 9110 says that a user agent may change a POST to a GET after a 302 for historical reasons.2
How often to poll. The 202 answer can have a Retry-After header with an estimate of the time to wait.1 RFC 9110 gives the header a meaning for a 503 and for a redirect; its value is a date or a number of seconds.2 The program below compares three ways to poll for jobs of 3, 12 and 40 seconds. The client does not know the time of the job.
# A job ends after D seconds; the client does not know D. Each strategy
# polls the status endpoint and stops at the first poll after the end.
def fixed(step):
def gen():
t = 0
while True:
t += step
yield t
return gen
def backoff(first, cap):
def gen():
t, step = 0, first
while True:
t += step
yield t
step = min(step * 2, cap)
return gen
strategies = [("every 1 s", fixed(1)), ("Retry-After: 5", fixed(5)),
("backoff 1, 2, 4 ... 16 s", backoff(1, 16))]
print("%-25s %-16s %-16s %s" % ("", "job of 3 s", "job of 12 s", "job of 40 s"))
for name, gen in strategies:
cells = []
for d in (3, 12, 40):
polls = 0
for t in gen():
polls += 1
if t >= d:
break
cells.append("%2d polls, +%2d s" % (polls, t - d))
print("%-25s %s" % (name, " ".join(cells)))
job of 3 s job of 12 s job of 40 s
every 1 s 3 polls, + 0 s 12 polls, + 0 s 40 polls, + 0 s
Retry-After: 5 1 polls, + 2 s 3 polls, + 3 s 8 polls, + 0 s
backoff 1, 2, 4 ... 16 s 2 polls, + 0 s 4 polls, + 3 s 6 polls, + 7 s
A poll each second sees the end quickly, but it sends one request for each second of the job. A fixed wait of 5 seconds sends few requests, but it can see the end up to 5 seconds late. A wait that doubles up to 16 seconds sends the fewest requests for long jobs, but the client can see the end of a long job much later. Retry-After lets the server, which can estimate the time of the job, set the interval.
Example
Each example file runs an API in the same process, with no network. The client sends a POST with an idempotency key and gets 202 with a status URL. It sends the POST again with the same key, as after a lost answer, and gets the same status URL, and no second job starts. The Azure page suggests this key, because the client cannot tell a lost answer from a lost request.1 A request with no month gets 400 at once, because the API checks the request before it starts the work.1 The client then polls at the interval of Retry-After and follows the 303. An unknown request id gets 404.
JOB_TIME = 5 # seconds that the worker needs for one report
class Api:
def __init__(self):
self.jobs = {} # request id -> time the job started
self.keys = {} # idempotency key -> request id
self.queued = 0
def post(self, key, month, now):
if not month:
return 400, {}, "month is missing"
if key in self.keys: # a retry: give back the first status URL
rid = self.keys[key]
else:
rid = "r%d" % (len(self.jobs) + 1)
self.keys[key], self.jobs[rid] = rid, now
self.queued += 1
return 202, {"Location": "/status/" + rid, "Retry-After": "2"}, ""
def get(self, path, now):
kind, rid = path.strip("/").split("/")
if rid not in self.jobs:
return 404, {}, ""
elapsed = now - self.jobs[rid]
if kind == "status":
if elapsed < JOB_TIME:
return 200, {}, "status=Running percentComplete=%d" % (elapsed * 100 // JOB_TIME)
return 303, {"Location": "/reports/" + rid}, ""
if elapsed < JOB_TIME:
return 404, {}, ""
return 200, {}, "report %s: 3 rows" % rid
def show(t, req, resp):
code, headers, body = resp
parts = [str(code)] + ["%s: %s" % kv for kv in headers.items()] + ([body] if body else [])
print("t=%d %s -> %s" % (t, req, " ".join(parts)))
return resp
api = Api()
code, h, _ = show(0, "POST /reports key=k1", api.post("k1", "2026-10", 0))
show(0, "POST /reports key=k1 (retry)", api.post("k1", "2026-10", 0))
show(0, "POST /reports key=k2, no month", api.post("k2", "", 0))
t, url = 0, h["Location"]
while True:
t += int(h.get("Retry-After", "2"))
code, h2, _ = show(t, "GET " + url, api.get(url, t))
if code == 303:
show(t, "GET " + h2["Location"], api.get(h2["Location"], t))
break
show(t, "GET /status/r9", api.get("/status/r9", t))
print("jobs queued: %d" % api.queued)
t=0 POST /reports key=k1 -> 202 Location: /status/r1 Retry-After: 2
t=0 POST /reports key=k1 (retry) -> 202 Location: /status/r1 Retry-After: 2
t=0 POST /reports key=k2, no month -> 400 month is missing
t=2 GET /status/r1 -> 200 status=Running percentComplete=40
t=4 GET /status/r1 -> 200 status=Running percentComplete=80
t=6 GET /status/r1 -> 303 Location: /reports/r1
t=6 GET /reports/r1 -> 200 report r1: 3 rows
t=6 GET /status/r9 -> 404
jobs queued: 1
- Verdict: idiom. Each handler returns a tuple of the status code, a dict of headers and a body, so the client code reads like a client of a real HTTP API.
- The dict
keysmaps an idempotency key to a request id, so a second POST with the same key gives back the first status URL. - The time is a parameter, not the clock, so the output is the same at each run; a real server keeps the start time of each job in a store.
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
static final int JOB_TIME = 5; // seconds that the worker needs for one report
record Response(int code, Map<String, String> headers, String body) {
static Response of(int code, String body, String... headers) {
Map<String, String> h = new LinkedHashMap<>();
for (int i = 0; i < headers.length; i += 2) {
h.put(headers[i], headers[i + 1]);
}
return new Response(code, h, body);
}
}
static class Api {
final Map<String, Integer> jobs = new HashMap<>(); // request id -> time the job started
final Map<String, String> keys = new HashMap<>(); // idempotency key -> request id
int queued = 0;
Response post(String key, String month, int now) {
if (month.isEmpty()) {
return Response.of(400, "month is missing");
}
String rid = keys.get(key);
if (rid == null) {
rid = "r" + (jobs.size() + 1);
keys.put(key, rid);
jobs.put(rid, now);
queued++;
}
return Response.of(202, "", "Location", "/status/" + rid, "Retry-After", "2");
}
Response get(String path, int now) {
String[] parts = path.substring(1).split("/");
Integer started = jobs.get(parts[1]);
if (started == null) {
return Response.of(404, "");
}
int elapsed = now - started;
if (parts[0].equals("status")) {
if (elapsed < JOB_TIME) {
return Response.of(200, "status=Running percentComplete=" + elapsed * 100 / JOB_TIME);
}
return Response.of(303, "", "Location", "/reports/" + parts[1]);
}
if (elapsed < JOB_TIME) {
return Response.of(404, "");
}
return Response.of(200, "report " + parts[1] + ": 3 rows");
}
}
static Response show(int t, String req, Response r) {
StringBuilder sb = new StringBuilder(String.valueOf(r.code()));
r.headers().forEach((k, v) -> sb.append(' ').append(k).append(": ").append(v));
if (!r.body().isEmpty()) {
sb.append(' ').append(r.body());
}
System.out.println("t=" + t + " " + req + " -> " + sb);
return r;
}
public static void main(String[] args) {
Api api = new Api();
Response first = show(0, "POST /reports key=k1", api.post("k1", "2026-10", 0));
show(0, "POST /reports key=k1 (retry)", api.post("k1", "2026-10", 0));
show(0, "POST /reports key=k2, no month", api.post("k2", "", 0));
int wait = Integer.parseInt(first.headers().get("Retry-After"));
String url = first.headers().get("Location");
int t = 0;
while (true) {
t += wait;
Response r = show(t, "GET " + url, api.get(url, t));
if (r.code() == 303) {
String loc = r.headers().get("Location");
show(t, "GET " + loc, api.get(loc, t));
break;
}
}
show(t, "GET /status/r9", api.get("/status/r9", t));
System.out.println("jobs queued: " + api.queued);
}
}
t=0 POST /reports key=k1 -> 202 Location: /status/r1 Retry-After: 2
t=0 POST /reports key=k1 (retry) -> 202 Location: /status/r1 Retry-After: 2
t=0 POST /reports key=k2, no month -> 400 month is missing
t=2 GET /status/r1 -> 200 status=Running percentComplete=40
t=4 GET /status/r1 -> 200 status=Running percentComplete=80
t=6 GET /status/r1 -> 303 Location: /reports/r1
t=6 GET /reports/r1 -> 200 report r1: 3 rows
t=6 GET /status/r9 -> 404
jobs queued: 1
- Verdict: idiom. A record
Responseholds the status code, the headers in aLinkedHashMap, which keeps their order, and a body. - The map
keysmaps an idempotency key to a request id, so a second POST with the same key starts no second job. - The time is a parameter, not the clock, so the output is the same at each run; a real server keeps the start time of each job in a store.
var api = new Api();
var first = Show(0, "POST /reports key=k1", api.Post("k1", "2026-10", 0));
Show(0, "POST /reports key=k1 (retry)", api.Post("k1", "2026-10", 0));
Show(0, "POST /reports key=k2, no month", api.Post("k2", "", 0));
int wait = int.Parse(first.Headers["Retry-After"]);
string url = first.Headers["Location"];
int t = 0;
while (true)
{
t += wait;
var r = Show(t, "GET " + url, api.Get(url, t));
if (r.Code == 303)
{
string loc = r.Headers["Location"];
Show(t, "GET " + loc, api.Get(loc, t));
break;
}
}
Show(t, "GET /status/r9", api.Get("/status/r9", t));
Console.WriteLine($"jobs queued: {api.Queued}");
static Response Show(int t, string req, Response r)
{
var parts = new List<string> { r.Code.ToString() };
parts.AddRange(r.Pairs.Select(h => $"{h.Key}: {h.Value}"));
if (r.Body != "")
{
parts.Add(r.Body);
}
Console.WriteLine($"t={t} {req} -> {string.Join(" ", parts)}");
return r;
}
record Response(int Code, string Body, List<KeyValuePair<string, string>> Pairs)
{
// A list keeps the order of the headers; the dictionary is for the lookups.
public Dictionary<string, string> Headers => Pairs.ToDictionary(p => p.Key, p => p.Value);
public static Response Of(int code, string body, params string[] h) =>
new(code, body, Enumerable.Range(0, h.Length / 2).Select(i => KeyValuePair.Create(h[2 * i], h[2 * i + 1])).ToList());
}
class Api
{
const int JobTime = 5; // seconds that the worker needs for one report
readonly Dictionary<string, int> jobs = new(); // request id -> time the job started
readonly Dictionary<string, string> keys = new(); // idempotency key -> request id
public int Queued { get; private set; }
public Response Post(string key, string month, int now)
{
if (month == "")
{
return Response.Of(400, "month is missing");
}
if (!keys.TryGetValue(key, out var rid))
{
rid = $"r{jobs.Count + 1}";
keys[key] = rid;
jobs[rid] = now;
Queued++;
}
return Response.Of(202, "", "Location", "/status/" + rid, "Retry-After", "2");
}
public Response Get(string path, int now)
{
var parts = path.Trim('/').Split('/');
if (!jobs.TryGetValue(parts[1], out var started))
{
return Response.Of(404, "");
}
int elapsed = now - started;
if (parts[0] == "status")
{
if (elapsed < JobTime)
{
return Response.Of(200, $"status=Running percentComplete={elapsed * 100 / JobTime}");
}
return Response.Of(303, "", "Location", "/reports/" + parts[1]);
}
if (elapsed < JobTime)
{
return Response.Of(404, "");
}
return Response.Of(200, $"report {parts[1]}: 3 rows");
}
}
t=0 POST /reports key=k1 -> 202 Location: /status/r1 Retry-After: 2
t=0 POST /reports key=k1 (retry) -> 202 Location: /status/r1 Retry-After: 2
t=0 POST /reports key=k2, no month -> 400 month is missing
t=2 GET /status/r1 -> 200 status=Running percentComplete=40
t=4 GET /status/r1 -> 200 status=Running percentComplete=80
t=6 GET /status/r1 -> 303 Location: /reports/r1
t=6 GET /reports/r1 -> 200 report r1: 3 rows
t=6 GET /status/r9 -> 404
jobs queued: 1
- Verdict: idiom. A record
Responsekeeps the headers as a list ofKeyValuePairvalues, so they print in a fixed order. TryGetValueon the dictionarykeysfinds the request id of an idempotency key, so a second POST with the same key starts no second job.- An ASP.NET Core API would return
Accepted(url)for the 202; the handlers here are plain methods, so the program needs no network.
package main
import (
"fmt"
"strings"
)
// jobTime is the number of seconds that the worker needs for one report.
const jobTime = 5
type header struct{ name, value string }
type response struct {
code int
headers []header
body string
}
// jobs maps a request id to the time its job started, and keys maps an
// idempotency key to a request id.
type api struct {
jobs map[string]int
keys map[string]string
queued int
}
func (a *api) post(key, month string, now int) response {
if month == "" {
return response{code: 400, body: "month is missing"}
}
rid, ok := a.keys[key]
if !ok {
rid = fmt.Sprintf("r%d", len(a.jobs)+1)
a.keys[key] = rid
a.jobs[rid] = now
a.queued++
}
return response{code: 202, headers: []header{{"Location", "/status/" + rid}, {"Retry-After", "2"}}}
}
func (a *api) get(path string, now int) response {
parts := strings.Split(strings.Trim(path, "/"), "/")
kind, rid := parts[0], parts[1]
started, ok := a.jobs[rid]
if !ok {
return response{code: 404}
}
elapsed := now - started
if kind == "status" {
if elapsed < jobTime {
return response{code: 200, body: fmt.Sprintf("status=Running percentComplete=%d", elapsed*100/jobTime)}
}
return response{code: 303, headers: []header{{"Location", "/reports/" + rid}}}
}
if elapsed < jobTime {
return response{code: 404}
}
return response{code: 200, body: fmt.Sprintf("report %s: 3 rows", rid)}
}
func show(t int, req string, r response) response {
parts := []string{fmt.Sprint(r.code)}
for _, h := range r.headers {
parts = append(parts, h.name+": "+h.value)
}
if r.body != "" {
parts = append(parts, r.body)
}
fmt.Printf("t=%d %s -> %s\n", t, req, strings.Join(parts, " "))
return r
}
func headerOf(r response, name string) string {
for _, h := range r.headers {
if h.name == name {
return h.value
}
}
return ""
}
func main() {
a := &api{jobs: map[string]int{}, keys: map[string]string{}}
first := show(0, "POST /reports key=k1", a.post("k1", "2026-10", 0))
show(0, "POST /reports key=k1 (retry)", a.post("k1", "2026-10", 0))
show(0, "POST /reports key=k2, no month", a.post("k2", "", 0))
var wait int
fmt.Sscan(headerOf(first, "Retry-After"), &wait)
t, url := 0, headerOf(first, "Location")
for {
t += wait
r := show(t, "GET "+url, a.get(url, t))
if r.code == 303 {
loc := headerOf(r, "Location")
show(t, "GET "+loc, a.get(loc, t))
break
}
}
show(t, "GET /status/r9", a.get("/status/r9", t))
fmt.Printf("jobs queued: %d\n", a.queued)
}
t=0 POST /reports key=k1 -> 202 Location: /status/r1 Retry-After: 2
t=0 POST /reports key=k1 (retry) -> 202 Location: /status/r1 Retry-After: 2
t=0 POST /reports key=k2, no month -> 400 month is missing
t=2 GET /status/r1 -> 200 status=Running percentComplete=40
t=4 GET /status/r1 -> 200 status=Running percentComplete=80
t=6 GET /status/r1 -> 303 Location: /reports/r1
t=6 GET /reports/r1 -> 200 report r1: 3 rows
t=6 GET /status/r9 -> 404
jobs queued: 1
- Verdict: idiom. A struct
responseholds the status code, a slice of headers and a body; a slice keeps the order of the headers, which a map does not. - The map
keysmaps an idempotency key to a request id, so a second POST with the same key starts no second job. - A real server would use
net/http, withw.Header().Setfor theLocationheader andw.WriteHeader(http.StatusAccepted); the handlers here are plain methods, so the program needs no network.
Consequences
Benefits.
- A quick answer. The client gets an answer in a short time, also for long work.1
- Independent scale. The API and the worker scale separately, and the server can schedule the work when it has capacity.1
- Only HTTP on the client. The client needs no callback endpoint and no open connection.1
Liabilities.
- More requests. Each poll is a request to the server.
Retry-Afterhelps a client not to poll too often, but a client written by others can ignore it.1 - State on the server. The status resource and the result use storage. The Azure page asks for a retention policy, and an
Expiresheader can tell the client how long the result stays.1 - Errors later. An error in the work must be kept at the URL of the
Locationheader, with a 4xx status code that matches the failure. The Azure page suggests RFC 9457 problem details for this.1 - No single standard. Implementations differ. Some have no status endpoint, and the client polls the result URL and gets 404 until the result exists, which is unclear, because an invalid id also gives 404.1
When not to use it
The Azure page names these cases.1
- A service for asynchronous notifications, such as Azure Event Grid, is available.
- The answers must stream to the client in real time. Server-Sent Events give a push channel from the server.
- The client must collect many results, and their latency is important. A message broker is better.
- The server can keep a connection open, as with WebSockets or SignalR, and notify the caller.
- The network allows a callback or a webhook to the client.
Variants and related patterns
Long polling. The client sends a request, and the server keeps the connection open until new data is available or a timeout occurs. This gives a shorter delay than periodic polling, but the server must manage the open connections and timeouts.1 The Azure sample has such a mode: the status endpoint waits with a delay that doubles each time, for up to about one minute.1
Cancel. A DELETE on the status resource can cancel the work. The back end then sets the state to canceled.1
A facade for old clients. A client that cannot handle 202 can call a facade that hides the asynchronous work. The Azure page names Logic Apps as such a layer.1
Over messaging. With queues in place of HTTP, the same idea is a Request-Reply with a reply channel and a Correlation Identifier. The request id in the status URL has the role of the correlation identifier.
Known uses
- Azure: the sample of the Azure page uses Azure Functions for the API, the status endpoint and the worker, a Service Bus queue between them, and Blob Storage for the result. When the result exists, the status endpoint answers 303 with a URL that has a shared access signature.1
- Azure Resource Manager uses a variant of the pattern for its asynchronous operations, and Logic Apps supports the pattern natively.1
References
- Microsoft, Azure Architecture Center, Asynchronous Request-Reply pattern, context and problem; solution; problems and considerations; when to use this pattern; example
- R. Fielding, M. Nottingham and J. Reschke (eds.), RFC 9110, HTTP Semantics, 2022, 15.3.3 202 Accepted; 15.4.3 302 Found; 15.4.4 303 See Other; 10.2.3 Retry-After
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag S5M7JH Edit this page History Report an error Markdown