MLOpsModel Deployment & CI/CD Automation

How do you make production ML inference requests idempotent and prevent duplicate execution during retries and redelivery?

Question 142 of 166 · Updated

On this page

Why inference needs request-level idempotency#

Production inference clients retry when a response is lost, a gateway times out, a worker restarts, or a queue redelivers a message. The first attempt may already have completed expensive inference or committed a downstream action even though the caller never received the acknowledgement. A blind retry can then run the same logical request again, consume GPU capacity twice, write duplicate prediction records, emit duplicate events, or trigger repeated business actions.

Request-level idempotency gives one logical prediction operation a stable identity across multiple transport attempts. The service recognizes a retry, coordinates with any in-flight execution, and returns or exposes the original outcome instead of starting an unintended second operation.

This lesson is deliberately narrower than general MLOps job idempotency (which concerns retried training and pipeline runs). It focuses on production inference request identity, concurrent duplicate arrivals, result replay, durable side effects, retention, and the limits of exactly-once claims.

1. Separate logical operation identity from transport attempts#

A logical operation is what the caller intends to happen once: for example, score payment transaction TX-782 using model release fraud-v42 and the approved feature snapshot. A transport attempt is one HTTP request, RPC call, or queue delivery trying to get that operation completed.

The caller or trusted upstream creates an opaque idempotency key once per logical operation and reuses it for retries. Each transport attempt can have a different request/trace ID. Do not generate a fresh idempotency key on every retry, because the server will interpret every attempt as new work. Conversely, do not derive the key solely from payload equality: two legitimate transactions can have identical features but still be distinct decisions.

A robust identity usually scopes the key by authenticated tenant or principal, API operation, and a client-generated operation token. Store a canonical request digest alongside it. The digest detects accidental or malicious reuse of the same key with a different payload, model selection, or inference options. Return a conflict for a key reused with a different logical request; never silently return a result for a different payload.

For deterministic business operations, include the business operation ID where appropriate. Do not embed sensitive user data in the key. Use opaque random tokens and access-controlled storage.

2. Define the idempotency contract#

Document what repeated submissions mean. A typical contract is:

  • First request with a new key: reserve the operation and execute inference.
  • Same key and same canonical request while running: return an in-progress response, wait within a bounded budget, or return a status resource; do not start a second execution.
  • Same key and same request after success: replay the stored response or return a stable result reference.
  • Same key and same request after a terminal failure: follow a documented policy—replay the failure, allow a controlled retry if the failure is known to be pre-execution, or require a new operation key for a genuinely new decision.
  • Same key with a different request digest: reject as a conflict.
  • Same key after retention expiry: follow an explicit expiry contract; do not pretend deduplication lasts forever.

For synchronous APIs, a repeated request may return the original status and response body, including the same prediction ID, model version, and decision metadata. For large responses, return a stable result URI instead of storing a large payload in the idempotency record.

3. Use atomic reservation, not check-then-act#

A common broken implementation is: query whether key K exists; if not, run inference; then insert K. Two concurrent requests can both observe that K is absent and both run the model. A process-local mutex does not solve this across replicas, regions, or worker restarts.

Use a durable shared store with a unique constraint on the scoped idempotency key. Atomically claim the key before dispatching work. A simplified state record can contain:

  • tenant and operation scope
  • idempotency key and canonical request digest
  • operation status: RESERVED, RUNNING, SUCCEEDED, FAILED, CANCELLED, or EXPIRED
  • stable prediction/result ID
  • selected model and feature snapshot identity
  • creation and expiry timestamps
  • response metadata or result reference
  • lease/owner information for recovery of abandoned workers

The unique constraint is the concurrency arbiter. On conflict, load the existing record and compare the request digest. If it matches, return the in-progress or completed state. If it differs, reject it. Do not rely on an application-level existence check as the correctness boundary.

A reservation lease can help recover when a worker crashes after claiming a key. Leases need ownership tokens or fencing generations so an old worker cannot later overwrite the result after a replacement worker has taken ownership. Expired leases should trigger reconciliation, not immediate duplicate execution without checking whether inference or a side effect already completed.

4. Numerical example: avoid duplicate GPU work#

Assume a fraud inference endpoint receives 80 logical requests per second. Due to transient response loss and client retries, 6% of requests produce one additional transport attempt. Without idempotency, that creates 80 × 0.06 = 4.8 unnecessary model executions per second if the original attempt reached inference.

If each inference consumes 35 ms of GPU execution, duplicate work is 4.8 × 35 ms = 168 ms of GPU time per second. Over one hour, that is 604.8 GPU-seconds of avoidable execution per replica-equivalent workload. At a hypothetical fully allocated GPU cost of $2.40 per hour, the direct compute cost is modest ($0.4032), but the real impact can be larger during saturation because duplicates occupy queue slots and increase tail latency for useful requests.

Suppose a durable idempotency reservation suppresses 95% of those duplicate executions. Avoided execution is 168 × 0.95 = 159.6 ms of GPU time per second. The remaining 8.4 ms/s represents late duplicates that arrived after dispatch or cases where the runtime cannot preempt already-running kernels. Measure actual saved work rather than assuming every duplicate HTTP request equals a duplicate GPU execution.

5. Coordinate duplicate requests that arrive while the first is running#

When two replicas receive the same key at nearly the same time, exactly one should win the atomic reservation. The other should not block indefinitely or spin on the database.

Choose one of three explicit behaviors:

  • Return 202 Accepted with a stable operation/result URL and a retry-after hint.
  • Wait for the existing operation only while the caller's original end-to-end deadline has sufficient budget.
  • Return a documented in-progress response that tells the client to poll or subscribe.

Do not launch a second model execution just because the first has not finished quickly. Do not hold a database transaction open during long GPU inference. Reserve in a short transaction, execute outside the transaction, then commit the terminal state with a conditional update tied to the current lease/fencing token.

If the caller's deadline expires, the operation may continue or be cancelled according to the request contract established in the preceding deadline/cancellation lesson. Idempotency and cancellation are complementary: the key identifies the same operation; cancellation determines whether that operation should continue.

6. Separate inference computation from durable business effects#

Many prediction calls are pure computations: given a fixed model and fixed input snapshot, they produce a prediction without changing external business state. But production workflows often also persist a decision, update a risk case, emit an event, or trigger an action.

A result record and its downstream effects need a clear commit boundary. Where possible, store the idempotency state, prediction result reference, and business decision in one database transaction. If publishing an event, use a transactional outbox: commit the decision and an outbox record atomically, then let a publisher deliver the event at least once. Consumers must be idempotent too, because event delivery can be repeated.

Do not claim end-to-end exactly-once effects merely because the inference API deduplicates requests. A downstream notification provider, feature service, or external business system may not share the same transaction. Propagate the logical operation ID to downstream services and use their idempotency contract or reconciliation mechanism. If a downstream service has no deduplication support, define the ambiguity and recovery process explicitly.

7. Handle the uncertain-outcome window#

A difficult failure occurs when model execution completes, but the worker crashes before recording SUCCEEDED. A retry sees RUNNING or an expired lease and cannot know from the idempotency table alone whether inference completed.

Use durable execution stages and correlation:

  1. Persist the reservation and immutable request/model/feature identity.
  2. Record dispatch attempt and worker ownership.
  3. Persist the prediction artifact/result under a stable operation ID.
  4. Commit the terminal result pointer and business effects atomically where possible.
  5. Reconcile records left RUNNING beyond a bounded threshold.

If the result artifact was written but the terminal state was not, reconciliation can validate its operation ID, content digest, model version, and input identity before completing the record. If no result exists and no worker owns a valid lease, a controlled retry may be safe for pure inference. For external side effects, query the downstream operation by the same idempotency key before repeating it.

A transport timeout is not proof that the server did nothing. Return an explicit unresolved or in-progress state rather than inventing success or failure.

