Skip to main content
Tasks are the fundamental unit of work in Hyrex. They are TypeScript functions that can be executed asynchronously by workers, with automatic retry handling, monitoring, and durability.

Basic Task Definition

Define a task using the hy.task() method:
Tasks can accept either zero arguments or one JSON-serializable argument. The return value must also be JSON-serializable or void.

Task Configuration

Configure task behavior with the config object:

Configuration Options

  • queue: Route tasks to specific worker pools (default: “default”)
  • maxRetries: Number of retry attempts on failure (0-10, default: 3)
  • timeoutSeconds: Maximum execution time before timeout
  • priority: Task priority from 1-10 (default: 3)
  • cron: Cron expression for scheduled tasks
  • idempotencyKey: Unique key to prevent duplicate task executions

Sending Tasks

Queue tasks for asynchronous execution:

Task Context

Access metadata about the current task execution:

Context Properties

  • taskId: Unique identifier for the task
  • durableId: Persistent identifier for durable task storage
  • rootId: ID of the root task in the task tree
  • parentId: ID of the parent task (null if root)
  • workflowRunId: ID of the workflow run (if part of workflow)
  • taskName: Name of the task being executed
  • queue: Queue name where task is processed
  • priority: Task priority level
  • attemptNumber: Current attempt number (0-based)
  • maxRetries: Maximum retry attempts configured
  • timeoutSeconds: Timeout configuration
  • executorId: ID of the executor processing this task

Error Handling

Tasks can throw errors to trigger retries:

Retry Behavior

  • Throwing any exception triggers a retry (if retries remain)
  • Return a value to complete the task (even with errors)
  • Retries use exponential backoff by default

Input Validation

Use Zod schemas for type-safe input validation:

Task Results

The send() method returns a task ID immediately:

Best Practices

  1. Use Type-Safe Interfaces
  2. Set Appropriate Timeouts
  3. Design for Idempotency
  4. Handle Errors Gracefully

Next Steps

Workflows

Orchestrate multiple tasks

Queues

Route tasks to worker pools

Retries

Configure retry strategies