Payments are experiencing issues due to temporary restrictions in Russia. If your payment does not go through, please submit a support request.Our support team is available 24/7 — we are always here to help with hosting and server issues.We are now accepting requests for dedicated server rental and colocation services in our data center.Reminder: we recommend enabling backups for additional data protection.A new VPS/VDS lineup with NVMe storage and improved performance is now available.Maintenance work on some servers has been completed. All services are operating normally.
Article12 min readViews3

API Returned 202 Accepted: How to Wait for the Job and Avoid Running the Import Twice

We test the asynchronous API against a safe model: a lost response returns the same job, intermediate status is not treated as success, and a modified command or terminal failure yields an explicit rejection.

Comments 0

Two metal capsules at a bright automated gateway: one accepted for processing, the other stopped
In this article

The code 202 Accepted only means that the API accepted the request for processing. Import, price recalculation, or stock update may still be running and could even fail. The client needs a job status address, clear terminal statuses, and a stable operation identifier. With a correct server implementation, a retry with the same identifier after a lost response returns the original job, not a second import.

In a small example, the server accepts an update for two SKU, but the response to create the job is lost. A retry with the same operation_id returns the previous job-1. The polling proceeds through running to succeeded. The modified load under the old identifier is rejected, while a separate failure remains failed. Good asynchronous design requires a bit more patience, but results in significantly fewer duplicate product movements.

What 202 promises and what remains the API contract

Standard RFC 9110 defines 202 as Accepted but not yet completed: processing may subsequently not occur. The Asynchronous Request-Reply pattern shows a common variant with a status address in Location, a hint in Retry-After, and distinct states Pending, Running, Succeeded, Failed, or Canceled. This is an example of a contract, not a mandatory format for every API.

The tutorial run below does not start an HTTP server, does not connect to 1C-Bitrix, and does not simulate a specific supplier. It separately checks client and server invariants in process memory: one logical command creates one job, a repeat with the same body finds it, and a new body under the old key is not mistaken for a repeat. All calls execute sequentially in a single process. Dictionaries exist only until the process ends: the model does not check concurrent POST, key registration atomicity, recovery after restart, or the idempotency retention period.

Initial Conditions

  • CPython 3.12.14 and the standard library only; the run was performed on November 6, 2026.

  • Isolated process without network, file-based database, background services, or user data.

  • Warehouse WH-1 receives absolute inventory values: SKU-A=7 and SKU-B=0; operation_id equals op-stock-101.

  • The first 202 response is lost after the server has already created job-1.

  • Polling allows only running, succeeded, and failed; success is confirmed by a substantive result.

  • For a modified body under the previous operation_id, an explicit PayloadConflict is expected, not the launch of a new job.

Step

Client signal

Expected result

1

POST op-stock-101

202, job-1 created

2

Response lost; the same POST repeated

202, the same job-1 returned

3

First poll of job-1

running; no business result yet

4

Second poll job-1

succeeded; updated=2

5

Old operation_id with different body

PayloadConflict

6

Separate job-2 ended with an error

failed; reason preserved

Diagram of two sequential requests with one operation_id: the first response is lost, the retry returns the original job-1
Reproducible sequence: A is the client, B is the API. Both POST requests contain op-stock-101 and the same body. After the first POST, job-1 is created, but the 202 response is lost (cross). The retry returns the same job-1: reused=True, jobs=1. The diagram shows order, not request duration; this is a model schematic, not a record of real network traffic.

Reproducible Model

Create a new empty directory, save the code to the async_job_lab.py file, and run it as a standard user. The script reads nothing, changes nothing, and deletes nothing outside the memory of its own process.