8. Canonical request hashing and model identity#

Canonicalize the semantic request before hashing: normalize field ordering, numeric representation, defaults, and relevant options. Exclude transport-only metadata such as trace IDs and retry counters. Include all fields that change the meaning of the prediction, such as tenant, input values, feature snapshot/version, requested model alias resolution, preprocessing contract, and decision options.

Be careful with model aliases such as production or champion. If an alias can move between attempts, the same idempotency key might resolve to a different model. Pin the resolved immutable model version at reservation time and return that version on every replay. If the caller explicitly requests “latest” and the alias changes before first reservation, the first accepted attempt determines the pinned version.

Hashing sensitive inputs requires privacy review. A plain hash of low-entropy personal fields can be vulnerable to guessing. Prefer a keyed HMAC or a digest of a protected canonical representation, restrict access, and apply retention/deletion policies to stored request metadata.

9. Retention, expiry, and key lifecycle#

Idempotency retention must cover the documented client retry window, queue redelivery horizon, and operational replay window. For example, if clients retry for 30 minutes and a queue can redeliver for 24 hours, a 10-minute key TTL is unsafe. Set retention with explicit margin, and distinguish a compact tombstone from a full response payload.

A simple numerical sizing example: 250 new logical requests per second, 24-hour retention, and an average 500 bytes per idempotency record. The active record count is 250 × 86,400 = 21.6 million. Raw record storage is approximately 10.8 GB before indexes, replication, and database overhead. If the full prediction payload is 12 KB, storing it inline would require about 259.2 GB for the same window. Store large outputs separately and retain a compact pointer/digest in the idempotency table.

Do not silently recycle a key while a delayed retry can still arrive. Define behavior after expiry: reject with an explicit expired-key response, require a new logical operation ID, or retain a tombstone longer than the response. For high-impact decisions, the business operation ID may need much longer retention than the transport deduplication cache.

10. Online, asynchronous, batch, and streaming inference#

Online inference: reserve the key before dispatch, return the original response on retry, and keep the request deadline separate from the idempotency retention period. A caller may stop waiting while the logical operation remains RUNNING.

Asynchronous inference: use the idempotency key to ensure duplicate job submissions return the same job ID. Queue redelivery must reuse the operation identity. Worker completion and result publication should be conditional and idempotent.

Batch inference: define identity at the unit-of-work level—batch ID plus partition or record key and immutable input/model snapshot. A duplicate batch submission should return the existing run or resume safely, not create a second visible output set. This extends the general job-idempotency idea but the request contract and operation state remain explicit.

Streaming inference: use event IDs or producer sequence IDs for deduplication, preserve ordering separately, and define the deduplication horizon. Deduplication does not guarantee event order; stale or out-of-order messages need sequence/version checks. Stateful stream operators must make state updates and consumed offsets atomic within the supported processing boundary.

11. Failure scenarios and debugging#

  • Client retries after a lost response and GPU usage doubles: inspect whether the retry reused the same key and whether the first attempt reached dispatch.
  • Two replicas both run the same operation: replace check-then-act with a durable unique constraint and atomic reservation.
  • Same key returns a different prediction after model rollout: pin immutable model and feature identities when first accepted.
  • Same key is reused with changed input: compare canonical request digests and return a conflict.
  • Worker crashes after inference but before success commit: reconcile stable result artifacts and worker leases before retrying.
  • Duplicate queue delivery writes two prediction records: enforce a unique operation ID at the result store and make consumer commit idempotent.
  • Outbox event is published twice: use stable event IDs and idempotent downstream consumers.
  • Expired key is retried after cleanup: enforce the documented expiry contract and retain tombstones where delayed delivery remains possible.
  • One tenant guesses another tenant's key: scope keys by authenticated tenant/principal and authorize result retrieval independently of key possession.

12. Monitoring and operational controls#

