# Func Timeouts and SSE Streaming | Creght API for AI

> Timeouts and streaming in Creght Func: where timeoutMs belongs, the 300-second execution cap and result-size limit, how to diagnose context deadline exceeded, and the full native fetch + SSE parsing implementation.

[![Creght](https://ugc.talizen.com/_assets/site/2061660904709165056/1780797461299__creght_logo.png)API for AI](/)

[View llms.txt](/llms.txt)

Overview

- [Creght API for AI](/api.md)

Discoverability

- [How to optimize llms.txt](/api/optimize-llms-txt.md)

Site configuration

- [Implement domain-based locale routing](/api/domain-locale-routing.md)

Backend

- [Calling external APIs on the server and managing the cache](/api/ssr-external-api-cache.md)
- [Build site backend workflows with Func](/api/func-backend.md)
- [JSON tables: definition, reads, and queries](/api/func-json-tables.md)
- [Uploads: signed direct upload and Func-generated files](/api/func-assets-upload.md)
- [Timeouts and streaming responses](/api/func-timeout-streaming.md)
- [Integrate Alipay PC Web Payment with Func](/api/func-alipay-payment.md)

Integrations

- [Send Email and Verification Codes with Integrations](/api/func-email-integration.md)
- [Take Alipay payments with an integration](/api/func-alipay-integration.md)

Auth

- [Require a Verified Email to Sign Up](/api/auth-verified-registration.md)
- [Reset and Change Passwords](/api/auth-password-reset.md)
- [Sign In From a Func](/api/auth-func-login.md)
- [Query users from a Func](/api/func-user-directory.md)

On this page

- [Timeout configuration](#timeout)
- [Diagnosing context deadline exceeded](#diagnosis)
- [Native Fetch + SSE streaming](#streaming)
- [Streaming is not a background job](#not-background)
- [Acceptance checklist](#checklist)

Backend/Timeouts and streaming responses

# Timeouts and streaming responses

invoke defaults to 5 seconds, execution caps at 300, and results cap near 1 MiB — which limit a long task actually hits, and the order in which to diagnose context deadline exceeded. Includes the complete ctx.sse.send plus native Fetch parsing loop, and where streaming stops being the answer.

Copy Markdown link

An ordinary `invoke()` waits for one complete JSON result and times out after **5 seconds by default**. Model generation, slow third-party APIs, and anything that should appear while it is being produced all run into that line. This page covers two things: putting the timeout in the right place, and using native Fetch plus SSE for bounded incremental output.

**Agent objective**

The timeout is a **caller-side** parameter: set it from the real duration of the work and verify it on the real page path. Stream incremental output with `ctx.sse.send` plus native `fetch`, and never invent detached background work.

## Timeout configuration

`invoke` defaults to **5 seconds**; the Func runner's default maximum execution time is **300 seconds**. A bounded model generation or upstream request may set a longer caller timeout. This does not enable detached background work.

```typescript
const result = await invoke('image.generate', input, {
  timeoutMs: 120000,
})
```

Several hard limits apply at the same time and do not move when you raise the timeout:

| Limit | Value |
| --- | --- |
| `invoke` default timeout | 5 seconds, overridden by the caller's `timeoutMs` |
| Maximum execution time | 300 seconds |
| Func result size | About 1 MiB; exceeding it fails the call — the first wall you hit when returning a whole table |
| Func code size | About 256 KiB |

### Diagnosing context deadline exceeded

For `context deadline exceeded` or `context timeout`, do these three things in order:

1. Inspect the actual `invoke(..., { timeoutMs })` value in the page. This is almost always where the problem is — the caller is still on the 5-second default.
2. Retry the same input and model with a larger timeout. `creght func run --timeout_ms` / `run_func.timeout_ms` **affects that self-test only**: passing there does not prove the production path passes, and failing there does not prove a platform hard limit.
3. If the larger value succeeds, raise the production caller's `timeoutMs` and verify the complete path in the real page.

> Do not treat shorter output, a lower `max_tokens`, a different model or provider, a new table, or a fake background job as the timeout fix. Each of those changes the feature, when the actual problem is one number set too low.

## Native Fetch + SSE streaming

For bounded incremental output, send events with `ctx.sse.send` and read them in the browser with native `fetch` and `ReadableStream`. **No `invokeStream` wrapper is required.**

```typescript
// /backend/func/writer.ts
export async function main(input, ctx) {
  ctx.sse.send('token', { text: 'Hello' })
  ctx.sse.send('token', { text: ' world' })
  return { ok: true }
}
```

The browser parses SSE frames itself. The key point is that `reader.read()` yields **arbitrary byte chunks** — a chunk is not guaranteed to be one event:

```typescript
const response = await fetch('/func/writer?stream=1&timeout_ms=120000', {
  method: 'POST',
  headers: {
    Accept: 'text/event-stream',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(input),
})
if (!response.ok || !response.body) throw new Error('Func stream failed')

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

while (true) {
  const { done, value } = await reader.read()
  if (done) break
  buffer += decoder.decode(value, { stream: true })

  const frames = buffer.split(/\r?\n\r?\n/)
  buffer = frames.pop() || ''
  for (const frame of frames) {
    const event = frame.match(/^event:\s*(.+)$/m)?.[1]
    const data = frame.match(/^data:\s*(.+)$/m)?.[1]
    if (event === 'token' && data) {
      output += JSON.parse(data).text
    }
  }
}
```

- You must **buffer across reads** and split frames only on a blank line, keeping the trailing partial frame for the next chunk.
- Streaming is selected by `?stream=1&timeout_ms=...` on the URL, not by an `invoke()` option.
- The platform sends the final `done` or `error` event; handle both.
- **Cookies cannot change after the first event** — headers are already committed. Anything that sets a session or cookie must happen before the first `send`.
- The call timeout still applies. Streaming is not an unbounded stream.

## Streaming is not a background job

SSE lets the user see progress sooner, but the output still belongs to **one request**. Func cannot continue after the request ends: there is no `setTimeout`/ `setInterval`, no job queue, and no "return now and finish later".

If the work genuinely exceeds 300 seconds, split it into steps the user can see: each step is one bounded call, intermediate state lives in a [JSON table](/api/func-json-tables.md), and the page drives the next step — instead of leaving one call hanging.

## Acceptance checklist

- Long-running calls set a `timeoutMs` matching the real duration in the production page, verified on the real path.
- Results carry no bulk payload and stay well below the 1 MiB limit.
- SSE parsing buffers across reads, splits on blank lines, and handles `done` and `error`.
- Any cookie-setting logic completes before the first SSE event.
- No timers, polling, or fake background jobs are used to work around a timeout.

**Completion criteria**

The timeout comes from a judgement about how long the work takes rather than trial and error, streaming is exercised end to end on a real page for the first, intermediate, and final events, and a timeout failure leaves the page in a clear user-visible state.

![Creght](https://ugc.talizen.com/_assets/site/2061660904709165056/1780797461299__creght_logo.png)

This website is built with [Creght](/)

[Discord](https://discord.gg/Qvq2nmZNnb)

## Links

- [Pricing](/price.md)
- [Solutions](/solution.md)
- [Customers](/customers.md)
- [Help Center](/help.md)
- [Contact Us](/contact.md)
- [Update Logs & Blogs](/blogs.md)
- [Refund Policy](/tuikuan.md)

## Resources

- [All Resources](/resources.md)
- [Templates](/templates.md)
- [Components](https://creghtlib.site.creght.com)
- [Animations](/design/effects.md)
- [Figma to Creght](/figma2creght.md)
- [API for AI](/api.md)

## Terms

- [Terms of Service](/legal/terms.md)
- [Privacy Policy](/legal/privacy.md)
- [Acceptable Use Policy](/legal/acceptable-use.md)

## Social Media

- [Twitter](https://twitter.com)
- [Facebook](https://www.facebook.com)
- [LinkedIn](https://www.linkedin.com)

[蜀ICP备2023038192号-2](https://beian.miit.gov.cn)