from dataclasses import dataclass from hashlib import sha256 import json class PayloadConflict(RuntimeError): pass @dataclass class Job: job_id: str operation_id: str payload_hash: str polls: int = 0 terminal: str | None = None class FakeAsyncApi: def __init__(self) -> None: self.jobs: dict[str, Job] = {} self.by_operation: dict[str, str] = {} @staticmethod def digest(payload: dict[str, object]) -> str: encoded = json.dumps( payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False ).encode("utf-8") return sha256(encoded).hexdigest() def start(self, operation_id: str, payload: dict[str, object]) -> dict[str, object]: payload_hash = self.digest(payload) if operation_id in self.by_operation: job = self.jobs[self.by_operation[operation_id]] if job.payload_hash != payload_hash: raise PayloadConflict("same operation_id with different payload") return { "http": 202, "job_id": job.job_id, "location": f"/jobs/{job.job_id}", "retry_after": 2, "reused": True, } job_id = f"job-{len(self.jobs) + 1}" job = Job(job_id, operation_id, payload_hash) self.jobs[job_id] = job self.by_operation[operation_id] = job_id return { "http": 202, "job_id": job_id, "location": f"/jobs/{job_id}", "retry_after": 2, "reused": False, } def poll(self, job_id: str) -> dict[str, object]: job = self.jobs[job_id] job.polls += 1 if job.terminal == "failed": return {"http": 200, "status": "failed", "error": "supplier_unavailable"} if job.polls == 1: return {"http": 200, "status": "running"} return {"http": 200, "status": "succeeded", "result": {"updated": 2}} api = FakeAsyncApi() payload = {"warehouse": "WH-1", "stocks": {"SKU-A": 7, "SKU-B": 0}} # The server accepts the job, but the client loses the response. lost_response = api.start("op-stock-101", payload) # A retry with the same operation_id and the same payload returns the same job. retry_response = api.start("op-stock-101", payload) assert lost_response["job_id"] == retry_response["job_id"] == "job-1" assert retry_response["reused"] is True and len(api.jobs) == 1 print( "retry: " f"http={retry_response['http']} job={retry_response['job_id']} " f"reused={retry_response['reused']} jobs={len(api.jobs)}" ) first_poll = api.poll("job-1") second_poll = api.poll("job-1") assert first_poll["status"] == "running" assert second_poll == {"http": 200, "status": "succeeded", "result": {"updated": 2}} print( "poll: " f"first={first_poll['status']} second={second_poll['status']} " f"updated={second_poll['result']['updated']}" ) try: api.start("op-stock-101", {"warehouse": "WH-1", "stocks": {"SKU-A": 8}}) except PayloadConflict as error: print(f"conflict: {error}") else: raise AssertionError("changed payload was accepted under the old operation_id") failed = api.start("op-stock-102", {"warehouse": "WH-2", "stocks": {"SKU-C": 4}}) api.jobs[failed["job_id"]].terminal = "failed" failed_poll = api.poll(failed["job_id"]) assert failed_poll["status"] == "failed" assert failed_poll["error"] == "supplier_unavailable" assert len(api.jobs) == 2 print( "terminal: " f"job={failed['job_id']} status={failed_poll['status']} " f"error={failed_poll['error']} jobs={len(api.jobs)}" )

Launch command:

python3 async_job_lab.py

Output received:

retry: http=202 job=job-1 reused=True jobs=1 poll: first=running second=succeeded updated=2 conflict: same operation_id with different payload terminal: job=job-2 status=failed error=supplier_unavailable jobs=2

Re-check on November 13, 2026, on CPython 3.12.14: the process terminated twice with code 0, and the output matched the one provided above. The SHA-256 hash of the example file is c1ab1f3456a8260cb82e400d85b5365ebf7eea1ff8ea5cf27073f8b1b47ba853. Assert checks confirm a single job after a sequential repeat, different responses for running and succeeded, rejection of the modified body, and a separate failed. There is no client-side wait cycle or actual update of the product catalog here: updated=2 is a pre-defined model result. Saving SKU-B=0 to the real product catalog is verified separately on a project copy.

What the run confirmed

Verification

Naive solution

Verified solution

Response 202 was lost

A repeated POST may create a second job

The same operation_id returns job-1; jobs=1

Status running

Consider import complete

Continue limited polling

Status succeeded

Limit to checking HTTP 200

Check terminal status and result.updated=2

Body changed

Execute modified command under previous operation_id

Reject PayloadConflict

Background operation failed

Green status for original 202

Record failed and supplier_unavailable

How to handle an asynchronous job

  1. Before the first POST, establish a stable operation_id and save it together with the exact normalized body or its cryptographic hash.

  2. After 202, save job_id and the verified Location. Do not mark the order or import as completed, and do not consider stock data updated.

  3. If the response to POST is ambiguous, repeat the request only according to documented API rules and with the original operation_id. A new key may create a second task.

  4. Poll at the address and interval specified in the contract, with a total wait time, a maximum number of requests, and the ability to stop the process via command.

  5. Distinguish between intermediate and terminal states. Only documented success and a verifiable result allow completing the local operation.

  6. At failed, preserve the machine code and secure details without converting the executor's error into a successful transport outcome.

  7. After the state retention period expires, predefine the verification method: retrieve the actual result for the business object, restore the saved response, or escalate the task for review.

Retry-After helps avoid polling the service too frequently, but it is not a guarantee of completion time. If the provider does not return Location or a documented task identifier, do not fabricate them on the client side and declare the contract ready. You must use the designated operation search method or agree on a custom intermediary.