Track:

  • New logical operations, transport attempts, and attempts per operation.
  • Idempotency hits, in-progress collisions, digest conflicts, and expired-key requests.
  • Duplicate attempts prevented before dispatch versus after dispatch.
  • GPU/CPU work avoided and stale outputs discarded.
  • Age and count of RUNNING reservations and expired leases.
  • Time from first reservation to terminal state.
  • Reconciliation outcomes and unresolved-operation age.
  • Outbox redelivery, consumer deduplication, and downstream duplicate-effect incidents.
  • Storage growth, record retention lag, and tombstone expiry.

Use low-cardinality metrics for tenant tier, endpoint, model family, and status. Keep raw keys and request IDs in access-controlled traces/logs, not metric labels. Alert on sudden duplicate spikes, conflicting payload reuse, stuck RUNNING records, rising lease recovery, and repeated downstream effects.

13. CI/CD and correctness tests#

Add integration and fault-injection tests that:

  • Send the same key concurrently to multiple replicas and assert one logical execution.
  • Retry after the server commits but before the response reaches the client.
  • Reuse a key with changed input and assert conflict.
  • Crash a worker after inference and before result-state commit.
  • Redeliver a queue message after consumer commit but before acknowledgement.
  • Roll the model alias between attempts and verify immutable version pinning.
  • Expire keys and test delayed retries at the retention boundary.
  • Verify tenant isolation and result authorization.
  • Duplicate outbox delivery and confirm one downstream business effect.
  • Race cancellation, completion, and retry while preserving one authoritative terminal state.

Test with a controllable inference worker and a real shared idempotency store. A unit test with an in-process dictionary cannot expose cross-replica races. Verify both caller-visible responses and actual model dispatch count.

14. Engineering trade-offs and common mistakes#

Durable deduplication adds a storage lookup and write to the request path; for low-latency endpoints, use a fast shared store and keep records compact, but never replace the correctness boundary with an unsafe local cache. Returning 202 avoids holding connections but requires a status API. Waiting for the first request gives a simpler client response but consumes concurrency and must obey the original deadline. Longer retention protects against delayed retries but increases storage and privacy obligations.

Common mistakes:

  • Generating a new key for every retry.
  • Treating identical payloads as necessarily the same business operation.
  • Using an in-memory cache or check-then-insert as the only concurrency control.
  • Returning an old result when the same key is reused with different input.
  • Allowing a mutable model alias to change the meaning of a retry.
  • Holding a database transaction open while GPU inference runs.
  • Assuming broker deduplication guarantees one consumer-side effect.
  • Claiming exactly-once behavior across systems without a shared transaction or downstream idempotency contract.
  • Deleting keys before the maximum retry/redelivery horizon.
  • Logging sensitive raw keys or using them as high-cardinality metric labels.

15. Production readiness checklist#

  • A stable logical operation key survives every retry and redelivery.
  • Keys are scoped by authenticated tenant and operation.
  • Canonical request digest detects conflicting key reuse.
  • A durable uniqueness constraint arbitrates concurrent arrivals.
  • In-progress duplicates receive a bounded status/wait response, never duplicate dispatch.
  • Immutable model and feature identities are pinned for the operation.
  • Result persistence and business effects have explicit transaction/outbox boundaries.
  • Worker crashes and uncertain outcomes have reconciliation paths.
  • Retention covers retry and redelivery windows with a documented expiry policy.
  • Metrics distinguish logical operations from transport attempts and actual model executions.
  • Multi-replica concurrency, lost acknowledgements, worker crashes, queue redelivery, and expiry races are tested in CI/CD.

The key principle: one logical inference operation can have many transport attempts, but retries should converge on one authoritative outcome and should not multiply business effects. Exactly-once delivery is not a universal network guarantee; build idempotent effects at each durable boundary and be precise about where the guarantee ends.

References

  1. 1.
  2. 2.
  3. 3.
    Idempotent Consumer patternMicrosoft Azure Architecture Center
  4. 4.
  5. 5.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningRetrieval-Augmented GenerationAI Agents