Skip to content

Shared state and message passing; Kafka/Redis Streams, ownership and cycle limits

15 min reading

Compare shared state and message passing using Kafka and Redis Streams as concrete transports.

Page details

GenAI · Lesson 27 of 45 · 4 / 4.2

Sources · 15 min reading · 31 min with practice

Published · Last edited:

More
20px

Progress is saved in this browser when storage is available.

View guided paths and progress

Know first: Manager-worker, sequential, peer and consensus patterns; compare with one agent. Optional help: GenAI foundations.

Optional background references

Hypothetical scenario. Northwind splits a task among workers. An approval is delayed, a worker restarts and a completion event arrives after cancellation. Maya needs to know which result still counts; Dev points to a consumed message, and Priya asks for the authoritative task state.

Maya: “The event arrived, but was that worker still allowed to finish this task?”

Dev: “The stream records delivery and consumer progress.”

Priya: “Check ownership and version at the transition where the result would be accepted.”

You will compare shared-state claims with message passing using Kafka and Redis Streams, tracing identity, ownership, cancellation and cycle limits. Delivery progress and accepted external effects require different evidence.

Who owns the task when an event arrives late?

Kafka's design documentation describes partitioned logs and consumer progress. Redis Streams supplies an append-oriented stream with consumer-group processing and pending-entry tracking. Both can carry orchestration events; neither makes a model's proposed action authorized or an external side effect exactly once merely because an event was acknowledged.

Shared memory requires an atomic claim or version check on the task record. Message passing needs a durable operation identity plus an owner transition when work is dispatched, completed or cancelled. In either design, bound delegation depth and reject cycles such as A delegating to B, then B delegating the same unresolved task back to A.

Hypothetical scenario. A run may have at most four delegated tasks and two attempts per task, so its attempt ceiling is 4 × 2 = 8 before considering separately budgeted coordination calls. A duplicate delivery consumes no new logical task identity, but an actual repeated execution still consumes work. Reconcile the application ledger against delivery acknowledgments rather than equating the two.

The completion arrives after cancellation

Northwind submits a document-maintenance task and receives a task identifier. Priya cancels it while a remote worker is processing the request. A completion event arrives afterward. The interface now has two apparently contradictory messages. The correct outcome depends on when the effect occurred and which state transition the application accepted, not on which message was displayed last.

Distinguish the logical task from its attempts and messages. One task can have several worker attempts, and each attempt can produce more than one event. A cancellation is a request about future or ongoing work. A completion is an observation about an effect. Their relationship needs a declared contract rather than a last-message-wins rule.

Keep event receipt separate from current task authority

Hypothetical scenario. Worker generation 7 publishes a completion after cancellation and replacement generation 8. A broker can deliver that event correctly while the workflow must reject its stale transition. Include task, operation and generation identities in every message.

Keep event receipt separate from current task authority
ArtifactConcrete evidenceDecision boundary
Eventtask, operation, generation, schemaInterpretation
Transport progresspartition/stream position, groupDelivery observation
Workflow transitionexpected version and current ownerAuthority
Deliver even if delayed: Broker event → Workflow authority.Deliver even if delayed: Broker event → Workflow authority. Broker event to Workflow authority: deliver even if delayed; Workflow authority to Current task state: conditional generation check.Broker eventWorkflow authorityCurrent task statedeliver even if delayedconditional generation check
Deliver even if delayed: Broker event → Workflow authority. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

Kafka groups or Redis Streams consumers track transport progress under their contracts; acknowledgement does not prove the application accepted the result. A transaction or guarded workflow update decides whether the event advances current state. Preserve stable business identity across redelivery, bound coordination cycles and retain accepted obligations when a consumer rebalances. An old consumer may still have an in-flight remote effect after losing its partition.

Why receipt cannot stand in for completion

A broker can confirm that it accepted a message. A worker can acknowledge that it processed a delivery. An authoritative service can confirm that a document changed. These observations concern different boundaries. Treating the first acknowledgment as final task success makes a fast response look useful while hiding work that has not happened.

Use states whose names reflect what is known: accepted, scheduled, running, effect unresolved, completed, cancellation requested and cancelled before effect. The exact vocabulary is an application choice. What matters is that each transition has an observable condition and that no state implies more than its evidence supports.

Messages can observe or change workflow state

