HTTP 202 Accepted: Poll Until the Operation Finishes
Handle HTTP 202 without confusing acceptance with completion. Design status polling, deadlines and failure handling with a runnable Python HTTP fixture.
HTTP 202 acknowledges acceptance, not completed work. Follow the API’s status-monitor contract, interpret its terminal success or failure state, and retain the operation identity if your polling deadline expires. Stopping the client’s wait does not cancel the operation.
Accepted is the beginning of an operation
Your export endpoint returns HTTP 202, so the interface displays “Download ready.” A minute later, the worker fails and no file exists. The transport exchange succeeded, but the product treated admission into a workflow as completion of that workflow.
HTTP 202 means the request was accepted for processing and processing is not complete. It does not guarantee that the work will eventually succeed or even be acted upon. The original HTTP response cannot later turn into a different status code; the client needs another way to discover what happened. A status resource is one common design.
Separate the submission response from the operation’s eventual state. If you create a durable job resource synchronously, a 201 response can describe that creation even while background work remains. Choose the contract intentionally: neither a job’s existence nor a successful GET of its status proves that the business operation succeeded.
Source: RFC 9110: HTTP 202 Accepted and Retry-After semantics ↗
Publish a monitor contract the client can follow
A useful submission response identifies the operation and gives the client a supported way to monitor it. In this illustrative contract, Location identifies a status resource and Retry-After supplies a polling delay. These fields are a design choice for this API, not a universal requirement that every 202 response uses the same headers.
The status resource returns 200 when the status representation was retrieved successfully. Its body carries queued, running, succeeded or failed. Another API may return 202 while work is pending or use 303 to direct the client to a result after completion. The client must implement the documented combination of HTTP behavior and operation states rather than assuming every 2xx means the result is ready.
Define where successful output lives, how failures are represented, and how long the monitor survives. If the monitor expires after a day, document the response for an expired operation. A 404 on a monitor can mean a wrong URL, missing authorization context, replication delay or retention expiry according to the API; it does not inherently mean the worker failed.
HTTP/1.1 202 Accepted
Location: /operations/export-42
Retry-After: 2
Content-Type: application/json
Cache-Control: no-store
{"status":"queued"}
GET /operations/export-42
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
{"status":"running"}Source: Microsoft Azure Architecture Center: asynchronous request-reply pattern ↗
Poll with a deadline and retain the operation identity
Persist the monitor URL or operation ID as soon as submission is acknowledged. Poll that resource; do not keep submitting the original POST while waiting. A lost submission response is a different recovery problem because the server may already have accepted the work. Use the API’s supported idempotency or lookup mechanism to reconcile it.
Honor the documented polling interval. Retry-After can be a non-negative integer number of seconds or an HTTP date. For production use, parse the supported forms and define a fallback for a missing or malformed value. If a requested wait exceeds your remaining budget, stop polling and retain the operation identity rather than polling earlier. A client deadline expiring means the client stopped waiting; it does not cancel the server-side operation.
Give each request a timeout and the polling loop a separate total budget. Use a monotonic clock for elapsed time. Authentication failures, rate limits, transport failures and a worker’s failed state need distinct handling. A transient monitor GET failure can be retried under a bounded policy without creating another operation. Do not silently turn an unknown state value into success or an unlimited wait.
Source: RFC 9110: HTTP 202 Accepted and Retry-After semantics ↗
Run a local success, failure and deadline fixture
The following Python standard-library script starts a loopback HTTP server on a temporary port, submits three operations and exercises the monitoring client. Save it as async_demo.py and run python3 async_demo.py. It needs no external service or credentials.
This is a deterministic protocol fixture: GET requests advance the simulated state. It does not start a real background export or demonstrate a durable queue. The two completed cases deliberately use the same 202 submission response and the same 200 monitor response code, but one ends in succeeded and the other in failed. The third stops waiting and retains its monitor URL.
Retry-After is zero only to keep this fixture immediate. The sample parses integer delays and trusts the local server. It is not a general client for arbitrary remote endpoints: production code must implement its API’s authentication, permitted monitor origins and redirects, HTTP error handling, date-form Retry-After and response validation. Its polling budget starts after submission; the submission request has its own timeout.
import json
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
from urllib.request import Request, urlopen
from urllib.parse import urljoin
from contextlib import contextmanager
class Handler(BaseHTTPRequestHandler):
jobs = {}
def log_message(self, *args):
pass
def reply(self, status, body, **headers):
raw = json.dumps(body).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(raw)))
self.send_header("Cache-Control", "no-store")
for name, value in headers.items():
self.send_header(name.replace("_", "-"), value)
self.end_headers()
self.wfile.write(raw)
def do_POST(self):
if self.path != "/jobs":
return self.reply(404, {"error": "not found"})
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
path = "/jobs/" + str(len(self.jobs) + 1)
self.jobs[path] = {"polls": 0, "fail": body.get("fail", False)}
self.reply(202, {"status": "queued"}, Location=path, Retry_After="0")
def do_GET(self):
job = self.jobs.get(self.path)
if job is None:
return self.reply(404, {"error": "unknown operation"})
job["polls"] += 1
state = ("queued" if job["polls"] == 1 else
"running" if job["polls"] == 2 else
"failed" if job["fail"] else "succeeded")
body = {"status": state}
if state == "succeeded":
body["result"] = {"rows": 3}
elif state == "failed":
body["error"] = {"code": "EXPORT_FAILED"}
self.reply(200, body, Retry_After="0")
class PollDeadline(TimeoutError):
def __init__(self, monitor_url):
super().__init__("Polling deadline reached; operation outcome is unknown")
self.monitor_url = monitor_url
def exchange(url, *, payload=None, timeout=2):
data = None if payload is None else json.dumps(payload).encode()
request = Request(url, data=data, headers={"Content-Type": "application/json"})
with urlopen(request, timeout=timeout) as response:
return response.status, response.headers, json.load(response)
def wait_for_job(base, *, fail=False, budget=5):
# Loopback fixture only. Production clients need their API's auth,
# URL trust rules, HTTP error policy and Retry-After date handling.
status, headers, body = exchange(base + "/jobs", payload={"fail": fail})
assert status == 202 and body["status"] == "queued"
monitor = urljoin(base + "/jobs", headers["Location"])
delay = int(headers.get("Retry-After", "1"))
deadline = time.monotonic() + budget
states = []
while True:
remaining = deadline - time.monotonic()
if remaining <= 0 or delay >= remaining:
raise PollDeadline(monitor)
time.sleep(delay)
remaining = deadline - time.monotonic()
if remaining <= 0:
raise PollDeadline(monitor)
status, headers, body = exchange(monitor, timeout=min(2, remaining))
assert status == 200
state = body.get("status")
states.append(state)
if state in {"succeeded", "failed"}:
return state, body, states
if state not in {"queued", "running"}:
raise ValueError("Unknown operation state")
delay = int(headers.get("Retry-After", "1"))
@contextmanager
def fixture():
server = HTTPServer(("127.0.0.1", 0), Handler)
thread = Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
yield "http://127.0.0.1:" + str(server.server_port)
finally:
server.shutdown()
server.server_close()
thread.join()
with fixture() as base:
state, body, states = wait_for_job(base)
assert states == ["queued", "running", "succeeded"]
assert body["result"] == {"rows": 3}
print("success:", states)
state, body, states = wait_for_job(base, fail=True)
assert states == ["queued", "running", "failed"]
assert body["error"]["code"] == "EXPORT_FAILED"
print("failure:", states)
try:
wait_for_job(base, budget=0)
raise AssertionError("Expected a polling deadline")
except PollDeadline as exc:
assert exc.monitor_url.startswith(base + "/jobs/")
print("deadline: monitor URL retained; outcome unknown")Read the outcomes as operation results
The successful fixture observes queued, running and succeeded, then checks the result body. The failure fixture observes queued, running and failed, then checks EXPORT_FAILED. Both use HTTP 200 to retrieve each monitor representation. This proves why a generic “HTTP request succeeded” test cannot replace interpretation of the API’s state field.
The zero-budget case still submits a request, then raises PollDeadline before polling. The exception retains monitor_url. In a real client, save that identity in a resumable workflow or an appropriate application record. Avoid writing credential-bearing monitor URLs into ordinary logs; some services use signed URLs that grant access to status or results.
An actual worker system needs stronger guarantees than this fixture. Persist accepted work before acknowledging it, associate the operation with its owner and maintain a recoverable state transition process. If a worker crashes after writing output but before marking success, recovery should reconcile the durable result instead of producing duplicate effects.
success: ['queued', 'running', 'succeeded']
failure: ['queued', 'running', 'failed']
deadline: monitor URL retained; outcome unknownSource: Microsoft Azure Architecture Center: asynchronous request-reply pattern ↗
Secure status and result access independently
A monitor URL is not automatically public just because its identifier is hard to guess. Authorize monitor and result access against the operation’s owner or tenant. If you return signed result URLs, define their expiry and avoid exposing them to another tenant through a shared cache or a log.
Clients should resolve relative monitor URLs against the response’s request URL and apply an explicit trust policy before sending credentials. Do not blindly follow a cross-origin Location with an Authorization header intended for the original API. If redirects are part of the contract, define which origins and methods are permitted. Browser clients also need the relevant response headers exposed through CORS when reading a cross-origin response.
If users can cancel work, document cancellation separately. A cancel request may race with successful completion, and abandoning a browser tab is not a reliable cancellation signal. Show whether cancellation was merely requested or actually completed. Preserve the terminal result when work already finished rather than inventing a canceled state.
Source: Microsoft Azure Architecture Center: asynchronous request-reply pattern ↗
Diagnose the point where progress stopped
When a client reports “stuck after 202,” capture the operation ID, submission timestamp, last observed state and last successful poll. Check whether the client followed the right monitor, whether polling stopped on an HTTP error, and whether a cached status response is obscuring progress. This example uses no-store; a production API may use another explicit cache and validator policy.
On the server, distinguish accepted work that never reached a worker from a running task that stopped making progress. Keep queue age and execution duration separate. If the worker completed but the monitor remains running, inspect the update that publishes the terminal state. If a success state points to a missing result, inspect result persistence and retention ordering.
For the interface, use separate messages for “accepted,” “still processing,” “completed,” “failed,” and “we stopped waiting.” Let users resume monitoring an existing operation. The useful end-to-end test is whether a newly submitted task reaches a verified terminal outcome and produces its promised result, including a controlled failure case—not whether the POST returned 202.
Source: RFC 9110: HTTP 202 Accepted and Retry-After semantics ↗
Your next steps
- Track submission success and operation success as separate events.
- Poll the documented monitor with bounded timing and explicit state handling.
- Retain operation identity on timeout and verify both successful and failed workflows.
Sources & official resources
Linked resources checked on 2026-11-11. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →