---
title: "Idle Timer with Resolution"
description: "Record every incoming message, and end when someone resolves the conversation or when no message arrives for a while (formerly Inbound Event Loop)."
canonical_url: "https://docs.superdurable.io/design-patterns/external-interaction/idle-timer-with-resolution/"
source: "docs/content/design-patterns/external-interaction/idle-timer-with-resolution.mdx"
locale: "en"
language: "python"
---

> Index of every page for AI agents: https://docs.superdurable.io/llms.txt

# Idle Timer with Resolution

Code on this page is in Python. Other languages: [Go](https://docs.superdurable.io/design-patterns/external-interaction/idle-timer-with-resolution.go.md) · [Java](https://docs.superdurable.io/design-patterns/external-interaction/idle-timer-with-resolution.java.md) · [TypeScript](https://docs.superdurable.io/design-patterns/external-interaction/idle-timer-with-resolution.typescript.md) · [Rust](https://docs.superdurable.io/design-patterns/external-interaction/idle-timer-with-resolution.rust.md)

Record every incoming message, and end when someone resolves the conversation or when no message arrives for a while (formerly Inbound Event Loop).

Use this pattern when a Flow takes inbound messages until a resolution arrives or the conversation goes quiet. Examples are replies in a support ticket, messages in a chat session, or answers in a review thread. It extends the [Idle Timer](https://docs.superdurable.io/design-patterns/external-interaction/idle-timer.md): each message restarts the inactivity Timer, and a separate resolution message ends the loop.

**Flow graph: SupportTicketConversationFlow**

**Steps**

1. `AwaitTicketMessage` (start Step): Record each batch of replies, or route on the resolution or the inactivity Timer. Next: `CloseResolvedTicket`, `AwaitTicketMessage` again, or `CloseInactiveTicket`. Reads `transcriptChunks`, `ticketReplies`, `ticketResolutions`; writes `transcriptChunks`.
2. `CloseInactiveTicket`: Close the quiet ticket once no reply or resolution is waiting. Next: `AwaitTicketMessage`.
3. `CloseResolvedTicket`: Close the resolved ticket once no reply is left to record. Next: `AwaitTicketMessage`.

**RPCs**

- `resolve_ticket`: Publishes to `ticketResolutions`.
- `send_ticket_reply`: Publishes to `ticketReplies`.

Example: [examples/python/dex_examples/patterns/inbound-event-loop/support_ticket_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/inbound-event-loop/support_ticket_flow.py)

## How it works

1. An RPC validates each reply and publishes it to a reply Channel. Another RPC validates the resolution and publishes it to a resolution Channel.
2. One waiting Step returns `AnyOf` over the reply Channel, the resolution Channel, and the inactivity Timer.
3. When replies win, its `Execute` appends them to the transcript and moves back to the same Step. The new execution registers a new wait, so the inactivity Timer restarts.
4. When the resolution wins, `Execute` moves to the Step that closes the resolved ticket. When the Timer wins, it moves to the Step that closes the quiet ticket.
5. Each closing Step completes the Flow with `ForceCompleteIfChannelsEmpty`. The close decision checks the Channels the Step names and accepts the close in one atomic commit. When a message committed before that check is still in a checked Channel, Dex moves back to the waiting Step instead of closing.

## Rules

- The RPC only validates its input and publishes it to a Channel. It writes no Attribute that the waiting Step reads or locks.
- One waiting Step waits on `AnyOf` over the reply Channel, the resolution Channel, and the inactivity Timer.
- Declare the reply Channel before the resolution Channel. When several Channel Conditions are ready at once, the first one declared wins, and only the winner's messages are consumed. Replies accepted before the resolution are therefore recorded first.
- A Channel Condition consumes messages only when it wins. A reply that arrives while `Execute` runs stays queued for the next execution, so no reply is lost.
- `Execute` appends the consumed messages to an Attribute, such as a transcript. The waiting Step is the only writer of that Attribute.
- `Execute` then moves back to the same Step. The new execution registers a new wait, so the inactivity Timer restarts after each message.
- To take every queued reply at once, use an at-least-one Channel Condition. You can also take one reply per execution.
- Keep the transcript bounded. A long conversation stores its messages in a [sequentially chunked AttributeMap](https://docs.superdurable.io/design-patterns/data-storage/sequentially-chunked-attribute-map.md). The example's waiting Step loads only the current chunk.

<a id="why-the-rpc-does-not-write-the-transcript"></a>

## Why the Step owns the transcript

If the RPC appended to the transcript, the waiting Step would have to lock the transcript, and the RPC would have to lock it too for its read-modify-write. Locks do not queue. Every RPC that arrives while the Step holds the lock, or while another RPC holds it, is rejected with a lock conflict, and the client must retry. Publishing to a Channel needs no lock, so concurrent replies never conflict.

## Messages at the close

Every closing Step completes with `ForceCompleteIfChannelsEmpty` on the reply Channel, as in [Drain External Channels](https://docs.superdurable.io/design-patterns/draining-channel-for-external-publishing.md). Its fallback moves back to the waiting Step.

- The resolution closes only when the reply Channel is empty at the atomic check. A reply committed before that check, still queued or taken by a Step that has not finished, triggers the fallback, which carries the resolution back to the waiting Step. That Step waits only for replies, writes them to the transcript, and moves to the resolution close again.
- The inactivity close also checks the resolution Channel. A reply or a resolution can commit after the Timer won, before the inactivity close runs. Its check finds the message, and the fallback reopens the wait. A reply is then written to the transcript, and a resolution moves to the resolution close.
- Keep the waiting Step the only consumer of the reply Channel.

The resolution RPC rejects an empty reason, because an empty pending resolution means "none".

An RPC that publishes after the check, while the close is pending, fails with `FLOW_CLOSING` and commits nothing; see [Pending close](https://docs.superdurable.io/reference/server/runtime-client.md#pending-close). A request that arrives while the Flow closes follows [Requests during Flow close](https://docs.superdurable.io/reference/server/runtime-client.md#requests-during-flow-close).

A successful RPC confirms that the message was published. Confirming that it was handled is a separate step. When the caller must confirm each reply was handled, the waiting Step records the reply's business ID in the same commit, and the caller reads that record. To retry the same delivery, reuse its RPC request ID. Before a new delivery of a reply, check that record for its business ID. See [Confirm that a message was handled](https://docs.superdurable.io/reference/server/runtime-client.md#confirm-message-handled).

## Example

`SupportTicketConversationFlow` takes replies to a support ticket. `sendTicketReply` rejects empty and overlong replies. `resolveTicket` rejects an empty reason. `AwaitTicketMessage` records replies, or moves to `CloseResolvedTicket` or `CloseInactiveTicket`. Its input is the pending resolution, which is empty until a resolution close falls back. The inactivity Timer is 24 hours. The tests skip it with the Client `SkipTimer` instead of shortening it.

**Python**

```python
TICKET_REPLIES = Channel("ticketReplies", str)
TICKET_RESOLUTIONS = Channel("ticketResolutions", str)
TRANSCRIPT_CHUNKS = AttributeMap("transcriptChunks", TranscriptChunk)


class AwaitTicketMessage(Step[str]):
    """Waits for replies, a resolution, or inactivity; the input is a pending resolution."""

    def wait_for(self, context: Context, pending_resolution: str) -> Wait:
        if pending_resolution:
            return Wait.until(TICKET_REPLIES.at_least(1))
        # Replies come before the resolution, so earlier replies are recorded first.
        return Wait.any_of(
            TICKET_REPLIES.at_least(1),
            TICKET_RESOLUTIONS.for_one(),
            Timer.by_duration(INACTIVITY_TIMEOUT),
        )

    def execute(self, context: Context, pending_resolution: str) -> StepDecision:
        replies = TICKET_REPLIES.results(context)
        if replies:
            # Appends replies to the current chunk and archives each full chunk.
            chunk = TRANSCRIPT_CHUNKS.get(context, CURRENT_TRANSCRIPT_CHUNK) or TranscriptChunk()
            next_sequence = chunk.replies[-1].sequence + 1 if chunk.replies else 1
            for text in replies:
                if len(chunk.replies) == TRANSCRIPT_CHUNK_SIZE:
                    archive_token = archive_chunk_token(chunk.replies[0].sequence)
                    TRANSCRIPT_CHUNKS.set(context, archive_token, chunk)
                    chunk = TranscriptChunk()
                chunk.replies.append(TicketReply(next_sequence, text))
                next_sequence += 1
            TRANSCRIPT_CHUNKS.set(context, CURRENT_TRANSCRIPT_CHUNK, chunk)
            if pending_resolution:
                return go_to(CloseResolvedTicket, pending_resolution)
            # A new execution registers a new wait, so the Timer restarts.
            return go_to(AwaitTicketMessage, "")
        resolutions = TICKET_RESOLUTIONS.results(context)
        if resolutions:
            return go_to(CloseResolvedTicket, resolutions[0])
        if context.has_timer_fired():
            return go_to(CloseInactiveTicket, None)
        raise RuntimeError("no Condition of the ticket wait completed")

    def get_step_options(self) -> StepOptions:
        return StepOptions(
            execute_load_attribute_map_instances=(
                TRANSCRIPT_CHUNKS.load(CURRENT_TRANSCRIPT_CHUNK),
            )
        )


class CloseResolvedTicket(Step[str]):
    def execute(self, context: Context, reason: str) -> StepDecision:
        return force_complete_if_channels_empty(
            f"resolved: {reason}",
            StepMovement.of(AwaitTicketMessage, reason),
            TICKET_REPLIES,
        )


class CloseInactiveTicket(Step[None]):
    def execute(self, context: Context, input: None) -> StepDecision:
        return force_complete_if_channels_empty(
            "closed after inactivity",
            StepMovement.of(AwaitTicketMessage, ""),
            TICKET_REPLIES,
            TICKET_RESOLUTIONS,
        )


class SupportTicketConversationFlow(Flow[str]):
    @rpc
    def send_ticket_reply(self, context: Context, text: str) -> None:
        """Validates one reply and queues it for the waiting Step."""
        if not text.strip():
            raise ValueError("reply text is required")
        if len(text) > MAX_REPLY_LENGTH:
            raise ValueError(f"reply text exceeds {MAX_REPLY_LENGTH} characters")
        TICKET_REPLIES.publish(context, text)

    @rpc
    def resolve_ticket(self, context: Context, reason: str) -> None:
        """Queues the resolution; an empty reason would mean no resolution."""
        if not reason.strip():
            raise ValueError("resolution reason is required")
        TICKET_RESOLUTIONS.publish(context, reason)
```

Example: [examples/python/dex_examples/patterns/inbound-event-loop/support_ticket_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/inbound-event-loop/support_ticket_flow.py)

The transcript update, the HTTP controller, and the tests are in the example folders. Run the HTTP sample from the [examples playground](https://github.com/superdurable/dex/tree/main/examples/playground).

## Next

- [Control Long-Running Work](https://docs.superdurable.io/design-patterns/external-interaction/control-long-running-work.md)
- [Channel](https://docs.superdurable.io/concepts/primitives/channel.md)
- [Timer](https://docs.superdurable.io/concepts/primitives/timer.md)
- [RPC](https://docs.superdurable.io/concepts/primitives/rpc.md)
- [Drain Channels](https://docs.superdurable.io/design-patterns/drain-channels.md)