For a project client, the waiting sequence must be defined separately. For example, test settings might include: a total budget of B=60 seconds from the start of waiting, no more than N=10 status requests, and a network timeout of T=5 seconds. These are client-selected limits, not a provider guarantee. Below is the design algorithm; it is not implemented and has not been tested as a network client in the provided script.

  1. Save job_id, the status address, the original operation_id, and the command body. Use monotonic clocks for the total budget B, and initialize the request counter to zero.

  2. Before each request, check for user cancellation, remaining budget, and whether the limit N has been exhausted. On cancellation, budget exhaustion, or reaching N, stop waiting with the status "result currently unknown". For the request itself, limit the timeout to the smaller of T and the remaining budget; increment the attempt counter.

  3. Validate the transport response and body against the API contract. Do not record business success for running. The next poll is allowed only after the permissible interval Retry-After or another documented interval; if it does not fit within the remaining budget, stop waiting.

  4. For succeeded, verify the mandatory result and compliance with the expected operation. The model expects updated=2; in actual batch import, the outcome of each SKU is required along with a check of the actual state. A missing or incomplete result demands investigation of the cause and verification, not a green checkmark.

  5. For failed, preserve the machine reason and display the failure to the operator. An unknown status, invalid response, or unavailable state must be sent to the contractually specified verification; do not launch a new import blindly.

  6. A network timeout, a shared deadline, and stopping local waiting do not cancel background work. Preserve the same job for subsequent verification. If the API supports cancellation, request it through standard procedures and confirm the outcome separately; a new POST with a new key is not a cancellation.

Model responses: the first poll for job-1 returns running, the second returns succeeded with updated=2; the first poll for a separate job-2 returns failed
Observed responses from the test API: for job-1, the first poll returns running, the second returns succeeded with result.updated=2; a separate job-2 returns failed with error=supplier_unavailable on the first poll. All three responses have HTTP 200, so a transport code alone is insufficient. The schema does not show the transition from running to failed, nor does it prove the application of warehouse stock levels.

Failures and edge cases

  • 202 received, but Location is missing or points to an address inaccessible to the client;

  • the server first responds with running, then returns an unknown state;

  • two workers simultaneously poll and complete the same local record;

  • the job is completed, but the response with succeeded was lost;

  • the job status was removed before the client could read the result;

  • the supplier allows cancellation, but cancel and completion occur simultaneously;

  • the package was accepted in full, yet the result contains partial rejections for SKU.

The last case cannot be closed with a single status succeeded: during batch processing, the result for each item must be accepted separately. If the job reports overall success but does not allow mapping SKU to outcomes, the API client still does not know which warehouse stock levels or prices were applied.

Boundary with 1C-Bitrix and store exchange

In 1C-Bitrix: Site Management, an asynchronous job may appear in its own import module, integration queue, or external service. This model does not describe the standard protocol for exchange with 1C and does not guarantee the presence of operation_id, Location, or a status method in a specific edition. Before implementation, verify the product and module version, exchange direction, product or product variant, warehouse, price and stock fields, technical user permissions, and external API documentation. On the actual service side, separately verify atomic key registration together with the cryptographic hash of the normalized request body, durable storage of the job and result, and key expiration time. A standard dictionary from the example does not protect against two simultaneous POST or process restarts.

  1. On a project copy, send a minimal package with two known SKU and absolute values.

  2. Artificially lose the response only on the test route and confirm that the retry does not create a second job.

  3. Verify running without changing the business status, then succeeded with the actual catalog state.

  4. Repeat with a stock value of 0: zero must remain a meaningful value, not a missing field.

  5. Obtain the terminal status failed and verify that the local task is visible to the operator, is not marked as completed, and does not repeat infinitely.

  6. Separately check the partial result for SKU if the external service processes the package non-atomically.

If a retry changes the product quantity by a delta, an idempotency contract is additionally required: its testable example is analyzed in the material "Delta in the API: How to Exclude Repeated Addition of Product Quantity". Here, a different question is addressed—how to distinguish acceptance of a long-running task from its completion.

The readiness criterion is measurable: a lost creation response must not multiply tasks, an intermediate status must not be presented as a result, a modified command must not be hidden under an old key, and succeeded and failed must lead to different testable actions. As long as the client knows only "we received a 202 response," they know the beginning of the story. The ending remains honestly silent.

Discussion 0

Share your experience and ask questions. Comments without links appear after editorial review.

No comments yet. Start the discussion.