TenkeyBridge
← Back to blog

QuickBooks Batch Requests Are Not Transactions: Handling Partial Failure on Desktop

  • quickbooks batch api
  • quickbooks batch partial failure
  • quickbooks desktop batch operations
Developer at a desk reviewing a JSON batch response on screen with several faulted items highlighted.

Quick answers

  • Is a QuickBooks batch request atomic? No — each item in the batch succeeds or fails independently, and there is no rollback of the items that already committed.
  • How do I know which items failed? Match each response element to the bId you sent; successful items carry the created or updated object, failed items carry a Fault.
  • What makes the entire request fail? Structural problems — malformed JSON, a missing or duplicate bId, an unknown operation, or exceeding the item limit — are rejected before any item runs.
  • How do I retry safely? Rebuild a new batch containing only the failed bIds, and on a stale-object fault (error 5010) re-read the object to get a fresh SyncToken before resending.
  • Does this differ between QuickBooks Online and Desktop? The semantics are the same; Desktop's limits and the set of supported entities differ, so check the compatibility matrix.

Batch endpoints look like transactions. They take a list, they return a list, and the shape of the thing invites you to think "all of this happens, or none of it does." That is not what the QuickBooks batch API does, on Online or on Desktop. It is a request-multiplexer: a way to spend one HTTP round trip instead of thirty. Each item is evaluated on its own, and the response is a bag of independent outcomes.

Most integrations get away with ignoring this for a while, because in the happy path the distinction is invisible. It stops being invisible the first time a nightly push writes 18 of 25 invoices and your job logs say "batch failed."

This post is about the failure modes: what partial failure actually looks like, which errors kill the whole request instead of one item, and how to write a retry loop that doesn't double-post.

Batch is not a transaction

The mental model worth internalizing: a batch is a loop the server runs for you, not a unit of work.

Send five invoice creates. Items one, two, and four succeed and are written to the company file. Item three fails validation — a customer reference that doesn't resolve. Item five fails because another process already bumped the SyncToken on the entity you're updating.

What you get back is HTTP 200, with five result elements. Three of them contain objects with real Id values that exist in QuickBooks right now. Two of them contain faults. Nothing rolls back. The three invoices that landed are still there whether or not you handle the other two.

This has a practical consequence that trips people up: a non-2xx status code is not how you detect per-item failure. A batch where every single item faulted still returns 200. If your HTTP client's error handling is the only place you check for problems, you will silently drop data.

POST /v3/company/{realmId}/batch
Content-Type: application/json
{
  "BatchItemRequest": [
    { "bId": "inv-1001", "operation": "create", "Invoice": { "...": "..." } },
    { "bId": "inv-1002", "operation": "create", "Invoice": { "...": "..." } },
    { "bId": "cust-77",  "operation": "update", "Customer": { "...": "..." } }
  ]
}

And the response, abbreviated:

{
  "BatchItemResponse": [
    { "bId": "inv-1001", "Invoice": { "Id": "4021", "SyncToken": "0" } },
    { "bId": "inv-1002", "Fault": { "type": "ValidationFault", "Error": [
        { "code": "6240", "Message": "Required param missing",
          "Detail": "Required parameter CustomerRef is missing" } ] } },
    { "bId": "cust-77", "Fault": { "type": "ValidationFault", "Error": [
        { "code": "5010", "Message": "Stale Object Error",
          "Detail": "Object has been updated since you last read it" } ] } }
  ]
}

Invoice 4021 exists. The other two did not happen. That is the whole semantics.

Read results by bId, never by position

The bId is a client-supplied correlation key. You choose it; the server echoes it. Treat it as the only reliable join between what you sent and what you got.

Do not index into the response array by position. Nothing in the contract promises the response preserves request order, and even if it happens to today, position-based matching turns a reordering into a silent data-corruption bug — you'd attribute invoice 4021's new Id to the wrong record in your database.

Some rules that have earned their place:

  • Make bId meaningful and unique within the request. Use something that maps back to your own primary key: inv-1001, cust-77. Duplicate bId values are a structural error (more on that below).
  • Build a dictionary first. Index the response by bId, then walk your original request items and look each one up. If a bId you sent has no corresponding response element, treat that as a failure, not a success — do not assume silence means it worked.
  • Don't reuse a bId across retries with different content. If you're going to log and correlate, the string should mean the same thing every time it appears.

Structural errors fail the whole request

Per-item independence applies to items the server was able to parse and dispatch. Problems with the envelope are different: they're rejected before anything runs, and you get a non-2xx response with no BatchItemResponse at all.

