Runs, Events & Streams

This page is the detailed reference for run and event records plus stream lineage and live delivery. Start with the Platform Execution Model for the complete relationship among events, handlers, runs, tasks, retries, workers, and streams.

Runs

A Run is one platform-invoked, top-level Hot function execution attempt, such as an API call, selected event handler, schedule, or task execution. Ordinary function calls inside it remain part of the same run's execution trace.

Run Lifecycle

running succeeded failed cancelled retry left? pending_retry retries as a new run (linked via origin_run_id)
StateDescription
runningWorker is executing the function
succeededFunction completed successfully
failedFunction returned an unhandled Err, called fail(), or timed out
cancelledRun was cancelled before completion
pending_retryFunction failed but will be retried automatically

Runs with "retry" metadata that fail are temporarily set to pending_retry until the retry executes. See Retries for details.

Run Timeouts

Each run has a timeout: the timeout metadata of the function it starts with, in seconds, or else the worker's worker.run-timeout. The worker caps a function's own timeout at worker.max-run-timeout.

draft-policy
meta {on-event: "drafting:requested", timeout: 1800}
fn (event) {
  run-drafting-loop(event.data)
}
SettingEnvironment variableDefaultMeaning
worker.run-timeoutHOT_WORKER_RUN_TIMEOUT300Timeout of a run whose function sets none
worker.max-run-timeoutHOT_WORKER_MAX_RUN_TIMEOUT3600Cap on a function's own timeout; at most 86400
worker.cancel-on-timeoutHOT_WORKER_CANCEL_ON_TIMEOUTtrueAsk a timed-out run to stop before freeing its slot

The clock starts when the worker hands the run to a VM thread, so loading the program counts against it, and until the program has loaded the run has the default timeout. Waits inside the run, such as ::hot::task/await, are capped to the time it has left minus 5 seconds, which the run keeps to record its result. A run with a timeout of 5 seconds or less therefore can't await a task, and an await in a longer run waits at most its timeout minus 5 seconds minus the time already spent.

When a run reaches its timeout, the worker asks it to stop and frees the executor slot once it has unwound, or after 5 more seconds if it hasn't. Either way the run is recorded as failed with Run timed out after N seconds. When the cap lowered the function's own timeout, the message says so: Run timed out after 3600 seconds (its timeout of 7200 seconds is capped by worker.max-run-timeout). A timed-out run is retried under its retry policy, like any other failure. For work longer than an hour, start a task instead.

A run longer than worker.run-timeout outlasts the window after which another worker takes over an event whose worker stopped responding (queue.event-orphan-idle-ms, raised as needed to cover worker.run-timeout plus handler setup). While the run executes, its worker keeps refreshing its claim on the event, so the event stays with it. If the worker can't refresh the claim for two thirds of that window, it stops the run the same way and records Run stopped: its worker could not refresh its claim on the event for N seconds, before any other worker could take the event over. Its retry policy applies as for any failure, and a later redelivery of the event finds the run finished and doesn't run it again. If the worker finds the claim already gone, it stops the run and leaves its record to the worker that took the event over. Either way, a run doesn't keep running alongside a redelivery of its event, unless it is stuck in work it can't be cancelled out of, as with timeouts. This guard applies to the Redis queue; the SQLite queue renews its leases but doesn't stop a run whose lease lapses.

Run Data

The API returns a run as:

{
  "run_id": "019a2f6e-7c1a-7b3e-9d6a-2f4c8e1b5a70",
  "env_id": "019a2f00-1111-7000-8000-00000000000a",
  "stream_id": "019a2f6e-7b90-7c11-8a55-6d0e9f3c2b18",
  "build_id": "019a2e10-4d2c-7f00-b1c3-5a9e7d2f4c66",
  "run_type": "event",
  "status": "succeeded",
  "start_time": "2026-11-04T10:30:00Z",
  "stop_time": "2026-11-04T10:30:02Z",
  "origin_run_id": null,
  "event_id": "019a2f6e-7b8f-7d42-a0e1-3c5b7f9d1e24",
  "result": {
    "status": "processed",
    "total": 99.99
  },
  "project_id": "019a2e00-2222-7000-8000-00000000000b",
  "project_name": "orders",
  "retry_attempt": 0
}

build_id, stop_time, origin_run_id and event_id are null when they don't apply: a running run has no stop_time, and origin_run_id is set on a retry. result, project_id, project_name and next_retry_at are left out when they have no value. next_retry_at appears while a run is pending_retry. The record doesn't name the function or its arguments. The run's event carries the input, and the execution trace shows the calls.

Execution Trace

Hot captures a full execution trace for every run, showing:

  • Each expression evaluated
  • Intermediate values
  • Function calls and returns
  • Timing for each step
  • Any errors with stack traces

