Skip to main content

Overview

Task types define the structures for task distribution, polling, and completion in Cadence. Tasks are the fundamental unit of work dispatched to workers. Source Locations:
  • common/types/shared.go - Common task types
  • common/types/matching.go - Matching service task types

Task List Types

TaskList

Identifies a task list for task distribution.
type TaskList struct {
    Name string
    Kind *TaskListKind
}
Name
string
required
Name of the task list. Must be unique within a domain.
Kind
TaskListKind
Kind of task list (Normal or Sticky)
Naming Best Practices:
  • Use descriptive names: order-processing, payment-verification
  • Include worker capabilities: gpu-tasks, high-memory-tasks
  • Avoid special characters except hyphens and underscores

TaskListKind

Type of task list.
type TaskListKind int32

const (
    TaskListKindNormal TaskListKind = iota
    TaskListKindSticky
)
Normal
int32
default:"0"
Regular task list for general task distribution
Sticky
int32
default:"1"
Sticky task list for routing to specific worker (decision tasks only)
Sticky Task Lists:
  • Keep workflow state cached in worker memory
  • Reduce history loading overhead
  • Improve decision task latency by ~90%
  • Automatically fall back to normal task list if worker unavailable

TaskListType

Type of tasks in a task list.
type TaskListType int32

const (
    TaskListTypeDecision TaskListType = iota
    TaskListTypeActivity
)
Decision
int32
default:"0"
Task list for decision tasks
Activity
int32
default:"1"
Task list for activity tasks

TaskListMetadata

Metadata for task list routing.
type TaskListMetadata struct {
    MaxTasksPerSecond *float64
}
MaxTasksPerSecond
float64
Rate limit for task dispatch from this task list

TaskListStatus

Status information for a task list.
type TaskListStatus struct {
    BacklogCountHint int64
    ReadLevel        int64
    AckLevel         int64
    RatePerSecond    float64
    TaskIDBlock      *TaskIDBlock
}
BacklogCountHint
int64
Approximate number of pending tasks in backlog
ReadLevel
int64
Current read position in task queue
AckLevel
int64
Last acknowledged task ID
RatePerSecond
float64
Current task dispatch rate
TaskIDBlock
TaskIDBlock
Current task ID allocation range

TaskIDBlock

Range of task IDs allocated to a task list.
type TaskIDBlock struct {
    StartID int64
    EndID   int64
}

Task List Partition Types

TaskListPartitionMetadata

Metadata for a task list partition.
type TaskListPartitionMetadata struct {
    Key          string
    OwnerHostName string
}
Key
string
Partition identifier
OwnerHostName
string
Host currently owning this partition

TaskListPartitionConfig

Configuration for task list partitioning.
type TaskListPartitionConfig struct {
    Version            int32
    NumReadPartitions  int32
    NumWritePartitions int32
}
Version
int32
required
Configuration version for optimistic concurrency
NumReadPartitions
int32
required
Number of partitions for task polling
NumWritePartitions
int32
required
Number of partitions for task addition
Partitioning Strategy:
  • Start with 1 partition (no partitioning)
  • Scale to 4-8 partitions for high throughput
  • Use 16+ partitions for very high scale (>1000 tasks/sec)

Decision Task Types

PollForDecisionTaskRequest

Request to poll for a decision task.
type PollForDecisionTaskRequest struct {
    Domain         string
    TaskList       *TaskList
    Identity       string
    BinaryChecksum string
}
Domain
string
required
Domain to poll from
TaskList
TaskList
required
Task list to poll
Identity
string
Worker identity (typically hostname and process ID)
BinaryChecksum
string
Checksum of worker binary for bad binary detection

PollForDecisionTaskResponse

Response containing a decision task.
type PollForDecisionTaskResponse struct {
    TaskToken                       []byte
    WorkflowExecution               *WorkflowExecution
    WorkflowType                    *WorkflowType
    PreviousStartedEventID          *int64
    StartedEventID                  int64
    Attempt                         int64
    BacklogCountHint                int64
    History                         *History
    NextPageToken                   []byte
    Query                           *WorkflowQuery
    WorkflowExecutionTaskList       *TaskList
    ScheduledTimestamp              *int64
    StartedTimestamp                *int64
    Queries                         map[string]*WorkflowQuery
    NextEventID                     int64
}
TaskToken
[]byte
Opaque token for completing/failing the task
WorkflowExecution
WorkflowExecution
Workflow execution this task belongs to
WorkflowType
WorkflowType
The workflow type
PreviousStartedEventID
int64
Event ID of previous decision task (for incremental history)
StartedEventID
int64
Event ID when this decision task started
Attempt
int64
Retry attempt number for this decision task
BacklogCountHint
int64
Approximate task backlog size
History
History
Workflow execution history (full or incremental)
NextPageToken
[]byte
Token to fetch additional history if paginated
Query
WorkflowQuery
Workflow query to answer (deprecated, use Queries)
Queries
map[string]WorkflowQuery
Map of query ID to workflow query
WorkflowExecutionTaskList
TaskList
Normal (non-sticky) task list for the workflow
NextEventID
int64
Next event ID to be assigned
Empty Response: If no task is available within poll timeout, returns empty response (all fields nil/zero).

RespondDecisionTaskCompletedRequest

Request to complete a decision task.
type RespondDecisionTaskCompletedRequest struct {
    TaskToken                  []byte
    Decisions                  []*Decision
    ExecutionContext           []byte
    Identity                   string
    StickyAttributes           *StickyExecutionAttributes
    ReturnNewDecisionTask      bool
    ForceCreateNewDecisionTask bool
    BinaryChecksum             string
    QueryResults               map[string]*WorkflowQueryResult
}
TaskToken
[]byte
required
Task token from poll response
Decisions
[]Decision
List of decisions to execute
ExecutionContext
[]byte
Opaque execution context to persist
Identity
string
Worker identity
StickyAttributes
StickyExecutionAttributes
Sticky task list configuration
ReturnNewDecisionTask
boolean
Return a new decision task immediately if available
ForceCreateNewDecisionTask
boolean
Force creation of a new decision task
BinaryChecksum
string
Worker binary checksum
QueryResults
map[string]WorkflowQueryResult
Results for queries that were processed

RespondDecisionTaskCompletedResponse

Response after completing a decision task.
type RespondDecisionTaskCompletedResponse struct {
    DecisionTask                *PollForDecisionTaskResponse
    ActivitiesToDispatchLocally map[string]*ActivityLocalDispatchInfo
}
DecisionTask
PollForDecisionTaskResponse
New decision task if ReturnNewDecisionTask was true
ActivitiesToDispatchLocally
map[string]ActivityLocalDispatchInfo
Activities to execute locally (same worker)

RespondDecisionTaskFailedRequest

Request to fail a decision task.
type RespondDecisionTaskFailedRequest struct {
    TaskToken      []byte
    Cause          *DecisionTaskFailedCause
    Details        []byte
    Identity       string
    BinaryChecksum string
}
TaskToken
[]byte
required
Task token from poll response
Cause
DecisionTaskFailedCause
Reason for failure
Details
[]byte
Additional failure details
Identity
string
Worker identity

StickyExecutionAttributes

Attributes for sticky execution.
type StickyExecutionAttributes struct {
    WorkerTaskList                *TaskList
    ScheduleToStartTimeoutSeconds *int32
}
WorkerTaskList
TaskList
required
Sticky task list for this worker
ScheduleToStartTimeoutSeconds
int32
required
Timeout before falling back to normal task list (typically 5-10 seconds)

Activity Task Types

PollForActivityTaskRequest

Request to poll for an activity task.
type PollForActivityTaskRequest struct {
    Domain           string
    TaskList         *TaskList
    Identity         string
    TaskListMetadata *TaskListMetadata
}
Domain
string
required
Domain to poll from
TaskList
TaskList
required
Task list to poll
Identity
string
Worker identity
TaskListMetadata
TaskListMetadata
Metadata for task routing

PollForActivityTaskResponse