Structural failures include:

  • Malformed JSON. Nothing is parsed, nothing runs.
  • A missing bId on any item — the server can't produce a correlatable response, so it refuses the request.
  • Duplicate bId values within one request, for the same reason.
  • An unknown or unsupported operation. create, update, delete, and query are the vocabulary; a typo is a request-level reject.
  • Exceeding the item limit. The batch endpoint caps how many items one request may carry; go over and the request is refused wholesale rather than truncated. The current cap is documented in the batch guide — read it there rather than hardcoding a number from a blog post.

This split is actually the good design. A structural reject is loud, happens before side effects, and is safe to fix and resend in full. The alternative — partially executing a request the server couldn't fully understand — would be much worse to clean up after.

The operational takeaway: validate structure client-side before you send. Checking for duplicate bIds and counting items is cheap. Discovering the problem from a 400 after you've assembled a 500-item payload is not.

The stale-object case deserves its own handling

Error 5010, stale object, is the one failure in this list that is expected in normal operation rather than a bug. It means the SyncToken you sent no longer matches the one on the record, because something changed it since you read it — another user in the QuickBooks UI, another process, or an earlier item in your own batch.

QuickBooks uses SyncToken as an optimistic-concurrency version number. You read an object, you get a token, you send the token back with your update, and the write is rejected if the token has moved. This is a feature: it's what prevents your overnight sync from silently reverting a bookkeeper's manual correction from an hour ago. If you want the longer treatment of how tokens interact with partial writes, we covered it in sparse updates vs. full replacement — the short version is that a sparse update with a stale token is still rejected, and that's correct.

The retry for 5010 is not "send it again." Sending the same payload with the same token will fail identically, forever. The retry is:

  1. Re-read the object to get the current SyncToken — and the current field values.
  2. Decide whether your intended change still makes sense given what changed underneath you.
  3. Resend with the fresh token.

Step 2 is the one people skip. If the remote record changed because a human edited it, blindly re-applying your write can clobber that edit. For a sparse update touching fields nobody else owns, re-apply freely. For anything where your system and a human both write the same field, you need a rule — last-writer-wins, or skip-and-flag, or whatever your business actually wants — and you should write it down somewhere other than a comment.

Note also the within-batch case: if a batch contains two updates to the same entity, the second one carries a token that the first one just invalidated. The second item fails with 5010 even though both items were "correct" when you built the request. Deduplicate updates by entity ID before batching.

Writing an idempotent retry

Here's the shape of a retry loop that doesn't duplicate data.

def submit_batch(client, items, max_attempts=3):
    pending = {item["bId"]: item for item in items}
    results, failures = {}, {}

    for attempt in range(max_attempts):
        if not pending:
            break

        response = client.batch(list(pending.values()))  # raises on 4xx/5xx
        by_bid = {r["bId"]: r for r in response["BatchItemResponse"]}

        next_pending = {}
        for bid, request_item in pending.items():
            result = by_bid.get(bid)

            if result is None:                      # no response = not confirmed
                next_pending[bid] = request_item
            elif "Fault" in result:
                code = result["Fault"]["Error"][0]["code"]
                if code == "5010":                  # stale: refetch, re-decide
                    refreshed = refresh_sync_token(client, request_item)
                    if refreshed:
                        next_pending[bid] = refreshed
                    else:
                        failures[bid] = result      # conflict we won't auto-resolve
                elif is_retryable(code):
                    next_pending[bid] = request_item
                else:
                    failures[bid] = result          # validation: a human must look
            else:
                results[bid] = result               # committed; never resend

        pending = next_pending

    failures.update({bid: {"Fault": "max attempts"} for bid in pending})
    return results, failures

The properties that matter:

  • Successful items leave pending permanently. A committed create is never in a later attempt's payload. This is the entire defense against duplicate invoices.
  • Validation faults are terminal. Error 6240 ("required param missing") will produce the same result on attempt three as on attempt one. Retrying it burns quota and hides the real problem. Park it for a human.
  • Stale-object faults are rebuilt, not resent. refresh_sync_token re-reads and returns a new request item, or returns None if the conflict is one you've decided not to resolve automatically.
  • A missing response is treated as unconfirmed, not failed. This is the one genuinely ambiguous state. If you retry a create you can't confirm, you risk a duplicate; if you don't, you risk a silent drop. Prefer a design where you can check: a stable DocNumber you can query for, or a reconciliation pass that finds orphans. Pick the failure you can detect.