A run records its first 10,000 function calls. A run that makes more keeps running but records no further calls; its info then shows call_tracing: "truncated", and once it ends, how many calls went unrecorded (untraced_calls). Set hot.emitter.max-calls-per-run in the worker's configuration to change the limit (0 records every call).

Triggering Runs

Runs can be triggered in several ways:

1. API Call (via hot:call event)

curl -X POST https://api.hot.dev/v1/events \
  -H "Authorization: Bearer $HOT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"event_type": "hot:call", "event_data": {"fn": "::myapp::orders/process-order", "args": [{"order_id": "12345"}]}}'

2. Event Handler

on-order-created
meta {on-event: "order:created"}
fn (event) {
  process-order(event.data.order_id)
}

3. Schedule (recurring)

daily-report
meta {schedule: "0 0 * * *"}
fn (event) {
  generate-report()
}

4. Dynamic Schedule (one-time or created at runtime)

// Schedule a function to run in 10 minutes
send("hot:schedule:new", {
  fn: "::myapp::tasks/process",
  args: [{task_id: "123"}],
  schedule: "in 10 minutes"
})

See Dynamic Schedules for more details.

5. Asynchronous Function Dispatch (from another run)

process-batch fn (orders) {
  // Each send publishes an event that dispatches a separate run
  map(orders, (order) {
    send("hot:call", {
      fn: "::myapp::orders/process-order",
      args: [order]
    })
  })
}

Events

Events are messages that trigger asynchronous workflows. They decouple event producers from consumers, enabling scalable and maintainable systems.

Event Structure

An Event in Hot has two fields:

Event type {
  type: Str,
  data: Any
}

A handler receives exactly this as its event argument. The type lives in ::hot::event and isn't a core name, so write ::hot::event/Event or alias it.

The send function has three arities:

// Pass event type and data directly
send("user:created", {id: "usr_12345", email: "alice@example.com"})

// Pass only the event type. The data is an empty map.
send("cache:refresh")

// Or pass an Event
send(::hot::event/Event({type: "user:created", data: {id: "usr_12345", email: "alice@example.com"}}))

Each returns an EventInfo for the published event:

info send("user:created", {id: "usr_12345"})
info.event.id     // UUID of the published event
info.event.type   // "user:created"
info.event.time   // Instant the event was published
info.stream.id    // UUID of the stream, the same as the sending run's
info.env.id       // UUID of the environment

send returns an Err if the event couldn't be stored, in which case no handler runs. Event data of any size can be sent as long as it fits blob.rehydrate.max-total-bytes, 512 MB as JSON by default: data over 1 MB as JSON goes to blob storage. Without blob storage, PostgreSQL refuses a jsonb value over 256 MB.

Sending Events

From Hot Code:

// Send an event after user creation
create-user fn (data) {
  user insert-user(data)

  // Send event for other handlers (send is a core function)
  send("user:created", {
    id: user.id,
    email: user.email,
    name: user.name
  })

  user
}

From the API:

curl -X POST https://api.hot.dev/v1/events \
  -H "Authorization: Bearer $HOT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "event_type": "user:created",
    "event_data": {"id": "usr_12345", "email": "alice@example.com"}
  }'

From External Systems (Webhooks): Configure webhooks to forward events from services like Stripe, GitHub, or Slack directly to Hot.

Event Handlers

Define handlers using the on-event metadata:

::myapp::notifications ns

// Handle a specific event type
on-user-created meta {on-event: "user:created"}
fn (event) {
  send-welcome-email(event.data.email)
}

An event may match zero, one, or multiple handlers. Each selected handler invocation is recorded as its own run in the event's stream.

Event Delivery

Hot guarantees at-least-once delivery for events:

  • Events are persisted before acknowledgment
  • Failed handlers can be retried automatically with configurable attempts and delay
  • Retry status is visible in the Hot App UI

Delivery is optimized for durability and throughput, not strict global ordering. Concurrent workers may process different events from the same stream at the same time, and retries or infrastructure redelivery can arrive after newer events. Queue message fields are additive so rolling deploys can read older messages; workers hydrate the authoritative event payload from the database before routing.

When a worker stops while it runs an event (it crashes or is killed), the next worker runs each event that was in flight on it alone, with no other event beside it, so one event that brings workers down can't take the others with it. With the SQLite queue, only such a stop, of an event running alone, counts toward the event's retry limit, and a worker restarted on the same host takes over the events of the one that stopped at once. An event that stops its worker each time it runs alone is dead-lettered, and its runs fail with that reason. If a handler's setup fails before it starts (its bundle can't be downloaded, extracted or compiled), the event is delivered again, and its run waits as pending_retry with the setup error until the handler starts or the event's retries run out.

