Tutorials Logic, IN info@tutorialslogic.com

Claude Streaming and Batches: Two Delivery Paths, One Reliable State Model

Choose delivery based on the customer’s clock

Streaming improves perceived responsiveness by delivering response events as Claude generates them. It does not make every workflow faster, and it adds UI and cancellation responsibilities. Design the interface to show partial text as provisional until a completed message and stop reason arrive.

Message Batches are suited to large asynchronous workloads. They use a different operational model from interactive requests: submit validated jobs, track status, process results idempotently, and plan for partial failures. Do not use an interactive request loop to process thousands of independent records.

The delivery decision: Use streaming when a person is waiting for a response. Use batches when work can wait and you need throughput or a large evaluation run. Neither path removes the need to track completion and errors. Choose interaction mode from user need: streaming for a live conversation, batches for independent asynchronous work.

Streaming and batches solve different problems

Need Use State you must keep
A customer is waiting Streaming Partial text, completion, cancellation, and a recoverable error.
A nightly backlog can wait Message Batches Request ID, item ID, processing status, result matching, and retry policy.
You are uncertain A normal request first A baseline for latency, response quality, and failure behavior.

Make partial text visibly partial

Streaming delivers a sequence of events rather than one final object. Buffer text by content block, render it safely, and handle the final event that establishes stop reason and usage. A network disconnect can leave the UI with partial text that must not be silently stored as a complete answer.

Stream over a server endpoint so your backend retains authentication, policy, model selection, and rate limiting.

  • Render incrementally but finalize explicitly.
  • Keep policy and keys server-side.
  • Track stop reason.

Finish a stream before you store the answer

A streaming UI should show that output is in progress and provide cancellation. Keep partial text in memory or a temporary record. Mark it complete only when the request finishes successfully; otherwise label it interrupted and offer retry or continue behavior.

Avoid triggering actions from partial model text. A stream is presentation, not a permission grant.

  • Mark interrupted output clearly.
  • Allow user cancellation.
  • Never execute side effects from partial text.

Model an asynchronous job as a state machine

Batches are a throughput pattern. Create independent, validated items with stable IDs, submit them, inspect asynchronous results, and write each outcome exactly once. Store item status so a worker restart does not duplicate billing, emails, or database changes.

Batch pricing, retention, and availability are product details that should be verified against current official documentation before launch.

  • Use stable item IDs.
  • Persist item state.
  • Process results idempotently.

Match batch results by your own identifiers

Cancellation is an application concern. Stop forwarding a stream when the user disconnects, abort downstream work where supported, and record final status. For batch consumers, use idempotency keys and state transitions to make retries safe.

Measure queue age, completion rate, failed item rate, and cost per completed artifact.

  • Abort responsibly.
  • Use idempotency keys.
  • Observe latency, error rate, and cost.

Keep delivery state in your application

A streamed response needs a small state machine. The UI can append text while the message is active, but only a completed event should mark the answer ready for storage or reuse.

The same discipline applies to batches. A worker should know whether an item is queued, running, completed, or retryable before it acts on the result.

  • Persist completion separately from text.
  • Give cancellation an explicit state.
  • Use durable item IDs for asynchronous work.

Build delivery state that survives a real interruption

Keep Partial and Complete Output Separate

A simple state object prevents the UI or persistence layer from treating an interrupted stream as final.

Keep Partial and Complete Output Separate
state = {"text": "", "complete": False}

def on_text_delta(delta: str) -> None:
    state["text"] += delta

def on_message_complete() -> None:
    state["complete"] = True

on_text_delta("Hello")
on_text_delta(" world")
on_message_complete()
print(state)
Output
{'text': 'Hello world', 'complete': True}
  • On disconnect, do not call on_message_complete.

Idempotent Batch Result Consumer

A completed item is recorded once even if a worker receives the result twice.

Idempotent Batch Result Consumer
processed_ids: set[str] = set()

def consume_result(item_id: str, result: str) -> str:
    if item_id in processed_ids:
        return "already_processed"
    processed_ids.add(item_id)
    return f"saved:{result}"

print(consume_result("job-1", "ok"))
print(consume_result("job-1", "ok"))
Output
saved:ok
already_processed
  • Use durable storage, not an in-memory set, in production.

Mark an Interrupted Stream Clearly

The state shown to the user should say that the partial reply did not finish.

Mark an Interrupted Stream Clearly
def interrupted_state(text: str) -> dict:
    return {"text": text, "complete": False, "status": "interrupted"}

print(interrupted_state("Partial answer")["status"])
Output
interrupted
  • Do not quietly promote this text to a completed assistant response.

Allow Only a Valid Batch Transition

A small transition guard prevents a retry worker from overwriting an already completed item.

Allow Only a Valid Batch Transition
ALLOWED = {"queued": {"running"}, "running": {"succeeded", "retryable"}}

def may_transition(current: str, target: str) -> bool:
    return target in ALLOWED.get(current, set())

print(may_transition("running", "succeeded"))
Output
True
  • Store this transition in durable storage when multiple workers are involved.
Before you make a slow answer look fast

Response-delivery review

4 checks
  • I choose streaming for a user-visible reason.
  • I never save partial output as complete by accident.
  • I design batch consumers to be idempotent.
  • I can cancel safely and measure backlog.

Delivery bugs that are easy to miss in a demo

  • Streaming everything because it looks responsive.
  • Persisting incomplete text as a final answer.
  • Using batches without item IDs or replay-safe consumers.

A product and operations exercise

Choose a delivery path for two real workloads

0 of 2 completed

Streaming and batch-processing questions

No. It changes delivery timing; control output with your prompt and max_tokens.

Only after the same validation, authorization, and idempotency checks used by interactive workflows.

Next Step
Next Practice

Finish the concept here, then reinforce it with hands-on coding, interview prep, or a tool that matches the topic.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.