Response containing an activity task.
type PollForActivityTaskResponse struct {
    TaskToken                       []byte
    WorkflowExecution               *WorkflowExecution
    ActivityID                      string
    ActivityType                    *ActivityType
    Input                           []byte
    ScheduledTimestamp              *int64
    ScheduleToCloseTimeoutSeconds   *int32
    StartedTimestamp                *int64
    StartToCloseTimeoutSeconds      *int32
    HeartbeatTimeoutSeconds         *int32
    Attempt                         int32
    ScheduledTimestampOfThisAttempt *int64
    HeartbeatDetails                []byte
    WorkflowType                    *WorkflowType
    WorkflowDomain                  string
    Header                          *Header
}
TaskToken
[]byte
Opaque token for completing/failing the task
WorkflowExecution
WorkflowExecution
Parent workflow execution
ActivityID
string
Activity identifier within the workflow
ActivityType
ActivityType
Type of activity to execute
Input
[]byte
Serialized activity input
ScheduledTimestamp
int64
When activity was first scheduled (nanoseconds)
ScheduleToCloseTimeoutSeconds
int32
Maximum time from schedule to completion
StartedTimestamp
int64
When this attempt started
StartToCloseTimeoutSeconds
int32
Maximum time from start to completion
HeartbeatTimeoutSeconds
int32
Maximum time between heartbeats
Attempt
int32
Current retry attempt number (0-based)
ScheduledTimestampOfThisAttempt
int64
When this retry attempt was scheduled
HeartbeatDetails
[]byte
Details from last heartbeat (for resuming)
WorkflowType
WorkflowType
Parent workflow type
WorkflowDomain
string
Parent workflow domain name
Header
Header
Context propagation headers from workflow

RespondActivityTaskCompletedRequest

Request to complete an activity task.
type RespondActivityTaskCompletedRequest struct {
    TaskToken []byte
    Result    []byte
    Identity  string
}
TaskToken
[]byte
required
Task token from poll response
Result
[]byte
Serialized activity result
Identity
string
Worker identity

RespondActivityTaskCompletedByIDRequest

Complete an activity by domain, workflow ID, and activity ID.
type RespondActivityTaskCompletedByIDRequest struct {
    Domain     string
    WorkflowID string
    RunID      string
    ActivityID string
    Result     []byte
    Identity   string
}
Domain
string
required
Domain name
WorkflowID
string
required
Workflow ID
RunID
string
Run ID (optional, uses current run if omitted)
ActivityID
string
required
Activity ID
Result
[]byte
Serialized result

RespondActivityTaskFailedRequest

Request to fail an activity task.
type RespondActivityTaskFailedRequest struct {
    TaskToken []byte
    Reason    *string
    Details   []byte
    Identity  string
}
TaskToken
[]byte
required
Task token from poll response
Reason
string
Failure reason/error message
Details
[]byte
Serialized failure details

RespondActivityTaskFailedByIDRequest

Fail an activity by identifiers.
type RespondActivityTaskFailedByIDRequest struct {
    Domain     string
    WorkflowID string
    RunID      string
    ActivityID string
    Reason     *string
    Details    []byte
    Identity   string
}

RespondActivityTaskCanceledRequest

Request to cancel an activity task.
type RespondActivityTaskCanceledRequest struct {
    TaskToken []byte
    Details   []byte
    Identity  string
}
TaskToken
[]byte
required
Task token from poll response
Details
[]byte
Cancellation details

RecordActivityTaskHeartbeatRequest

Request to record an activity heartbeat.
type RecordActivityTaskHeartbeatRequest struct {
    TaskToken []byte
    Details   []byte
    Identity  string
}
TaskToken
[]byte
required
Task token from poll response
Details
[]byte
Progress details (can be used to resume on retry)
Identity
string
Worker identity

RecordActivityTaskHeartbeatResponse

Response after recording heartbeat.
type RecordActivityTaskHeartbeatResponse struct {
    CancelRequested bool
}
CancelRequested
boolean
Whether the activity has been requested to cancel

Task Source Types

TaskSource

Source of a task.
type TaskSource int32

const (
    TaskSourceHistory TaskSource = iota
    TaskSourceDbBacklog
)
History
int32
default:"0"
Task added directly from history service (sync match)
DbBacklog
int32
default:"1"
Task loaded from persistent backlog (async match)

Poller Information Types

PollerInfo

