Workers for Agents in TypeScript: Patterns That Hold Up in Production

Workers for Agents in TypeScript: Patterns That Hold Up in Production

The 60-second version

Workers reward a specific style of TypeScript: small, single-purpose, structured-input-and-output, well-typed. The constraints (30 seconds, 128MB, no state) push you toward this style automatically. Workers that hold up in production share patterns: typed input/output schemas, defensive HTTP calls with timeouts, structured error returns, no hidden side effects.

Five production patterns

1. Type your input and output.
Type strictly. The agent works against the schema. Schema drift breaks the agent silently.
2. Defensive HTTP with timeouts.
External API calls inside a 30-second budget need their own timeouts. A 25-second API call leaves 5 seconds for everything else. Set explicit fetch timeouts shorter than the Worker timeout.
3. Structured error returns instead of throws.
Throw inside a Worker and the agent gets opaque failure. Return structured error objects and the agent can reason about the failure and respond gracefully.
4. Idempotency where state matters.
Workers have no persistent state, but they can hit external systems that do. If the external call is non-idempotent (e.g., creates a record), include an idempotency key derived from input. Calling the Worker twice should produce one record, not two.
5. Approved domains as a deployment artifact.
Track domain approvals in code. When a Worker stops working in production, “did the approved domains change” is the first thing to check.

Three production failures to design around

1. The 30-second wall. Aim for under 5 seconds typical, under 15 worst case. Long calls fail under retry loads.
2. Silent domain blocks. A Worker calling a non-approved domain fails with an error that isn’t always obvious. Log every outbound destination.
3. Memory leaks via large responses. Don’t pull a 50MB JSON response into a 128MB Worker. Stream, paginate, or pre-filter at the source.

Testing strategy

Unit-test the Worker logic separately from the agent. Use mock HTTP. Then integration-test with the actual agent calling the Worker. The two test layers catch different bugs.

What to read next

Workers + External APIs, Notion AI Meets MCP, Workers for Agents foundation piece, Security Posture.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *