Last reviewed: November 15, 2026 (Asia/Shanghai). Public references were retrieved November 14 UTC.

Direct answer

Control CometAPI costs from Lambda SQS batch retries by enabling ReportBatchItemFailures on the event source mapping and returning the identifiers of records that still need queue delivery. Persist each completed record’s outcome before treating it as successful. On redelivery, consult that durable outcome and the existing model attempt before authorizing any new generation.

AWS’s SQS error-handling reference says a failed batch makes all its messages visible again by default, including successfully processed messages. One bad record can therefore send a naive handler back through several already completed CometAPI calls. Partial batch responses narrow that replay to failed records; durable application state protects against duplicates that remain possible.

Who this is for

This guide is for application engineers and AI cost owners processing independent CometAPI text jobs through a Lambda event source mapping attached to an SQS standard queue. It assumes a controlled model adapter, durable job and attempt records, and an existing queue recovery policy.

The response examples and acceptance criteria are implementation guidance. No Lambda deployment, authenticated CometAPI generation, or billing experiment was performed for this article. An SQS batch is a transport grouping, not a provider batch API request or a model discount.

Key takeaways

  • Configure partial responses on the mapping and implement the matching handler response.
  • Return SQS messageId values in itemIdentifier; keep business job and model attempt identities separate.
  • Omit a record only after its outcome or recovery responsibility is durable.
  • Expect duplicates even after partial responses are enabled.
  • Keep an uncertain model attempt reserved when its queue record returns.
  • Compare model attempts per completed job alongside record deliveries and Lambda invocations.

Contract details to verify

Find the batch-wide spending trigger

The Lambda and SQS integration guide documents synchronous invocation with batches of queue messages. Successful processing lets Lambda delete messages. By default, a batch-processing error makes the batch’s messages visible again after the visibility timeout. The same guide warns that event source mappings process events at least once and duplicate record processing can occur.

Consider a handler that generates nine summaries, encounters an invalid tenth record, and throws. Without partial reporting, the nine successful records can return with the failed work. If the handler treats every delivery as a new generation, its next invocation can purchase those summaries again. Disabling retries inside the HTTP client leaves this outer retry path intact.

Inspect the actual event source mapping, rather than only the function’s application settings. Its FunctionResponseTypes must include ReportBatchItemFailures. The handler must also return the documented response shape. Changing one side alone does not establish the intended per-record behavior.

Treat the response as a deletion decision

Suppose one invocation receives SQS records with message IDs message-a, message-b, and message-c. The application durably completes A and C, while B still requires delivery. Its response is:

{
  "batchItemFailures": [
    { "itemIdentifier": "message-b" }
  ]
}

Use the SQS record’s messageId here. A business job_id, model attempt ID, or receipt handle is a different identifier. Resolve the job from the record, but map the queue decision back to the identifier Lambda supplied in that event.

AWS’s error-handling reference documents two consequential boundaries:

Returned outcomeDocumented batch treatmentApplication implication
Valid list containing B’s message IDPartial failure for the reported recordA and C must already be safe to release from this delivery
Empty or null failure list; empty or null event responseComplete successAccidentally omitting a failure can lose its queue trigger
Invalid JSON, invalid identifier, or an identifier absent from the batchComplete failureA malformed response can replay completed work
Function throws an exceptionComplete failureA final throw defeats the partial decisions collected earlier

Always produce an explicit object with the exact keys. Catch record-level failures into the failure list, while preserving the underlying attempt state. A broad catch that logs an error and returns an empty list can cause deletion of work that still lacks a durable outcome.

Keep record completion separate from model completion

Receiving an answer does not finish the queue record if the answer and its accounting evidence exist only in Lambda memory. Store the result and financial evidence, or durably transfer their recovery responsibility, before omitting that record from the failure list.

A practical decision table is:

Durable application stateQueue response decisionModel action on another delivery
Result and attempt evidence committedOmit from failuresReturn recorded state; no generation
Permanent rejection committed to the approved quarantine pathOmit from failuresPreserve rejection; no generation
No dispatch occurred; record remains eligible but processing deferredInclude unless a durable recovery path has accepted itRecheck eligibility and financial admission
Prior dispatch may have occurred; no durable recovery handoffInclude and retain unresolved stateReconcile the same attempt; do not blindly resend
Recovery service durably owns an unresolved attemptOmit only under that explicit handoff contractRecovery service controls the existing identity

These are recommended application rules, not states supplied by Lambda. If the store is unavailable and neither completion nor recovery can be confirmed, keep the record failed. Another delivery must find the unresolved attempt rather than infer that failure means permission to generate again.

Operator workflow

Make the record handler safe to revisit

Use a stable application job identity bound to the authorized workload and immutable input revision. Retain the SQS message ID for transport correlation and a distinct attempt ID for each authorized outbound call. A re-enqueued job must still resolve its original business state.

For each record, follow this sequence:

  1. Resolve and validate its job and frozen request bindings.
  2. Read the durable outcome. A completed or terminally rejected job needs no new generation.
  3. If an earlier attempt is active or uncertain, defer to that state or its recorded recovery owner.
  4. For genuinely new eligible work, atomically reserve the covered exposure and grant one single-use dispatch claim.
  5. Make the approved bounded model attempt, then persist its result and usage evidence through a separate recovery-capable path.
  6. Decide whether this queue record is complete, durably handed off, or still requires delivery. Build the final failure list from those decisions.

Use the site’s atomic budget reservation workflow for financial admission. Reading the same stored claim token does not grant a second send. A timed-out or expired claim needs reconciliation, including preventing a delayed former owner from sending, before a replacement is authorized.

When generation succeeds but persistence fails, retry persistence using the captured evidence. Do not let a generateAndSave wrapper restart both stages. If the process loses the evidence, retain the attempt’s unresolved exposure. The ambiguous-attempt reconciliation guide covers that recovery decision.

Bound the work before returning the response

Choose batch size, per-record concurrency, and outbound timeouts so the function has time to persist outcomes and return its response. For a sequential handler, check remaining execution time before starting another record. Include records left unprocessed in the failure list. For concurrent processing, await the started record tasks and construct one final response from their recorded outcomes.

A function that never returns cannot deliver a partial response. Earlier completed records may then be delivered again, which is another reason durable outcomes remain necessary. Keep queue visibility and runtime settings under review, but do not present a longer visibility interval as duplicate suppression.

AWS also documents that enabling ReportBatchItemFailures prevents Lambda from scaling down message polling when function invocations fail. Do not rely on repeated record failures to act as a spending brake. Keep an explicit shared admission limit, an approved retry and queue redrive policy, and an incident procedure for pausing new model dispatch.

A budget denial is a local processing decision. It is not permission to discard required work. Either retain the queue failure or commit an approved deferred-work handoff before releasing the record. Recovery must preserve the original job and cumulative attempt history.

Measure the spending effect

CometAPI’s pre-call cost guide bases estimates on model pricing and the endpoint’s billable units, including input size and output limits. It directs users to actual usage and billing records after completion. Apply that distinction to every model attempt, including those whose queue invocation later fails.

Consider a deliberately simplified counterfactual. Ten records contain nine valid jobs and one invalid job that fails before model dispatch. Assume all ten are delivered together three times, the naive handler regenerates all nine valid jobs on every delivery, and each model attempt costs a hypothetical average of $0.004. Compare that with partial reporting, where only the invalid record is delivered twice more:

Quantity across the exampleWhole-batch replay without durable suppressionValid partial reporting
Lambda invocations33
Record deliveries3012
Model attempts279
Illustrative model cost$0.108$0.036

The illustrative difference is 18 attempts and $0.072 before AWS and coordination costs. The example assumes fixed retry grouping solely for arithmetic; actual retry batches need not preserve that grouping. The rate is fictional, output costs can vary, and no savings were measured.

If durable state already suppresses generation for completed jobs, whole-batch replay in the same fixture can also remain at nine model attempts. Partial reporting can still reduce record reprocessing, but it cannot claim those model savings a second time. Compare against the actual deployed baseline.