Handlers should be idempotent when they perform external side effects, because the same event can be delivered more than once after a retry, worker crash, Redis pending-entry reclaim, or task reconciliation pass. This also applies to run timeouts: when a handler exceeds its run timeout it is recorded as a failure and retried according to its retry policy. The worker cancels the timed-out run cooperatively, but a handler stuck in non-cooperative work (a tight native loop or blocking syscall) can keep running in the background while its retry begins, so the two attempts may briefly overlap.

Streams

Streams are the correlation boundary for platform work. Related events, runs, retries, and tasks share a stream ID, producing one end-to-end workflow history. A new externally published event creates a stream unless its request supplies an existing stream_id; events and tasks created inside running Hot code inherit the current stream.

The same stream ID is also a live delivery channel. Clients can subscribe to run lifecycle notifications and data emitted with ::hot::stream/data. User-emitted stream data is ephemeral and is not persisted with the durable event, run, and task records.

Use Cases

  • Workflow lineage - Trace related events, runs, retries, and tasks
  • AI/LLM Responses - Stream tokens as they're generated
  • Live Updates - Push data to clients in real-time
  • Long-Running Operations - Report progress incrementally
  • Bidirectional Communication - WebSocket-style interactions

Server-Sent Events (SSE)

Stream data to clients in real-time using ::hot::stream/data.

Hot code — emit chunks as they arrive:

::messages ::anthropic::messages

handle-chat
meta { on-event: "chat:message" }
fn (event) {
  // Call a streaming AI API (requires the hot.dev/anthropic package)
  request ::messages/MessagesPostRequest({
    model: "claude-sonnet-4-20250514",
    max_tokens: 4096,
    messages: [{role: "user", content: event.data.message}]
  })
  response ::messages/post-stream(request)

  // Emit each non-empty text delta to the client in real time
  reduce(response.body, (acc, chunk) {
    delta chunk.data.delta.text
    cond {
      delta => {
        ::hot::stream/data("ai:delta", {text: delta})
        concat(acc, delta)
      }
      => { acc }
    }
  }, "")
}

JavaScript client (subscribe and publish in one request):

// POST /v1/streams/subscribe-with-event opens the subscription first and
// then publishes the event, so no stream:data is missed.
const response = await fetch('/v1/streams/subscribe-with-event', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${API_KEY}`,
    'Content-Type': 'application/json',
    'Accept': 'text/event-stream'
  },
  body: JSON.stringify({
    event_type: 'chat:message',
    event_data: { message: 'Hello!' }
    // stream_id: existingStreamId   // optional: continue an existing stream
  })
});

const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';

while (true) {
  const { done, value } = await reader.read();
  if (done) break;

  // Parse SSE events (data: {...}\n\n format); a chunk can end mid-line
  buffer += decoder.decode(value, { stream: true });
  const lines = buffer.split('\n');
  buffer = lines.pop();
  for (const line of lines) {
    if (line.startsWith('data: ')) {
      const event = JSON.parse(line.slice(6));
      if (event.type === 'event:published') {
        // Always the first event: { event_id, stream_id, event_type }
        console.log('Stream:', event.stream_id);
      }
      if (event.type === 'stream:data' && event.data_type === 'ai:delta') {
        // Real-time chunk from ::hot::stream/data
        appendToResponse(event.payload.text);
      }
      if (event.type === 'run:stop') {
        // Run completed
        console.log('Final result:', event.run.result);
      }
    }
  }
}

The request body takes event_type, event_data and an optional stream_id. The response is the event stream itself. Its first event is event:published, followed by run:start, stream:data, run:stop, run:fail, run:cancel and task:update as they happen. The connection stays open for up to 5 minutes and then ends with stream:complete. See Subscribe with Event in the API reference.

Don't publish with POST /v1/events and then subscribe to /v1/streams/{stream_id}/subscribe when you need the stream data. That subscription delivers only the stream:data emitted after it opens, and data is ephemeral, so whatever the handler emitted first is lost. Use the separate subscribe endpoint to follow a stream that is already running.

Subscription States

Live stream subscription lifecycle An open subscription becomes active, then either closes normally or enters an error state. open connection established subscribed active receiving live events complete failure closed normal completion error connection interrupted

The subscription lifecycle is distinct from the durable stream record. Closing a client connection does not delete the events, runs, or tasks correlated by the stream ID.

Viewing Streams

The Streams page in the Hot App lists the environment's streams, newest first, and can be searched by stream ID. Each row shows:

  • Stream ID, linked to the stream's page
  • Context: the stream's latest event type and latest run function
  • Start and Last Activity times
  • Duration
  • Runs and Events counts
  • Project

A stream's page shows the same details with a graph of the stream and its runs, events, and tasks. Live subscriber connections aren't listed.

Monitoring

All runs, events, tasks, and streams are visible in the Hot App with:

  • Real-time updates as executions happen
  • Filtering by status, function, event type
  • Full-text search across payloads
  • Detailed drill-down views