What "idempotent" means here

The QuickBooks batch endpoint does not take an idempotency key. There is no server-side dedupe that will catch a create you sent twice. Idempotency in this context is something your client implements, by tracking which bIds have committed and refusing to resend them.

That's a strong argument for persisting batch state rather than keeping it in a local variable. If your process dies between the response and the database write, an in-memory results map dies with it, and the next run has no idea invoice 4021 already exists. A durable "submitted / confirmed / failed" column on your side of the sync is dull and it saves you.

Classify errors before you retry

The retry logic above hinges on is_retryable(code), which is where the real design work lives. Broadly, three buckets:

  • Terminal — validation faults, unresolvable references, permission errors. Resending changes nothing. Surface these to an operator with the bId and enough context to act.
  • Rebuild-then-retry — stale-object (5010) and anything else where the payload must change before the retry can succeed.
  • Transient — throttling and timeouts. Back off and resend the same items.

Desktop adds a wrinkle worth knowing: the underlying QuickBooks Desktop errors are qbXML status codes and HRESULTs, not QBO fault codes. TenkeyBridge maps them into QBO-shaped faults so your existing handler keeps working, but the mapping isn't always one-to-one, and a Desktop-origin condition can surface with a Detail string that reads differently from what QBO would say. We walked through that translation layer in decoding QuickBooks Desktop errors. If you're switching a working QBO integration over, the error-handling branch is usually where the surprises are — the full list is in the error code reference.

Limits, honestly

A few things to size for rather than discover:

  • Item count is capped per request. Chunk your work client-side; don't rely on the server to split for you. The documented cap is in the batch guide.
  • A batch is one round trip, not one unit of work. Batching reduces HTTP overhead. It does not reduce the amount of work QuickBooks does, and on Desktop that work runs against a company file, which has its own concurrency characteristics. A 30-item batch is not 30x faster than 30 requests; it's one connection instead of 30.
  • Not every entity and operation supported in QBO has a Desktop equivalent. That's a parity question, not a batch question, but it shows up inside batches as per-item faults. Check the Desktop parity matrix before you build a batch that assumes an entity exists.
  • Batch is not a bulk-read tool. query operations are allowed as batch items, but for pulling changed records across a company file, change data capture is the right instrument — with its own window and object-count limits that we documented separately.

If you're porting an existing QuickBooks Online integration to Desktop, the batch semantics described here are the same on both sides — same endpoint shape, same bId correlation, same non-atomicity. That's the point of a QBO-compatible API for Desktop: your batch code mostly doesn't change. What changes is which errors you see and how often, which is exactly why the retry classifier is worth writing properly before you need it.

FAQ

Is a QuickBooks batch atomic?

No. Each item in a BatchItemRequest is processed independently, and items that succeed are committed to the company file even if other items in the same request fail. There is no rollback, no two-phase commit, and no way to ask for one. If you need all-or-nothing semantics across several objects, you have to build compensating logic yourself — write, check, and reverse on failure.

How do I retry only the failed items?

Index the response by bId, keep the items whose result contains a Fault, and build a new batch from just those. Never resend a bId whose response contained a committed object — that's how duplicate invoices happen. For stale-object faults (5010), re-read the entity to get a current SyncToken before resending rather than retrying the identical payload.

What makes a whole batch request fail?

Structural problems with the request itself: malformed JSON, a missing or duplicated bId, an unrecognized operation, or more items than the endpoint accepts. These are rejected before any item executes, so you get a non-2xx response with no per-item results and no side effects. Content-level problems with individual items never fail the whole request.

Can I mix entity types and operations in one batch?

Yes — creates, updates, deletes, and queries across different entity types can go in the same request. The caveat is ordering: items are not guaranteed to execute in the order you listed them, so don't batch a create and an update that depends on its new Id. Split dependent work into sequential requests.

Do batch items count individually against rate limits?

Assume yes. Batching saves HTTP round trips and connection overhead, not the underlying work. Size your batches for throughput and error-handling convenience rather than as a way to slip past throttling.

What if the HTTP connection drops mid-batch?

You're in the ambiguous state: some items may have committed. Don't blindly resend. Query for the records you were trying to create using a field you control — a document number or a reference you set — and reconcile before retrying. This is the main reason to put a stable, queryable identifier on anything you create. If you want to watch partial failure happen without touching a production file, the sandbox takes a malformed batch as happily as a good one — the quickstart gets you a token in a few minutes.