Information about an active poller.
type PollerInfo struct {
    LastAccessTime *int64
    Identity       string
    RatePerSecond  float64
}
LastAccessTime
int64
Last poll timestamp (nanoseconds)
Identity
string
Worker identity string
RatePerSecond
float64
Poll rate from this worker

Task List Description Types

DescribeTaskListRequest

Request to describe a task list.
type DescribeTaskListRequest struct {
    Domain                string
    TaskList              *TaskList
    TaskListType          *TaskListType
    IncludeTaskListStatus bool
}
Domain
string
required
Domain name
TaskList
TaskList
required
Task list to describe
TaskListType
TaskListType
required
Type (Decision or Activity)
IncludeTaskListStatus
boolean
Include detailed status information

DescribeTaskListResponse

Response with task list information.
type DescribeTaskListResponse struct {
    Pollers        []*PollerInfo
    TaskListStatus *TaskListStatus
}
Pollers
[]PollerInfo
List of active pollers
TaskListStatus
TaskListStatus
Task list status if requested

Activity Dispatch Types

ActivityLocalDispatchInfo

Information for locally dispatching an activity.
type ActivityLocalDispatchInfo struct {
    ActivityID                      string
    ScheduledTimestamp              *int64
    StartedTimestamp                *int64
    ScheduledTimestampOfThisAttempt *int64
    TaskToken                       []byte
}
ActivityID
string
Activity identifier
ScheduledTimestamp
int64
When activity was scheduled
StartedTimestamp
int64
When activity started
ScheduledTimestampOfThisAttempt
int64
When this attempt was scheduled
TaskToken
[]byte
Task token for completing the activity

ActivityTaskDispatchInfo

Detailed dispatch information for an activity.
type ActivityTaskDispatchInfo struct {
    ScheduledEvent                  *HistoryEvent
    StartedTimestamp                *int64
    Attempt                         *int64
    ScheduledTimestampOfThisAttempt *int64
    HeartbeatDetails                []byte
    WorkflowType                    *WorkflowType
    WorkflowDomain                  string
}

Best Practices

Task List Design

  1. Naming Strategy
    • One task list per worker type
    • Separate decision and activity task lists
    • Use descriptive names: order-processing-activities
  2. Partitioning
    • Start with no partitioning
    • Add partitions when >100 tasks/sec
    • Monitor backlog and adjust
  3. Sticky Execution
    • Always enable for decision tasks
    • Use 5-10 second sticky timeout
    • Monitor fallback rate

Polling Best Practices

  1. Poll Timeout
    • Set context timeout: 60-90 seconds
    • Handle empty responses gracefully
    • Implement exponential backoff on errors
  2. Worker Identity
    • Include hostname and process ID
    • Add version information
    • Use for debugging and monitoring
  3. Concurrency
    • Start with 10-20 pollers per worker
    • Scale based on task throughput
    • Monitor task latency

Task Completion

  1. Idempotency
    • Task tokens ensure idempotency
    • Safe to retry completion
    • Handle duplicate completion gracefully
  2. Timeouts
    • Set appropriate activity timeouts
    • Use heartbeat for long tasks (>30 sec)
    • Record progress in heartbeat details
  3. Error Handling
    • Return structured errors
    • Use retry policies appropriately
    • Log task failures

Heartbeat Strategy

  1. Frequency
    • Heartbeat at 1/3 of timeout
    • Example: 30s timeout → 10s heartbeat
    • Reduce frequency for stable tasks
  2. Progress Tracking
    • Store resumable state in details
    • Use for retry recovery
    • Keep details small (less than 32KB)
  3. Cancellation Check
    • Check CancelRequested in response
    • Cleanup and exit if canceled
    • Record final state in cancellation details

Monitoring & Metrics

Key Metrics

  • task.poll.latency: Time to receive task
  • task.execution.latency: Task processing time
  • task.backlog.size: Pending task count
  • task.sync.match.rate: Sync match success rate
  • poller.count: Active poller count

Health Indicators

  • High sync match rate (>90%): Healthy
  • Growing backlog: Need more workers
  • High poll latency: Reduce poll timeout or add partitions
  • Low poller count: Workers may be down

See Also

Build docs developers (and LLMs) love