Temporal's workflow message-passing documentation distinguishes Signals, Queries and Updates as different interaction mechanisms. That distinction provides a concrete vocabulary for asynchronous input, state inspection and interactions with responses. Choose a mechanism from the intended contract rather than assuming every message means the same kind of completion.

For Northwind, an accepted cancellation request can enter the workflow while a separate query reports the current task state. A result record should say whether cancellation prevented the effect, arrived after it or remains unresolved. The caller should not have to infer those outcomes from transport timing.

Keep message validation and effect validation separate. An event can have a valid schema and still refer to the wrong task revision. An event can have the correct task identity but arrive after the task has moved to a state where the event is no longer applicable. Persist the rejection or reconciliation reason in an inspectable form.

Draw the observations on separate timelines

Follow the decision boundaries

Asynchronous Agents: Events, Cancellation and Uncertain CompletionCaller, workflow and external effect have separate timelines. Connections represent submissions and observations rather than synchronized clocks.CallerWorkflowExternal effect

The caller, workflow and external service have different observations. A horizontal placement in this illustrative diagram explains the selected sequence; it is not a claim about synchronized clocks. Use durable identities and authoritative state transitions to connect observations rather than relying only on wall-clock ordering.

Count logical effects instead of delivery volume

Hypothetical scenario. Ten logical document tasks each produce an accepted event and a completion event. That is 10 × 2 = 20 unique event identities. Suppose the delivery system repeats six deliveries of those existing identities. The receiver observes 20 + 6 = 26 deliveries while the logical event set still contains 20 entries.

If a dashboard counts every completion delivery as a new successful task, duplicates can inflate its result. Deduplicate according to the application's event identity and record the accepted task transition with its effect. A separate delivery metric can still report 26 deliveries because that is useful operational work. It should not be labeled 26 completed tasks.

Now suppose three tasks receive a cancellation request, and two of those requests arrive after their effects are authoritatively confirmed. Under a selected policy that only prevents future effects, those two tasks remain completed with a late-cancellation observation. The third can become cancelled-before-effect only after the workflow establishes that no effect was accepted and prevents a stale worker from creating one later.

The third case cannot be settled by subtracting a cancellation message from a completion count. It requires an enforceable transition, such as an authoritative task generation that the effect service validates. A count is a summary of accepted states; it is not the mechanism that makes the states true.

Reject stale work at the boundary that matters

Assign the logical task an identity and identify the revision or generation to which an attempt belongs. When an approved proposal changes, a late result from the old generation should not become the accepted result for the new one. Preserve it as history or send it to reconciliation according to the operation's actual consequences.

A generation field is useful only where it is enforced. If an external document service ignores it, a stale worker may still perform a write even after the local workflow rejects its completion event. The effect boundary needs a supported conditional write, permission mechanism or operation identity that matches the application's cancellation and revision contract.

For repeated deliveries, record the transition and deduplication evidence together where the chosen storage system supports the required atomicity. Marking an event as seen before applying its effect can lose work after a crash. Applying an effect before recording identity can repeat it. The correct pattern depends on whether the effect shares a transaction with the record or needs remote reconciliation.

In the wild: messaging has several interaction contracts

Temporal's published message-passing guide describes actual workflow communication mechanisms rather than one generic fire-and-forget operation. It is relevant because an application often needs both asynchronous input and a way to inspect or receive a decision. The reference is not a universal guarantee that Northwind's external document writes are exactly once.

The task and cancellation sequence is hypothetical. Its operational lesson is to name what a returned response confirms. A successful message submission can be useful even when work is incomplete, provided the interface exposes the task's subsequent observable states honestly.

Derive backlog drain under stated assumptions

For a separate toy workload, suppose a queue contains 120 ready tasks. New tasks arrive at six per minute, while the selected worker pool completes ten per minute under stable conditions. Net drain is 10 − 6 = 4 tasks per minute. Clearing the initial backlog takes 120 / 4 = 30 minutes if both rates remain constant and no task is blocked elsewhere.

Increasing the number of workers helps only if another dependency permits the extra throughput. A document service may enforce its own limit. Tasks awaiting human review may not be ready work at all. Separate ready, waiting, unresolved and terminal counts before using a queue-length estimate to make a capacity decision.

Cancellation can reduce ready work, but removing a task from the visible queue does not cancel a worker that already claimed it. Keep ownership, lease or generation rules explicit. A useful operations view should show the distinction so an empty queue is not mistaken for a system with no outstanding effects.

Use asynchronous execution for a real waiting boundary

Asynchrony is useful when a task outlives a single request, waits for external input or needs independent scheduling. A short read can be simpler as a direct request with a clear deadline. Moving it to a queue adds state and delivery semantics that may not improve the user contract.

Where asynchronous execution is justified, return a stable task identifier and an understandable status contract. Make retries refer to the same logical operation where appropriate. Provide a supported way to inspect uncertainty rather than encouraging users to resubmit a new task whenever a response is slow.

Messages that say less than they appear to

An acknowledgment proves the business effect. It proves the boundary described by that acknowledgment. Identify which component issued it and what it observed.

The newest timestamp wins. Clock order alone does not establish applicability, authority or the current task generation.

Cancellation erases history. It changes permitted future transitions according to a policy. Already accepted effects can require a separately authorized corrective operation.

Expose uncertainty without inviting duplicate submissions

A task-status interface should tell the caller what the system knows and what it is still determining. An unresolved effect can have a stable identity and a reconciliation status. That is more useful than a generic failure that encourages the user to create a second task for the same requested change.

For Northwind, a delayed publication response can say that the original request is being checked. A retry button should reference that operation where the contract supports it. Starting a completely new logical action should be an explicit decision because it changes deduplication and authority assumptions.

Retain rejected late events for the operational purpose they serve, under the appropriate access and retention policy. A stale event can explain why a worker appears active after cancellation. It should not be silently promoted into the current task state, nor should its presence be mistaken for a second completed task.

Consider notification delivery separately from task completion. A task can complete successfully while its user notification fails. Retrying the notification should not rerun the document write. Distinct effect identities let the workflow recover one boundary without repeating another.

This separation also makes support easier. Priya can look up the document operation, the cancellation decision and the notification attempt as related records with different outcomes. A single ambiguous status string would force her to reconstruct those facts from message arrival order.

What must be checked in the implementation

Delivery guarantees, deduplication scope, transaction support and cancellation behavior depend on the broker, workflow runtime and external service. The example event counts and drain rates are selected and assume stable conditions. A durable workflow history does not create atomicity across unrelated systems. Verify where stale attempts are rejected and how uncertain remote effects are reconciled before promising a terminal outcome.

Test the event boundary

The event is acknowledged but its generation was rejected. Is the task complete?

Reveal the design reasoning

No. The acknowledgement closes transport handling only. Current state still needs its accepted completion or recovery obligation. Report rejected stale events separately from useful work.

Decision: Guard event-driven state changes at the workflow owner, not at broker receipt.

Resolve the event sequence

Why are 26 deliveries not 26 logical events in the example?

Twenty event identities were created, and six deliveries repeat existing identities. Track unique logical events separately from transport work. Completion metrics should follow accepted task transitions, while delivery counts can still describe operational load.

A stale worker's completion is rejected locally. Has the system prevented its remote write?

Only if the effect boundary enforces the corresponding version, generation or authority rule. Rejecting a completion event after a remote write does not undo that write. Inspect the external service contract and reconcile any already accepted effect.

Why does the backlog take 30 minutes rather than 12 minutes to clear?

New work keeps arriving. The net drain is ten completions minus six arrivals, or four tasks per minute. Dividing 120 by four gives 30 minutes under the stated stable-rate assumptions; dividing by ten would ignore incoming work.

Northwind decision log

  1. Keep logical task, attempt and event identities distinct.
  2. Reject stale work where the effect is accepted, not only in the event handler.
  3. Expose cancellation and unresolved completion without inviting duplicate submissions.

Go deeper: supporting mechanisms

Related: Agentic systems · Retries and tool outcomes.

Check the mechanism in this lesson

Does a Redis Streams acknowledgment prove that the external operation happened exactly once?

Compare the explanation

No. Transport acknowledgment records consumer progress, while the external effect has its own operation identity and outcome. Reconcile duplicates and uncertain effects in the application ledger.

Carry the decision forward

Northwind can reject stale work despite successful delivery. Page 28 binds human approval to an exact proposed action and version, so a resumed task cannot reinterpret a reviewer’s decision.