Record job ID, SQS message ID, Lambda invocation ID, attempt ID, response decision, pricing revision, reported usage, calculated cost, and reconciliation state. Keep contents and credentials out of routine cost events. Charge usage once per attempt; queue redelivery does not create another charge for the same evidence. A new outbound attempt can create additional exposure and needs separate admission.

Track record deliveries per completed job, model attempts per completed job, calculated model cost per completed job, and unresolved reserved value. Keep Lambda and SQS charges in separate subtotals. An estimate supports planning; a monetary ceiling needs verified bounds for every covered billable component.

Verification before rollout

Start with a counted fake model adapter and no usable provider credential. Validate handler responses locally, then confirm event source mapping behavior in a disposable AWS integration. These are proposed acceptance criteria, not reported test results.

ScenarioRequired observation
Nine records complete; one fails before generationResponse lists only the failed SQS message ID; completed results are durable
The failed record is delivered againCompleted jobs create no fresh attempt or settlement
Duplicate arrives despite a previous successful responseDurable job state suppresses new generation
Failure list accidentally uses a business job IDContract check rejects the response before rollout
Per-record errors are followed by an outer throwTest exposes whole-batch failure and the replay path
Catch block returns an empty list after persistence failureTest detects unsafe success reporting
Function stops after generation but before storing evidenceAttempt remains unresolved; redelivery cannot blindly resend
Execution allowance is almost exhaustedNo new work starts; all unprocessed records are reported
Budget is exhausted while polling continuesAdapter count stays bounded by admission; required work remains recoverable
Recovery handoff or quarantine persistence failsRecord remains failed rather than silently released

Check adapter calls and durable state alongside the queue response. A correctly shaped JSON object alone cannot establish correct deletion, idempotency, or accounting. Authorize a small service canary only after the deployed mapping and handler pass together.

Failure modes

The flag is enabled but the handler still throws. A batch-wide exception bypasses per-record reporting. Return the accumulated failures through the handler’s normal successful return path.

An empty list means “I caught everything.” AWS treats it as complete success. Require a durable disposition for every omitted record.

The queue retry count becomes the model attempt count. A delivery can make no model call, one call, or hidden repeated calls. Count outbound attempts at the controlled adapter.

An unknown attempt is marked ready on redelivery. The first request may already have generated. Preserve its reservation and evidence identity while reconciling.

A lower invocation count is the only target. The example has three invocations in both cases but different model spend. Review record-level work and actual attempt usage.

Sources checked

Three distinct primary public references returned HTTP 200 during live research on November 14, 2026 UTC, November 15 in Asia/Shanghai:

These are currently served official technical references for an evergreen integration task. Retrieval and HTTP modification headers do not establish a feature release date. Recheck the deployed mapping and selected model’s billing contract before rollout. The disposition rules, financial example, and verification matrix are application recommendations derived from those documented boundaries.

FAQ

Does this guarantee exactly one CometAPI call per job?

No. AWS still documents duplicate processing, and an upstream outcome can remain uncertain after a crash. Partial reporting reduces one replay mechanism; durable claims and reconciliation govern permission for additional attempts.

Can I use the same loop with a FIFO queue?

The independent-record workflow here targets a standard queue. AWS says a FIFO handler using partial responses should stop after the first failure and report all failed and unprocessed messages to preserve ordering. Review that contract before adapting the handler.

Should a permanently invalid record retry forever?

Give it an approved terminal rejection or quarantine outcome and make that outcome durable before omitting it. If the application cannot record that disposition, retain failure and follow the queue’s bounded recovery policy.

Is returning a failed record permission to call the model again?

It requests another delivery. The existing job, attempt, deadline, and financial state still determine whether any new model attempt is allowed.

Reader next step

Choose one standard-queue Lambda handler. Verify its deployed FunctionResponseTypes, implement the mixed-success fixture, and prove that both an unsafe empty list and an outer throw are detected. Require durable record dispositions and attempt accounting before expanding traffic.

When those checks pass, Start with CometAPI for one approved bounded integration check. Reconcile model attempts and usage independently of Lambda invocation success.